babylon.viewer.max.js 5.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. if(typeof exports === 'object' && typeof module === 'object') {
  4. module.exports = factory();
  5. } else if(typeof define === 'function' && define.amd) {
  6. define("babylonjs-viewer", amdDependencies, factory);
  7. } else if(typeof exports === 'object') {
  8. exports["babylonjs-viewer"] = factory();
  9. } else {
  10. root["BabylonViewer"] = factory();
  11. }
  12. })(this, function() {
  13. var BabylonViewer =
  14. /******/ (function(modules) { // webpackBootstrap
  15. /******/ // The module cache
  16. /******/ var installedModules = {};
  17. /******/
  18. /******/ // The require function
  19. /******/ function __webpack_require__(moduleId) {
  20. /******/
  21. /******/ // Check if module is in cache
  22. /******/ if(installedModules[moduleId]) {
  23. /******/ return installedModules[moduleId].exports;
  24. /******/ }
  25. /******/ // Create a new module (and put it into the cache)
  26. /******/ var module = installedModules[moduleId] = {
  27. /******/ i: moduleId,
  28. /******/ l: false,
  29. /******/ exports: {}
  30. /******/ };
  31. /******/
  32. /******/ // Execute the module function
  33. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  34. /******/
  35. /******/ // Flag the module as loaded
  36. /******/ module.l = true;
  37. /******/
  38. /******/ // Return the exports of the module
  39. /******/ return module.exports;
  40. /******/ }
  41. /******/
  42. /******/
  43. /******/ // expose the modules object (__webpack_modules__)
  44. /******/ __webpack_require__.m = modules;
  45. /******/
  46. /******/ // expose the module cache
  47. /******/ __webpack_require__.c = installedModules;
  48. /******/
  49. /******/ // define getter function for harmony exports
  50. /******/ __webpack_require__.d = function(exports, name, getter) {
  51. /******/ if(!__webpack_require__.o(exports, name)) {
  52. /******/ Object.defineProperty(exports, name, {
  53. /******/ configurable: false,
  54. /******/ enumerable: true,
  55. /******/ get: getter
  56. /******/ });
  57. /******/ }
  58. /******/ };
  59. /******/
  60. /******/ // getDefaultExport function for compatibility with non-harmony modules
  61. /******/ __webpack_require__.n = function(module) {
  62. /******/ var getter = module && module.__esModule ?
  63. /******/ function getDefault() { return module['default']; } :
  64. /******/ function getModuleExports() { return module; };
  65. /******/ __webpack_require__.d(getter, 'a', getter);
  66. /******/ return getter;
  67. /******/ };
  68. /******/
  69. /******/ // Object.prototype.hasOwnProperty.call
  70. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  71. /******/
  72. /******/ // __webpack_public_path__
  73. /******/ __webpack_require__.p = "";
  74. /******/
  75. /******/ // Load entry module and return exports
  76. /******/ return __webpack_require__(__webpack_require__.s = 15);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {
  83. (function universalModuleDefinition(root, factory) {
  84. var amdDependencies = [];
  85. var CANNON = root.CANNON || this.CANNON;
  86. var OIMO = root.OIMO || this.OIMO;
  87. var earcut = root.earcut || this.earcut;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(18); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(19); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(20); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = function (right) {
  1980. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1981. };
  1982. /**
  1983. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. this.x = x;
  2299. this.y = y;
  2300. }
  2301. /**
  2302. * Gets a string with the Vector2 coordinates
  2303. * @returns a string with the Vector2 coordinates
  2304. */
  2305. Vector2.prototype.toString = function () {
  2306. return "{X: " + this.x + " Y:" + this.y + "}";
  2307. };
  2308. /**
  2309. * Gets class name
  2310. * @returns the string "Vector2"
  2311. */
  2312. Vector2.prototype.getClassName = function () {
  2313. return "Vector2";
  2314. };
  2315. /**
  2316. * Gets current vector hash code
  2317. * @returns the Vector2 hash code as a number
  2318. */
  2319. Vector2.prototype.getHashCode = function () {
  2320. var hash = this.x || 0;
  2321. hash = (hash * 397) ^ (this.y || 0);
  2322. return hash;
  2323. };
  2324. // Operators
  2325. /**
  2326. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2327. * @param array defines the source array
  2328. * @param index defines the offset in source array
  2329. * @returns the current Vector2
  2330. */
  2331. Vector2.prototype.toArray = function (array, index) {
  2332. if (index === void 0) { index = 0; }
  2333. array[index] = this.x;
  2334. array[index + 1] = this.y;
  2335. return this;
  2336. };
  2337. /**
  2338. * Copy the current vector to an array
  2339. * @returns a new array with 2 elements: the Vector2 coordinates.
  2340. */
  2341. Vector2.prototype.asArray = function () {
  2342. var result = new Array();
  2343. this.toArray(result, 0);
  2344. return result;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2348. * @param source defines the source Vector2
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.copyFrom = function (source) {
  2352. this.x = source.x;
  2353. this.y = source.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Sets the Vector2 coordinates with the given floats
  2358. * @param x defines the first coordinate
  2359. * @param y defines the second coordinate
  2360. * @returns the current updated Vector2
  2361. */
  2362. Vector2.prototype.copyFromFloats = function (x, y) {
  2363. this.x = x;
  2364. this.y = y;
  2365. return this;
  2366. };
  2367. /**
  2368. * Sets the Vector2 coordinates with the given floats
  2369. * @param x defines the first coordinate
  2370. * @param y defines the second coordinate
  2371. * @returns the current updated Vector2
  2372. */
  2373. Vector2.prototype.set = function (x, y) {
  2374. return this.copyFromFloats(x, y);
  2375. };
  2376. /**
  2377. * Add another vector with the current one
  2378. * @param otherVector defines the other vector
  2379. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2380. */
  2381. Vector2.prototype.add = function (otherVector) {
  2382. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2383. };
  2384. /**
  2385. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2386. * @param otherVector defines the other vector
  2387. * @param result defines the target vector
  2388. * @returns the unmodified current Vector2
  2389. */
  2390. Vector2.prototype.addToRef = function (otherVector, result) {
  2391. result.x = this.x + otherVector.x;
  2392. result.y = this.y + otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns the current updated Vector2
  2399. */
  2400. Vector2.prototype.addInPlace = function (otherVector) {
  2401. this.x += otherVector.x;
  2402. this.y += otherVector.y;
  2403. return this;
  2404. };
  2405. /**
  2406. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2407. * @param otherVector defines the other vector
  2408. * @returns a new Vector2
  2409. */
  2410. Vector2.prototype.addVector3 = function (otherVector) {
  2411. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2412. };
  2413. /**
  2414. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2415. * @param otherVector defines the other vector
  2416. * @returns a new Vector2
  2417. */
  2418. Vector2.prototype.subtract = function (otherVector) {
  2419. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2420. };
  2421. /**
  2422. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2423. * @param otherVector defines the other vector
  2424. * @param result defines the target vector
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2428. result.x = this.x - otherVector.x;
  2429. result.y = this.y - otherVector.y;
  2430. return this;
  2431. };
  2432. /**
  2433. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2434. * @param otherVector defines the other vector
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.subtractInPlace = function (otherVector) {
  2438. this.x -= otherVector.x;
  2439. this.y -= otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Multiplies in place the current Vector2 coordinates by the given ones
  2444. * @param otherVector defines the other vector
  2445. * @returns the current updated Vector2
  2446. */
  2447. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2448. this.x *= otherVector.x;
  2449. this.y *= otherVector.y;
  2450. return this;
  2451. };
  2452. /**
  2453. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2454. * @param otherVector defines the other vector
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.multiply = function (otherVector) {
  2458. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2459. };
  2460. /**
  2461. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2462. * @param otherVector defines the other vector
  2463. * @param result defines the target vector
  2464. * @returns the unmodified current Vector2
  2465. */
  2466. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2467. result.x = this.x * otherVector.x;
  2468. result.y = this.y * otherVector.y;
  2469. return this;
  2470. };
  2471. /**
  2472. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2473. * @param x defines the first coordinate
  2474. * @param y defines the second coordinate
  2475. * @returns a new Vector2
  2476. */
  2477. Vector2.prototype.multiplyByFloats = function (x, y) {
  2478. return new Vector2(this.x * x, this.y * y);
  2479. };
  2480. /**
  2481. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2482. * @param otherVector defines the other vector
  2483. * @returns a new Vector2
  2484. */
  2485. Vector2.prototype.divide = function (otherVector) {
  2486. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2487. };
  2488. /**
  2489. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2490. * @param otherVector defines the other vector
  2491. * @param result defines the target vector
  2492. * @returns the unmodified current Vector2
  2493. */
  2494. Vector2.prototype.divideToRef = function (otherVector, result) {
  2495. result.x = this.x / otherVector.x;
  2496. result.y = this.y / otherVector.y;
  2497. return this;
  2498. };
  2499. /**
  2500. * Divides the current Vector3 coordinates by the given ones
  2501. * @param otherVector defines the other vector
  2502. * @returns the current updated Vector2
  2503. */
  2504. Vector2.prototype.divideInPlace = function (otherVector) {
  2505. return this.divideToRef(otherVector, this);
  2506. };
  2507. /**
  2508. * Gets a new Vector2 with current Vector2 negated coordinates
  2509. * @returns a new Vector2
  2510. */
  2511. Vector2.prototype.negate = function () {
  2512. return new Vector2(-this.x, -this.y);
  2513. };
  2514. /**
  2515. * Multiply the Vector2 coordinates by scale
  2516. * @param scale defines the scaling factor
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.scaleInPlace = function (scale) {
  2520. this.x *= scale;
  2521. this.y *= scale;
  2522. return this;
  2523. };
  2524. /**
  2525. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2526. * @param scale defines the scaling factor
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.prototype.scale = function (scale) {
  2530. var result = new Vector2(0, 0);
  2531. this.scaleToRef(scale, result);
  2532. return result;
  2533. };
  2534. /**
  2535. * Scale the current Vector2 values by a factor to a given Vector2
  2536. * @param scale defines the scale factor
  2537. * @param result defines the Vector2 object where to store the result
  2538. * @returns the unmodified current Vector2
  2539. */
  2540. Vector2.prototype.scaleToRef = function (scale, result) {
  2541. result.x = this.x * scale;
  2542. result.y = this.y * scale;
  2543. return this;
  2544. };
  2545. /**
  2546. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2547. * @param scale defines the scale factor
  2548. * @param result defines the Vector2 object where to store the result
  2549. * @returns the unmodified current Vector2
  2550. */
  2551. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2552. result.x += this.x * scale;
  2553. result.y += this.y * scale;
  2554. return this;
  2555. };
  2556. /**
  2557. * Gets a boolean if two vectors are equals
  2558. * @param otherVector defines the other vector
  2559. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2560. */
  2561. Vector2.prototype.equals = function (otherVector) {
  2562. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2563. };
  2564. /**
  2565. * Gets a boolean if two vectors are equals (using an epsilon value)
  2566. * @param otherVector defines the other vector
  2567. * @param epsilon defines the minimal distance to consider equality
  2568. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2569. */
  2570. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2571. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2572. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2573. };
  2574. // Properties
  2575. /**
  2576. * Gets the length of the vector
  2577. * @returns the vector length (float)
  2578. */
  2579. Vector2.prototype.length = function () {
  2580. return Math.sqrt(this.x * this.x + this.y * this.y);
  2581. };
  2582. /**
  2583. * Gets the vector squared length
  2584. * @returns the vector squared length (float)
  2585. */
  2586. Vector2.prototype.lengthSquared = function () {
  2587. return (this.x * this.x + this.y * this.y);
  2588. };
  2589. // Methods
  2590. /**
  2591. * Normalize the vector
  2592. * @returns the current updated Vector2
  2593. */
  2594. Vector2.prototype.normalize = function () {
  2595. var len = this.length();
  2596. if (len === 0)
  2597. return this;
  2598. var num = 1.0 / len;
  2599. this.x *= num;
  2600. this.y *= num;
  2601. return this;
  2602. };
  2603. /**
  2604. * Gets a new Vector2 copied from the Vector2
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.prototype.clone = function () {
  2608. return new Vector2(this.x, this.y);
  2609. };
  2610. // Statics
  2611. /**
  2612. * Gets a new Vector2(0, 0)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.Zero = function () {
  2616. return new Vector2(0, 0);
  2617. };
  2618. /**
  2619. * Gets a new Vector2(1, 1)
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.One = function () {
  2623. return new Vector2(1, 1);
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set from the given index element of the given array
  2627. * @param array defines the data source
  2628. * @param offset defines the offset in the data source
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.FromArray = function (array, offset) {
  2632. if (offset === void 0) { offset = 0; }
  2633. return new Vector2(array[offset], array[offset + 1]);
  2634. };
  2635. /**
  2636. * Sets "result" from the given index element of the given array
  2637. * @param array defines the data source
  2638. * @param offset defines the offset in the data source
  2639. * @param result defines the target vector
  2640. */
  2641. Vector2.FromArrayToRef = function (array, offset, result) {
  2642. result.x = array[offset];
  2643. result.y = array[offset + 1];
  2644. };
  2645. /**
  2646. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2647. * @param value1 defines 1st point of control
  2648. * @param value2 defines 2nd point of control
  2649. * @param value3 defines 3rd point of control
  2650. * @param value4 defines 4th point of control
  2651. * @param amount defines the interpolation factor
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2655. var squared = amount * amount;
  2656. var cubed = amount * squared;
  2657. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2658. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2659. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2660. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2661. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2662. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2667. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2668. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2669. * @param value defines the value to clamp
  2670. * @param min defines the lower limit
  2671. * @param max defines the upper limit
  2672. * @returns a new Vector2
  2673. */
  2674. Vector2.Clamp = function (value, min, max) {
  2675. var x = value.x;
  2676. x = (x > max.x) ? max.x : x;
  2677. x = (x < min.x) ? min.x : x;
  2678. var y = value.y;
  2679. y = (y > max.y) ? max.y : y;
  2680. y = (y < min.y) ? min.y : y;
  2681. return new Vector2(x, y);
  2682. };
  2683. /**
  2684. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2685. * @param value1 defines the 1st control point
  2686. * @param tangent1 defines the outgoing tangent
  2687. * @param value2 defines the 2nd control point
  2688. * @param tangent2 defines the incoming tangent
  2689. * @param amount defines the interpolation factor
  2690. * @returns a new Vector2
  2691. */
  2692. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2693. var squared = amount * amount;
  2694. var cubed = amount * squared;
  2695. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2696. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2697. var part3 = (cubed - (2.0 * squared)) + amount;
  2698. var part4 = cubed - squared;
  2699. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2700. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2701. return new Vector2(x, y);
  2702. };
  2703. /**
  2704. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2705. * @param start defines the start vector
  2706. * @param end defines the end vector
  2707. * @param amount defines the interpolation factor
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Lerp = function (start, end, amount) {
  2711. var x = start.x + ((end.x - start.x) * amount);
  2712. var y = start.y + ((end.y - start.y) * amount);
  2713. return new Vector2(x, y);
  2714. };
  2715. /**
  2716. * Gets the dot product of the vector "left" and the vector "right"
  2717. * @param left defines first vector
  2718. * @param right defines second vector
  2719. * @returns the dot product (float)
  2720. */
  2721. Vector2.Dot = function (left, right) {
  2722. return left.x * right.x + left.y * right.y;
  2723. };
  2724. /**
  2725. * Returns a new Vector2 equal to the normalized given vector
  2726. * @param vector defines the vector to normalize
  2727. * @returns a new Vector2
  2728. */
  2729. Vector2.Normalize = function (vector) {
  2730. var newVector = vector.clone();
  2731. newVector.normalize();
  2732. return newVector;
  2733. };
  2734. /**
  2735. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2736. * @param left defines 1st vector
  2737. * @param right defines 2nd vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Minimize = function (left, right) {
  2741. var x = (left.x < right.x) ? left.x : right.x;
  2742. var y = (left.y < right.y) ? left.y : right.y;
  2743. return new Vector2(x, y);
  2744. };
  2745. /**
  2746. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2747. * @param left defines 1st vector
  2748. * @param right defines 2nd vector
  2749. * @returns a new Vector2
  2750. */
  2751. Vector2.Maximize = function (left, right) {
  2752. var x = (left.x > right.x) ? left.x : right.x;
  2753. var y = (left.y > right.y) ? left.y : right.y;
  2754. return new Vector2(x, y);
  2755. };
  2756. /**
  2757. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2758. * @param vector defines the vector to transform
  2759. * @param transformation defines the matrix to apply
  2760. * @returns a new Vector2
  2761. */
  2762. Vector2.Transform = function (vector, transformation) {
  2763. var r = Vector2.Zero();
  2764. Vector2.TransformToRef(vector, transformation, r);
  2765. return r;
  2766. };
  2767. /**
  2768. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2769. * @param vector defines the vector to transform
  2770. * @param transformation defines the matrix to apply
  2771. * @param result defines the target vector
  2772. */
  2773. Vector2.TransformToRef = function (vector, transformation, result) {
  2774. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2775. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2776. result.x = x;
  2777. result.y = y;
  2778. };
  2779. /**
  2780. * Determines if a given vector is included in a triangle
  2781. * @param p defines the vector to test
  2782. * @param p0 defines 1st triangle point
  2783. * @param p1 defines 2nd triangle point
  2784. * @param p2 defines 3rd triangle point
  2785. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2786. */
  2787. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2788. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2789. var sign = a < 0 ? -1 : 1;
  2790. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2791. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2792. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2793. };
  2794. /**
  2795. * Gets the distance between the vectors "value1" and "value2"
  2796. * @param value1 defines first vector
  2797. * @param value2 defines second vector
  2798. * @returns the distance between vectors
  2799. */
  2800. Vector2.Distance = function (value1, value2) {
  2801. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2802. };
  2803. /**
  2804. * Returns the squared distance between the vectors "value1" and "value2"
  2805. * @param value1 defines first vector
  2806. * @param value2 defines second vector
  2807. * @returns the squared distance between vectors
  2808. */
  2809. Vector2.DistanceSquared = function (value1, value2) {
  2810. var x = value1.x - value2.x;
  2811. var y = value1.y - value2.y;
  2812. return (x * x) + (y * y);
  2813. };
  2814. /**
  2815. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2816. * @param value1 defines first vector
  2817. * @param value2 defines second vector
  2818. * @returns a new Vector2
  2819. */
  2820. Vector2.Center = function (value1, value2) {
  2821. var center = value1.add(value2);
  2822. center.scaleInPlace(0.5);
  2823. return center;
  2824. };
  2825. /**
  2826. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2827. * @param p defines the middle point
  2828. * @param segA defines one point of the segment
  2829. * @param segB defines the other point of the segment
  2830. * @returns the shortest distance
  2831. */
  2832. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2833. var l2 = Vector2.DistanceSquared(segA, segB);
  2834. if (l2 === 0.0) {
  2835. return Vector2.Distance(p, segA);
  2836. }
  2837. var v = segB.subtract(segA);
  2838. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2839. var proj = segA.add(v.multiplyByFloats(t, t));
  2840. return Vector2.Distance(p, proj);
  2841. };
  2842. return Vector2;
  2843. }());
  2844. BABYLON.Vector2 = Vector2;
  2845. /**
  2846. * Classed used to store (x,y,z) vector representation
  2847. * A Vector3 is the main object used in 3D geometry
  2848. * It can represent etiher the coordinates of a point the space, either a direction
  2849. * Reminder: Babylon.js uses a left handed forward facing system
  2850. */
  2851. var Vector3 = /** @class */ (function () {
  2852. /**
  2853. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2854. * @param x defines the first coordinates (on X axis)
  2855. * @param y defines the second coordinates (on Y axis)
  2856. * @param z defines the third coordinates (on Z axis)
  2857. */
  2858. function Vector3(
  2859. /**
  2860. * Defines the first coordinates (on X axis)
  2861. */
  2862. x,
  2863. /**
  2864. * Defines the second coordinates (on Y axis)
  2865. */
  2866. y,
  2867. /**
  2868. * Defines the third coordinates (on Z axis)
  2869. */
  2870. z) {
  2871. this.x = x;
  2872. this.y = y;
  2873. this.z = z;
  2874. }
  2875. /**
  2876. * Creates a string representation of the Vector3
  2877. * @returns a string with the Vector3 coordinates.
  2878. */
  2879. Vector3.prototype.toString = function () {
  2880. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2881. };
  2882. /**
  2883. * Gets the class name
  2884. * @returns the string "Vector3"
  2885. */
  2886. Vector3.prototype.getClassName = function () {
  2887. return "Vector3";
  2888. };
  2889. /**
  2890. * Creates the Vector3 hash code
  2891. * @returns a number which tends to be unique between Vector3 instances
  2892. */
  2893. Vector3.prototype.getHashCode = function () {
  2894. var hash = this.x || 0;
  2895. hash = (hash * 397) ^ (this.y || 0);
  2896. hash = (hash * 397) ^ (this.z || 0);
  2897. return hash;
  2898. };
  2899. // Operators
  2900. /**
  2901. * Creates an array containing three elements : the coordinates of the Vector3
  2902. * @returns a new array of numbers
  2903. */
  2904. Vector3.prototype.asArray = function () {
  2905. var result = [];
  2906. this.toArray(result, 0);
  2907. return result;
  2908. };
  2909. /**
  2910. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2911. * @param array defines the destination array
  2912. * @param index defines the offset in the destination array
  2913. * @returns the current Vector3
  2914. */
  2915. Vector3.prototype.toArray = function (array, index) {
  2916. if (index === void 0) { index = 0; }
  2917. array[index] = this.x;
  2918. array[index + 1] = this.y;
  2919. array[index + 2] = this.z;
  2920. return this;
  2921. };
  2922. /**
  2923. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2924. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2925. */
  2926. Vector3.prototype.toQuaternion = function () {
  2927. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2928. };
  2929. /**
  2930. * Adds the given vector to the current Vector3
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.addInPlace = function (otherVector) {
  2935. this.x += otherVector.x;
  2936. this.y += otherVector.y;
  2937. this.z += otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2942. * @param otherVector defines the second operand
  2943. * @returns the resulting Vector3
  2944. */
  2945. Vector3.prototype.add = function (otherVector) {
  2946. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2947. };
  2948. /**
  2949. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2950. * @param otherVector defines the second operand
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the current Vector3
  2953. */
  2954. Vector3.prototype.addToRef = function (otherVector, result) {
  2955. result.x = this.x + otherVector.x;
  2956. result.y = this.y + otherVector.y;
  2957. result.z = this.z + otherVector.z;
  2958. return this;
  2959. };
  2960. /**
  2961. * Subtract the given vector from the current Vector3
  2962. * @param otherVector defines the second operand
  2963. * @returns the current updated Vector3
  2964. */
  2965. Vector3.prototype.subtractInPlace = function (otherVector) {
  2966. this.x -= otherVector.x;
  2967. this.y -= otherVector.y;
  2968. this.z -= otherVector.z;
  2969. return this;
  2970. };
  2971. /**
  2972. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2973. * @param otherVector defines the second operand
  2974. * @returns the resulting Vector3
  2975. */
  2976. Vector3.prototype.subtract = function (otherVector) {
  2977. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2978. };
  2979. /**
  2980. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2981. * @param otherVector defines the second operand
  2982. * @param result defines the Vector3 object where to store the result
  2983. * @returns the current Vector3
  2984. */
  2985. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2986. result.x = this.x - otherVector.x;
  2987. result.y = this.y - otherVector.y;
  2988. result.z = this.z - otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2993. * @param x defines the x coordinate of the operand
  2994. * @param y defines the y coordinate of the operand
  2995. * @param z defines the z coordinate of the operand
  2996. * @returns the resulting Vector3
  2997. */
  2998. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2999. return new Vector3(this.x - x, this.y - y, this.z - z);
  3000. };
  3001. /**
  3002. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3010. result.x = this.x - x;
  3011. result.y = this.y - y;
  3012. result.z = this.z - z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3017. * @returns a new Vector3
  3018. */
  3019. Vector3.prototype.negate = function () {
  3020. return new Vector3(-this.x, -this.y, -this.z);
  3021. };
  3022. /**
  3023. * Multiplies the Vector3 coordinates by the float "scale"
  3024. * @param scale defines the multiplier factor
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.scaleInPlace = function (scale) {
  3028. this.x *= scale;
  3029. this.y *= scale;
  3030. this.z *= scale;
  3031. return this;
  3032. };
  3033. /**
  3034. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3035. * @param scale defines the multiplier factor
  3036. * @returns a new Vector3
  3037. */
  3038. Vector3.prototype.scale = function (scale) {
  3039. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3040. };
  3041. /**
  3042. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3043. * @param scale defines the multiplier factor
  3044. * @param result defines the Vector3 object where to store the result
  3045. * @returns the current Vector3
  3046. */
  3047. Vector3.prototype.scaleToRef = function (scale, result) {
  3048. result.x = this.x * scale;
  3049. result.y = this.y * scale;
  3050. result.z = this.z * scale;
  3051. return this;
  3052. };
  3053. /**
  3054. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3055. * @param scale defines the scale factor
  3056. * @param result defines the Vector3 object where to store the result
  3057. * @returns the unmodified current Vector3
  3058. */
  3059. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3060. result.x += this.x * scale;
  3061. result.y += this.y * scale;
  3062. result.z += this.z * scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3067. * @param otherVector defines the second operand
  3068. * @returns true if both vectors are equals
  3069. */
  3070. Vector3.prototype.equals = function (otherVector) {
  3071. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3072. };
  3073. /**
  3074. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3075. * @param otherVector defines the second operand
  3076. * @param epsilon defines the minimal distance to define values as equals
  3077. * @returns true if both vectors are distant less than epsilon
  3078. */
  3079. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3080. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3081. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3082. };
  3083. /**
  3084. * Returns true if the current Vector3 coordinates equals the given floats
  3085. * @param x defines the x coordinate of the operand
  3086. * @param y defines the y coordinate of the operand
  3087. * @param z defines the z coordinate of the operand
  3088. * @returns true if both vectors are equals
  3089. */
  3090. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3091. return this.x === x && this.y === y && this.z === z;
  3092. };
  3093. /**
  3094. * Multiplies the current Vector3 coordinates by the given ones
  3095. * @param otherVector defines the second operand
  3096. * @returns the current updated Vector3
  3097. */
  3098. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3099. this.x *= otherVector.x;
  3100. this.y *= otherVector.y;
  3101. this.z *= otherVector.z;
  3102. return this;
  3103. };
  3104. /**
  3105. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3106. * @param otherVector defines the second operand
  3107. * @returns the new Vector3
  3108. */
  3109. Vector3.prototype.multiply = function (otherVector) {
  3110. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3111. };
  3112. /**
  3113. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3114. * @param otherVector defines the second operand
  3115. * @param result defines the Vector3 object where to store the result
  3116. * @returns the current Vector3
  3117. */
  3118. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3119. result.x = this.x * otherVector.x;
  3120. result.y = this.y * otherVector.y;
  3121. result.z = this.z * otherVector.z;
  3122. return this;
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3126. * @param x defines the x coordinate of the operand
  3127. * @param y defines the y coordinate of the operand
  3128. * @param z defines the z coordinate of the operand
  3129. * @returns the new Vector3
  3130. */
  3131. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3132. return new Vector3(this.x * x, this.y * y, this.z * z);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3136. * @param otherVector defines the second operand
  3137. * @returns the new Vector3
  3138. */
  3139. Vector3.prototype.divide = function (otherVector) {
  3140. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3141. };
  3142. /**
  3143. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3144. * @param otherVector defines the second operand
  3145. * @param result defines the Vector3 object where to store the result
  3146. * @returns the current Vector3
  3147. */
  3148. Vector3.prototype.divideToRef = function (otherVector, result) {
  3149. result.x = this.x / otherVector.x;
  3150. result.y = this.y / otherVector.y;
  3151. result.z = this.z / otherVector.z;
  3152. return this;
  3153. };
  3154. /**
  3155. * Divides the current Vector3 coordinates by the given ones.
  3156. * @param otherVector defines the second operand
  3157. * @returns the current updated Vector3
  3158. */
  3159. Vector3.prototype.divideInPlace = function (otherVector) {
  3160. return this.divideToRef(otherVector, this);
  3161. };
  3162. /**
  3163. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3164. * @param other defines the second operand
  3165. * @returns the current updated Vector3
  3166. */
  3167. Vector3.prototype.minimizeInPlace = function (other) {
  3168. if (other.x < this.x)
  3169. this.x = other.x;
  3170. if (other.y < this.y)
  3171. this.y = other.y;
  3172. if (other.z < this.z)
  3173. this.z = other.z;
  3174. return this;
  3175. };
  3176. /**
  3177. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3178. * @param other defines the second operand
  3179. * @returns the current updated Vector3
  3180. */
  3181. Vector3.prototype.maximizeInPlace = function (other) {
  3182. if (other.x > this.x)
  3183. this.x = other.x;
  3184. if (other.y > this.y)
  3185. this.y = other.y;
  3186. if (other.z > this.z)
  3187. this.z = other.z;
  3188. return this;
  3189. };
  3190. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3191. /**
  3192. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3193. */
  3194. get: function () {
  3195. var absX = Math.abs(this.x);
  3196. var absY = Math.abs(this.y);
  3197. if (absX !== absY) {
  3198. return true;
  3199. }
  3200. var absZ = Math.abs(this.z);
  3201. if (absX !== absZ) {
  3202. return true;
  3203. }
  3204. if (absY !== absZ) {
  3205. return true;
  3206. }
  3207. return false;
  3208. },
  3209. enumerable: true,
  3210. configurable: true
  3211. });
  3212. // Properties
  3213. /**
  3214. * Gets the length of the Vector3
  3215. * @returns the length of the Vecto3
  3216. */
  3217. Vector3.prototype.length = function () {
  3218. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3219. };
  3220. /**
  3221. * Gets the squared length of the Vector3
  3222. * @returns squared length of the Vector3
  3223. */
  3224. Vector3.prototype.lengthSquared = function () {
  3225. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3226. };
  3227. /**
  3228. * Normalize the current Vector3.
  3229. * Please note that this is an in place operation.
  3230. * @returns the current updated Vector3
  3231. */
  3232. Vector3.prototype.normalize = function () {
  3233. var len = this.length();
  3234. if (len === 0 || len === 1.0)
  3235. return this;
  3236. var num = 1.0 / len;
  3237. this.x *= num;
  3238. this.y *= num;
  3239. this.z *= num;
  3240. return this;
  3241. };
  3242. /**
  3243. * Normalize the current Vector3 to a new vector
  3244. * @returns the new Vector3
  3245. */
  3246. Vector3.prototype.normalizeToNew = function () {
  3247. var normalized = new Vector3(0, 0, 0);
  3248. this.normalizeToRef(normalized);
  3249. return normalized;
  3250. };
  3251. /**
  3252. * Normalize the current Vector3 to the reference
  3253. * @param reference define the Vector3 to update
  3254. * @returns the updated Vector3
  3255. */
  3256. Vector3.prototype.normalizeToRef = function (reference) {
  3257. var len = this.length();
  3258. if (len === 0 || len === 1.0) {
  3259. reference.set(this.x, this.y, this.z);
  3260. return reference;
  3261. }
  3262. var scale = 1.0 / len;
  3263. this.scaleToRef(scale, reference);
  3264. return reference;
  3265. };
  3266. /**
  3267. * Creates a new Vector3 copied from the current Vector3
  3268. * @returns the new Vector3
  3269. */
  3270. Vector3.prototype.clone = function () {
  3271. return new Vector3(this.x, this.y, this.z);
  3272. };
  3273. /**
  3274. * Copies the given vector coordinates to the current Vector3 ones
  3275. * @param source defines the source Vector3
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.copyFrom = function (source) {
  3279. this.x = source.x;
  3280. this.y = source.y;
  3281. this.z = source.z;
  3282. return this;
  3283. };
  3284. /**
  3285. * Copies the given floats to the current Vector3 coordinates
  3286. * @param x defines the x coordinate of the operand
  3287. * @param y defines the y coordinate of the operand
  3288. * @param z defines the z coordinate of the operand
  3289. * @returns the current updated Vector3
  3290. */
  3291. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3292. this.x = x;
  3293. this.y = y;
  3294. this.z = z;
  3295. return this;
  3296. };
  3297. /**
  3298. * Copies the given floats to the current Vector3 coordinates
  3299. * @param x defines the x coordinate of the operand
  3300. * @param y defines the y coordinate of the operand
  3301. * @param z defines the z coordinate of the operand
  3302. * @returns the current updated Vector3
  3303. */
  3304. Vector3.prototype.set = function (x, y, z) {
  3305. return this.copyFromFloats(x, y, z);
  3306. };
  3307. // Statics
  3308. /**
  3309. * Get the clip factor between two vectors
  3310. * @param vector0 defines the first operand
  3311. * @param vector1 defines the second operand
  3312. * @param axis defines the axis to use
  3313. * @param size defines the size along the axis
  3314. * @returns the clip factor
  3315. */
  3316. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3317. var d0 = Vector3.Dot(vector0, axis) - size;
  3318. var d1 = Vector3.Dot(vector1, axis) - size;
  3319. var s = d0 / (d0 - d1);
  3320. return s;
  3321. };
  3322. /**
  3323. * Get angle between two vectors
  3324. * @param vector0 angle between vector0 and vector1
  3325. * @param vector1 angle between vector0 and vector1
  3326. * @param normal direction of the normal
  3327. * @return the angle between vector0 and vector1
  3328. */
  3329. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3330. var v0 = vector0.clone().normalize();
  3331. var v1 = vector1.clone().normalize();
  3332. var dot = Vector3.Dot(v0, v1);
  3333. var n = Vector3.Cross(v0, v1);
  3334. if (Vector3.Dot(n, normal) > 0) {
  3335. return Math.acos(dot);
  3336. }
  3337. return -Math.acos(dot);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set from the index "offset" of the given array
  3341. * @param array defines the source array
  3342. * @param offset defines the offset in the source array
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.FromArray = function (array, offset) {
  3346. if (!offset) {
  3347. offset = 0;
  3348. }
  3349. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3353. * This function is deprecated. Use FromArray instead
  3354. * @param array defines the source array
  3355. * @param offset defines the offset in the source array
  3356. * @returns the new Vector3
  3357. */
  3358. Vector3.FromFloatArray = function (array, offset) {
  3359. return Vector3.FromArray(array, offset);
  3360. };
  3361. /**
  3362. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3363. * @param array defines the source array
  3364. * @param offset defines the offset in the source array
  3365. * @param result defines the Vector3 where to store the result
  3366. */
  3367. Vector3.FromArrayToRef = function (array, offset, result) {
  3368. result.x = array[offset];
  3369. result.y = array[offset + 1];
  3370. result.z = array[offset + 2];
  3371. };
  3372. /**
  3373. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3374. * This function is deprecated. Use FromArrayToRef instead.
  3375. * @param array defines the source array
  3376. * @param offset defines the offset in the source array
  3377. * @param result defines the Vector3 where to store the result
  3378. */
  3379. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3380. return Vector3.FromArrayToRef(array, offset, result);
  3381. };
  3382. /**
  3383. * Sets the given vector "result" with the given floats.
  3384. * @param x defines the x coordinate of the source
  3385. * @param y defines the y coordinate of the source
  3386. * @param z defines the z coordinate of the source
  3387. * @param result defines the Vector3 where to store the result
  3388. */
  3389. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3390. result.x = x;
  3391. result.y = y;
  3392. result.z = z;
  3393. };
  3394. /**
  3395. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3396. * @returns a new empty Vector3
  3397. */
  3398. Vector3.Zero = function () {
  3399. return new Vector3(0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3403. * @returns a new unit Vector3
  3404. */
  3405. Vector3.One = function () {
  3406. return new Vector3(1.0, 1.0, 1.0);
  3407. };
  3408. /**
  3409. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3410. * @returns a new up Vector3
  3411. */
  3412. Vector3.Up = function () {
  3413. return new Vector3(0.0, 1.0, 0.0);
  3414. };
  3415. /**
  3416. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3417. * @returns a new forward Vector3
  3418. */
  3419. Vector3.Forward = function () {
  3420. return new Vector3(0.0, 0.0, 1.0);
  3421. };
  3422. /**
  3423. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3424. * @returns a new right Vector3
  3425. */
  3426. Vector3.Right = function () {
  3427. return new Vector3(1.0, 0.0, 0.0);
  3428. };
  3429. /**
  3430. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3431. * @returns a new left Vector3
  3432. */
  3433. Vector3.Left = function () {
  3434. return new Vector3(-1.0, 0.0, 0.0);
  3435. };
  3436. /**
  3437. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3438. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3439. * @param vector defines the Vector3 to transform
  3440. * @param transformation defines the transformation matrix
  3441. * @returns the transformed Vector3
  3442. */
  3443. Vector3.TransformCoordinates = function (vector, transformation) {
  3444. var result = Vector3.Zero();
  3445. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3450. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @param result defines the Vector3 where to store the result
  3454. */
  3455. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3456. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3457. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3458. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3459. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3460. result.x = x / w;
  3461. result.y = y / w;
  3462. result.z = z / w;
  3463. };
  3464. /**
  3465. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3466. * This method computes tranformed coordinates only, not transformed direction vectors
  3467. * @param x define the x coordinate of the source vector
  3468. * @param y define the y coordinate of the source vector
  3469. * @param z define the z coordinate of the source vector
  3470. * @param transformation defines the transformation matrix
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3474. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3475. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3476. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3477. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3478. result.x = rx / rw;
  3479. result.y = ry / rw;
  3480. result.z = rz / rw;
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3484. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3485. * @param vector defines the Vector3 to transform
  3486. * @param transformation defines the transformation matrix
  3487. * @returns the new Vector3
  3488. */
  3489. Vector3.TransformNormal = function (vector, transformation) {
  3490. var result = Vector3.Zero();
  3491. Vector3.TransformNormalToRef(vector, transformation, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param vector defines the Vector3 to transform
  3498. * @param transformation defines the transformation matrix
  3499. * @param result defines the Vector3 where to store the result
  3500. */
  3501. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3502. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3503. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3504. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3505. result.x = x;
  3506. result.y = y;
  3507. result.z = z;
  3508. };
  3509. /**
  3510. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3511. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3512. * @param x define the x coordinate of the source vector
  3513. * @param y define the y coordinate of the source vector
  3514. * @param z define the z coordinate of the source vector
  3515. * @param transformation defines the transformation matrix
  3516. * @param result defines the Vector3 where to store the result
  3517. */
  3518. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3519. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3520. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3521. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3522. };
  3523. /**
  3524. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3525. * @param value1 defines the first control point
  3526. * @param value2 defines the second control point
  3527. * @param value3 defines the third control point
  3528. * @param value4 defines the fourth control point
  3529. * @param amount defines the amount on the spline to use
  3530. * @returns the new Vector3
  3531. */
  3532. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3533. var squared = amount * amount;
  3534. var cubed = amount * squared;
  3535. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3536. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3537. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3538. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3539. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3540. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3541. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3542. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3543. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3544. return new Vector3(x, y, z);
  3545. };
  3546. /**
  3547. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3548. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3549. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3550. * @param value defines the current value
  3551. * @param min defines the lower range value
  3552. * @param max defines the upper range value
  3553. * @returns the new Vector3
  3554. */
  3555. Vector3.Clamp = function (value, min, max) {
  3556. var x = value.x;
  3557. x = (x > max.x) ? max.x : x;
  3558. x = (x < min.x) ? min.x : x;
  3559. var y = value.y;
  3560. y = (y > max.y) ? max.y : y;
  3561. y = (y < min.y) ? min.y : y;
  3562. var z = value.z;
  3563. z = (z > max.z) ? max.z : z;
  3564. z = (z < min.z) ? min.z : z;
  3565. return new Vector3(x, y, z);
  3566. };
  3567. /**
  3568. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3569. * @param value1 defines the first control point
  3570. * @param tangent1 defines the first tangent vector
  3571. * @param value2 defines the second control point
  3572. * @param tangent2 defines the second tangent vector
  3573. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3577. var squared = amount * amount;
  3578. var cubed = amount * squared;
  3579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3581. var part3 = (cubed - (2.0 * squared)) + amount;
  3582. var part4 = cubed - squared;
  3583. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3584. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3585. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3586. return new Vector3(x, y, z);
  3587. };
  3588. /**
  3589. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3590. * @param start defines the start value
  3591. * @param end defines the end value
  3592. * @param amount max defines amount between both (between 0 and 1)
  3593. * @returns the new Vector3
  3594. */
  3595. Vector3.Lerp = function (start, end, amount) {
  3596. var result = new Vector3(0, 0, 0);
  3597. Vector3.LerpToRef(start, end, amount, result);
  3598. return result;
  3599. };
  3600. /**
  3601. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3602. * @param start defines the start value
  3603. * @param end defines the end value
  3604. * @param amount max defines amount between both (between 0 and 1)
  3605. * @param result defines the Vector3 where to store the result
  3606. */
  3607. Vector3.LerpToRef = function (start, end, amount, result) {
  3608. result.x = start.x + ((end.x - start.x) * amount);
  3609. result.y = start.y + ((end.y - start.y) * amount);
  3610. result.z = start.z + ((end.z - start.z) * amount);
  3611. };
  3612. /**
  3613. * Returns the dot product (float) between the vectors "left" and "right"
  3614. * @param left defines the left operand
  3615. * @param right defines the right operand
  3616. * @returns the dot product
  3617. */
  3618. Vector3.Dot = function (left, right) {
  3619. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3620. };
  3621. /**
  3622. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3623. * The cross product is then orthogonal to both "left" and "right"
  3624. * @param left defines the left operand
  3625. * @param right defines the right operand
  3626. * @returns the cross product
  3627. */
  3628. Vector3.Cross = function (left, right) {
  3629. var result = Vector3.Zero();
  3630. Vector3.CrossToRef(left, right, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Sets the given vector "result" with the cross product of "left" and "right"
  3635. * The cross product is then orthogonal to both "left" and "right"
  3636. * @param left defines the left operand
  3637. * @param right defines the right operand
  3638. * @param result defines the Vector3 where to store the result
  3639. */
  3640. Vector3.CrossToRef = function (left, right, result) {
  3641. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3642. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3643. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3644. result.copyFrom(MathTmp.Vector3[0]);
  3645. };
  3646. /**
  3647. * Returns a new Vector3 as the normalization of the given vector
  3648. * @param vector defines the Vector3 to normalize
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.Normalize = function (vector) {
  3652. var result = Vector3.Zero();
  3653. Vector3.NormalizeToRef(vector, result);
  3654. return result;
  3655. };
  3656. /**
  3657. * Sets the given vector "result" with the normalization of the given first vector
  3658. * @param vector defines the Vector3 to normalize
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.NormalizeToRef = function (vector, result) {
  3662. result.copyFrom(vector);
  3663. result.normalize();
  3664. };
  3665. /**
  3666. * Project a Vector3 onto screen space
  3667. * @param vector defines the Vector3 to project
  3668. * @param world defines the world matrix to use
  3669. * @param transform defines the transform (view x projection) matrix to use
  3670. * @param viewport defines the screen viewport to use
  3671. * @returns the new Vector3
  3672. */
  3673. Vector3.Project = function (vector, world, transform, viewport) {
  3674. var cw = viewport.width;
  3675. var ch = viewport.height;
  3676. var cx = viewport.x;
  3677. var cy = viewport.y;
  3678. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3679. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3680. var matrix = MathTmp.Matrix[0];
  3681. world.multiplyToRef(transform, matrix);
  3682. matrix.multiplyToRef(viewportMatrix, matrix);
  3683. return Vector3.TransformCoordinates(vector, matrix);
  3684. };
  3685. /**
  3686. * Unproject from screen space to object space
  3687. * @param source defines the screen space Vector3 to use
  3688. * @param viewportWidth defines the current width of the viewport
  3689. * @param viewportHeight defines the current height of the viewport
  3690. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3691. * @param transform defines the transform (view x projection) matrix to use
  3692. * @returns the new Vector3
  3693. */
  3694. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3695. var matrix = MathTmp.Matrix[0];
  3696. world.multiplyToRef(transform, matrix);
  3697. matrix.invert();
  3698. source.x = source.x / viewportWidth * 2 - 1;
  3699. source.y = -(source.y / viewportHeight * 2 - 1);
  3700. var vector = Vector3.TransformCoordinates(source, matrix);
  3701. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3702. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3703. vector = vector.scale(1.0 / num);
  3704. }
  3705. return vector;
  3706. };
  3707. /**
  3708. * Unproject from screen space to object space
  3709. * @param source defines the screen space Vector3 to use
  3710. * @param viewportWidth defines the current width of the viewport
  3711. * @param viewportHeight defines the current height of the viewport
  3712. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3713. * @param view defines the view matrix to use
  3714. * @param projection defines the projection matrix to use
  3715. * @returns the new Vector3
  3716. */
  3717. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3718. var result = Vector3.Zero();
  3719. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3720. return result;
  3721. };
  3722. /**
  3723. * Unproject from screen space to object space
  3724. * @param source defines the screen space Vector3 to use
  3725. * @param viewportWidth defines the current width of the viewport
  3726. * @param viewportHeight defines the current height of the viewport
  3727. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3728. * @param view defines the view matrix to use
  3729. * @param projection defines the projection matrix to use
  3730. * @param result defines the Vector3 where to store the result
  3731. */
  3732. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3733. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3734. };
  3735. /**
  3736. * Unproject from screen space to object space
  3737. * @param sourceX defines the screen space x coordinate to use
  3738. * @param sourceY defines the screen space y coordinate to use
  3739. * @param sourceZ defines the screen space z coordinate to use
  3740. * @param viewportWidth defines the current width of the viewport
  3741. * @param viewportHeight defines the current height of the viewport
  3742. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3743. * @param view defines the view matrix to use
  3744. * @param projection defines the projection matrix to use
  3745. * @param result defines the Vector3 where to store the result
  3746. */
  3747. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3748. var matrix = MathTmp.Matrix[0];
  3749. world.multiplyToRef(view, matrix);
  3750. matrix.multiplyToRef(projection, matrix);
  3751. matrix.invert();
  3752. var screenSource = MathTmp.Vector3[0];
  3753. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3754. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3755. screenSource.z = 2 * sourceZ - 1.0;
  3756. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3757. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3758. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3759. result.scaleInPlace(1.0 / num);
  3760. }
  3761. };
  3762. /**
  3763. * Gets the minimal coordinate values between two Vector3
  3764. * @param left defines the first operand
  3765. * @param right defines the second operand
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.Minimize = function (left, right) {
  3769. var min = left.clone();
  3770. min.minimizeInPlace(right);
  3771. return min;
  3772. };
  3773. /**
  3774. * Gets the maximal coordinate values between two Vector3
  3775. * @param left defines the first operand
  3776. * @param right defines the second operand
  3777. * @returns the new Vector3
  3778. */
  3779. Vector3.Maximize = function (left, right) {
  3780. var max = left.clone();
  3781. max.maximizeInPlace(right);
  3782. return max;
  3783. };
  3784. /**
  3785. * Returns the distance between the vectors "value1" and "value2"
  3786. * @param value1 defines the first operand
  3787. * @param value2 defines the second operand
  3788. * @returns the distance
  3789. */
  3790. Vector3.Distance = function (value1, value2) {
  3791. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3792. };
  3793. /**
  3794. * Returns the squared distance between the vectors "value1" and "value2"
  3795. * @param value1 defines the first operand
  3796. * @param value2 defines the second operand
  3797. * @returns the squared distance
  3798. */
  3799. Vector3.DistanceSquared = function (value1, value2) {
  3800. var x = value1.x - value2.x;
  3801. var y = value1.y - value2.y;
  3802. var z = value1.z - value2.z;
  3803. return (x * x) + (y * y) + (z * z);
  3804. };
  3805. /**
  3806. * Returns a new Vector3 located at the center between "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the new Vector3
  3810. */
  3811. Vector3.Center = function (value1, value2) {
  3812. var center = value1.add(value2);
  3813. center.scaleInPlace(0.5);
  3814. return center;
  3815. };
  3816. /**
  3817. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3819. * to something in order to rotate it from its local system to the given target system
  3820. * Note: axis1, axis2 and axis3 are normalized during this operation
  3821. * @param axis1 defines the first axis
  3822. * @param axis2 defines the second axis
  3823. * @param axis3 defines the third axis
  3824. * @returns a new Vector3
  3825. */
  3826. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3827. var rotation = Vector3.Zero();
  3828. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3829. return rotation;
  3830. };
  3831. /**
  3832. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @param ref defines the Vector3 where to store the result
  3837. */
  3838. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3839. var quat = MathTmp.Quaternion[0];
  3840. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3841. quat.toEulerAnglesToRef(ref);
  3842. };
  3843. return Vector3;
  3844. }());
  3845. BABYLON.Vector3 = Vector3;
  3846. //Vector4 class created for EulerAngle class conversion to Quaternion
  3847. var Vector4 = /** @class */ (function () {
  3848. /**
  3849. * Creates a Vector4 object from the given floats.
  3850. */
  3851. function Vector4(x, y, z, w) {
  3852. this.x = x;
  3853. this.y = y;
  3854. this.z = z;
  3855. this.w = w;
  3856. }
  3857. /**
  3858. * Returns the string with the Vector4 coordinates.
  3859. */
  3860. Vector4.prototype.toString = function () {
  3861. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3862. };
  3863. /**
  3864. * Returns the string "Vector4".
  3865. */
  3866. Vector4.prototype.getClassName = function () {
  3867. return "Vector4";
  3868. };
  3869. /**
  3870. * Returns the Vector4 hash code.
  3871. */
  3872. Vector4.prototype.getHashCode = function () {
  3873. var hash = this.x || 0;
  3874. hash = (hash * 397) ^ (this.y || 0);
  3875. hash = (hash * 397) ^ (this.z || 0);
  3876. hash = (hash * 397) ^ (this.w || 0);
  3877. return hash;
  3878. };
  3879. // Operators
  3880. /**
  3881. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3882. */
  3883. Vector4.prototype.asArray = function () {
  3884. var result = new Array();
  3885. this.toArray(result, 0);
  3886. return result;
  3887. };
  3888. /**
  3889. * Populates the given array from the given index with the Vector4 coordinates.
  3890. * Returns the Vector4.
  3891. */
  3892. Vector4.prototype.toArray = function (array, index) {
  3893. if (index === undefined) {
  3894. index = 0;
  3895. }
  3896. array[index] = this.x;
  3897. array[index + 1] = this.y;
  3898. array[index + 2] = this.z;
  3899. array[index + 3] = this.w;
  3900. return this;
  3901. };
  3902. /**
  3903. * Adds the given vector to the current Vector4.
  3904. * Returns the updated Vector4.
  3905. */
  3906. Vector4.prototype.addInPlace = function (otherVector) {
  3907. this.x += otherVector.x;
  3908. this.y += otherVector.y;
  3909. this.z += otherVector.z;
  3910. this.w += otherVector.w;
  3911. return this;
  3912. };
  3913. /**
  3914. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3915. */
  3916. Vector4.prototype.add = function (otherVector) {
  3917. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3918. };
  3919. /**
  3920. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3921. * Returns the current Vector4.
  3922. */
  3923. Vector4.prototype.addToRef = function (otherVector, result) {
  3924. result.x = this.x + otherVector.x;
  3925. result.y = this.y + otherVector.y;
  3926. result.z = this.z + otherVector.z;
  3927. result.w = this.w + otherVector.w;
  3928. return this;
  3929. };
  3930. /**
  3931. * Subtract in place the given vector from the current Vector4.
  3932. * Returns the updated Vector4.
  3933. */
  3934. Vector4.prototype.subtractInPlace = function (otherVector) {
  3935. this.x -= otherVector.x;
  3936. this.y -= otherVector.y;
  3937. this.z -= otherVector.z;
  3938. this.w -= otherVector.w;
  3939. return this;
  3940. };
  3941. /**
  3942. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3943. */
  3944. Vector4.prototype.subtract = function (otherVector) {
  3945. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3946. };
  3947. /**
  3948. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3949. * Returns the current Vector4.
  3950. */
  3951. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3952. result.x = this.x - otherVector.x;
  3953. result.y = this.y - otherVector.y;
  3954. result.z = this.z - otherVector.z;
  3955. result.w = this.w - otherVector.w;
  3956. return this;
  3957. };
  3958. /**
  3959. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3960. */
  3961. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3962. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3963. };
  3964. /**
  3965. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3966. * Returns the current Vector4.
  3967. */
  3968. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3969. result.x = this.x - x;
  3970. result.y = this.y - y;
  3971. result.z = this.z - z;
  3972. result.w = this.w - w;
  3973. return this;
  3974. };
  3975. /**
  3976. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3977. */
  3978. Vector4.prototype.negate = function () {
  3979. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3980. };
  3981. /**
  3982. * Multiplies the current Vector4 coordinates by scale (float).
  3983. * Returns the updated Vector4.
  3984. */
  3985. Vector4.prototype.scaleInPlace = function (scale) {
  3986. this.x *= scale;
  3987. this.y *= scale;
  3988. this.z *= scale;
  3989. this.w *= scale;
  3990. return this;
  3991. };
  3992. /**
  3993. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3994. */
  3995. Vector4.prototype.scale = function (scale) {
  3996. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3997. };
  3998. /**
  3999. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4000. * Returns the current Vector4.
  4001. */
  4002. Vector4.prototype.scaleToRef = function (scale, result) {
  4003. result.x = this.x * scale;
  4004. result.y = this.y * scale;
  4005. result.z = this.z * scale;
  4006. result.w = this.w * scale;
  4007. return this;
  4008. };
  4009. /**
  4010. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4011. * @param scale defines the scale factor
  4012. * @param result defines the Vector4 object where to store the result
  4013. * @returns the unmodified current Vector4
  4014. */
  4015. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4016. result.x += this.x * scale;
  4017. result.y += this.y * scale;
  4018. result.z += this.z * scale;
  4019. result.w += this.w * scale;
  4020. return this;
  4021. };
  4022. /**
  4023. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4024. */
  4025. Vector4.prototype.equals = function (otherVector) {
  4026. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4027. };
  4028. /**
  4029. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4030. */
  4031. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4032. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4033. return otherVector
  4034. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4035. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4036. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4037. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4038. };
  4039. /**
  4040. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4041. */
  4042. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4043. return this.x === x && this.y === y && this.z === z && this.w === w;
  4044. };
  4045. /**
  4046. * Multiplies in place the current Vector4 by the given one.
  4047. * Returns the updated Vector4.
  4048. */
  4049. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4050. this.x *= otherVector.x;
  4051. this.y *= otherVector.y;
  4052. this.z *= otherVector.z;
  4053. this.w *= otherVector.w;
  4054. return this;
  4055. };
  4056. /**
  4057. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4058. */
  4059. Vector4.prototype.multiply = function (otherVector) {
  4060. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4061. };
  4062. /**
  4063. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4064. * Returns the current Vector4.
  4065. */
  4066. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4067. result.x = this.x * otherVector.x;
  4068. result.y = this.y * otherVector.y;
  4069. result.z = this.z * otherVector.z;
  4070. result.w = this.w * otherVector.w;
  4071. return this;
  4072. };
  4073. /**
  4074. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4075. */
  4076. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4077. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4078. };
  4079. /**
  4080. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4081. */
  4082. Vector4.prototype.divide = function (otherVector) {
  4083. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4084. };
  4085. /**
  4086. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4087. * Returns the current Vector4.
  4088. */
  4089. Vector4.prototype.divideToRef = function (otherVector, result) {
  4090. result.x = this.x / otherVector.x;
  4091. result.y = this.y / otherVector.y;
  4092. result.z = this.z / otherVector.z;
  4093. result.w = this.w / otherVector.w;
  4094. return this;
  4095. };
  4096. /**
  4097. * Divides the current Vector3 coordinates by the given ones.
  4098. * @returns the updated Vector3.
  4099. */
  4100. Vector4.prototype.divideInPlace = function (otherVector) {
  4101. return this.divideToRef(otherVector, this);
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.minimizeInPlace = function (other) {
  4109. if (other.x < this.x)
  4110. this.x = other.x;
  4111. if (other.y < this.y)
  4112. this.y = other.y;
  4113. if (other.z < this.z)
  4114. this.z = other.z;
  4115. if (other.w < this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4121. * @param other defines the second operand
  4122. * @returns the current updated Vector4
  4123. */
  4124. Vector4.prototype.maximizeInPlace = function (other) {
  4125. if (other.x > this.x)
  4126. this.x = other.x;
  4127. if (other.y > this.y)
  4128. this.y = other.y;
  4129. if (other.z > this.z)
  4130. this.z = other.z;
  4131. if (other.w > this.w)
  4132. this.w = other.w;
  4133. return this;
  4134. };
  4135. // Properties
  4136. /**
  4137. * Returns the Vector4 length (float).
  4138. */
  4139. Vector4.prototype.length = function () {
  4140. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4141. };
  4142. /**
  4143. * Returns the Vector4 squared length (float).
  4144. */
  4145. Vector4.prototype.lengthSquared = function () {
  4146. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4147. };
  4148. // Methods
  4149. /**
  4150. * Normalizes in place the Vector4.
  4151. * Returns the updated Vector4.
  4152. */
  4153. Vector4.prototype.normalize = function () {
  4154. var len = this.length();
  4155. if (len === 0)
  4156. return this;
  4157. var num = 1.0 / len;
  4158. this.x *= num;
  4159. this.y *= num;
  4160. this.z *= num;
  4161. this.w *= num;
  4162. return this;
  4163. };
  4164. /**
  4165. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4166. */
  4167. Vector4.prototype.toVector3 = function () {
  4168. return new Vector3(this.x, this.y, this.z);
  4169. };
  4170. /**
  4171. * Returns a new Vector4 copied from the current one.
  4172. */
  4173. Vector4.prototype.clone = function () {
  4174. return new Vector4(this.x, this.y, this.z, this.w);
  4175. };
  4176. /**
  4177. * Updates the current Vector4 with the given one coordinates.
  4178. * Returns the updated Vector4.
  4179. */
  4180. Vector4.prototype.copyFrom = function (source) {
  4181. this.x = source.x;
  4182. this.y = source.y;
  4183. this.z = source.z;
  4184. this.w = source.w;
  4185. return this;
  4186. };
  4187. /**
  4188. * Updates the current Vector4 coordinates with the given floats.
  4189. * Returns the updated Vector4.
  4190. */
  4191. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4192. this.x = x;
  4193. this.y = y;
  4194. this.z = z;
  4195. this.w = w;
  4196. return this;
  4197. };
  4198. /**
  4199. * Updates the current Vector4 coordinates with the given floats.
  4200. * Returns the updated Vector4.
  4201. */
  4202. Vector4.prototype.set = function (x, y, z, w) {
  4203. return this.copyFromFloats(x, y, z, w);
  4204. };
  4205. // Statics
  4206. /**
  4207. * Returns a new Vector4 set from the starting index of the given array.
  4208. */
  4209. Vector4.FromArray = function (array, offset) {
  4210. if (!offset) {
  4211. offset = 0;
  4212. }
  4213. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4214. };
  4215. /**
  4216. * Updates the given vector "result" from the starting index of the given array.
  4217. */
  4218. Vector4.FromArrayToRef = function (array, offset, result) {
  4219. result.x = array[offset];
  4220. result.y = array[offset + 1];
  4221. result.z = array[offset + 2];
  4222. result.w = array[offset + 3];
  4223. };
  4224. /**
  4225. * Updates the given vector "result" from the starting index of the given Float32Array.
  4226. */
  4227. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4228. Vector4.FromArrayToRef(array, offset, result);
  4229. };
  4230. /**
  4231. * Updates the given vector "result" coordinates from the given floats.
  4232. */
  4233. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4234. result.x = x;
  4235. result.y = y;
  4236. result.z = z;
  4237. result.w = w;
  4238. };
  4239. /**
  4240. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4241. */
  4242. Vector4.Zero = function () {
  4243. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4244. };
  4245. /**
  4246. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4247. */
  4248. Vector4.One = function () {
  4249. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4250. };
  4251. /**
  4252. * Returns a new normalized Vector4 from the given one.
  4253. */
  4254. Vector4.Normalize = function (vector) {
  4255. var result = Vector4.Zero();
  4256. Vector4.NormalizeToRef(vector, result);
  4257. return result;
  4258. };
  4259. /**
  4260. * Updates the given vector "result" from the normalization of the given one.
  4261. */
  4262. Vector4.NormalizeToRef = function (vector, result) {
  4263. result.copyFrom(vector);
  4264. result.normalize();
  4265. };
  4266. Vector4.Minimize = function (left, right) {
  4267. var min = left.clone();
  4268. min.minimizeInPlace(right);
  4269. return min;
  4270. };
  4271. Vector4.Maximize = function (left, right) {
  4272. var max = left.clone();
  4273. max.maximizeInPlace(right);
  4274. return max;
  4275. };
  4276. /**
  4277. * Returns the distance (float) between the vectors "value1" and "value2".
  4278. */
  4279. Vector4.Distance = function (value1, value2) {
  4280. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4281. };
  4282. /**
  4283. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4284. */
  4285. Vector4.DistanceSquared = function (value1, value2) {
  4286. var x = value1.x - value2.x;
  4287. var y = value1.y - value2.y;
  4288. var z = value1.z - value2.z;
  4289. var w = value1.w - value2.w;
  4290. return (x * x) + (y * y) + (z * z) + (w * w);
  4291. };
  4292. /**
  4293. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4294. */
  4295. Vector4.Center = function (value1, value2) {
  4296. var center = value1.add(value2);
  4297. center.scaleInPlace(0.5);
  4298. return center;
  4299. };
  4300. /**
  4301. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4302. * This methods computes transformed normalized direction vectors only.
  4303. */
  4304. Vector4.TransformNormal = function (vector, transformation) {
  4305. var result = Vector4.Zero();
  4306. Vector4.TransformNormalToRef(vector, transformation, result);
  4307. return result;
  4308. };
  4309. /**
  4310. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4311. * This methods computes transformed normalized direction vectors only.
  4312. */
  4313. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4314. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4315. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4316. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4317. result.x = x;
  4318. result.y = y;
  4319. result.z = z;
  4320. result.w = vector.w;
  4321. };
  4322. /**
  4323. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4324. * This methods computes transformed normalized direction vectors only.
  4325. */
  4326. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4327. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4328. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4329. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4330. result.w = w;
  4331. };
  4332. return Vector4;
  4333. }());
  4334. BABYLON.Vector4 = Vector4;
  4335. var Size = /** @class */ (function () {
  4336. /**
  4337. * Creates a Size object from the given width and height (floats).
  4338. */
  4339. function Size(width, height) {
  4340. this.width = width;
  4341. this.height = height;
  4342. }
  4343. // Returns a string with the Size width and height.
  4344. Size.prototype.toString = function () {
  4345. return "{W: " + this.width + ", H: " + this.height + "}";
  4346. };
  4347. /**
  4348. * Returns the string "Size"
  4349. */
  4350. Size.prototype.getClassName = function () {
  4351. return "Size";
  4352. };
  4353. /**
  4354. * Returns the Size hash code.
  4355. */
  4356. Size.prototype.getHashCode = function () {
  4357. var hash = this.width || 0;
  4358. hash = (hash * 397) ^ (this.height || 0);
  4359. return hash;
  4360. };
  4361. /**
  4362. * Updates the current size from the given one.
  4363. * Returns the updated Size.
  4364. */
  4365. Size.prototype.copyFrom = function (src) {
  4366. this.width = src.width;
  4367. this.height = src.height;
  4368. };
  4369. /**
  4370. * Updates in place the current Size from the given floats.
  4371. * Returns the updated Size.
  4372. */
  4373. Size.prototype.copyFromFloats = function (width, height) {
  4374. this.width = width;
  4375. this.height = height;
  4376. return this;
  4377. };
  4378. /**
  4379. * Updates in place the current Size from the given floats.
  4380. * Returns the updated Size.
  4381. */
  4382. Size.prototype.set = function (width, height) {
  4383. return this.copyFromFloats(width, height);
  4384. };
  4385. /**
  4386. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4387. */
  4388. Size.prototype.multiplyByFloats = function (w, h) {
  4389. return new Size(this.width * w, this.height * h);
  4390. };
  4391. /**
  4392. * Returns a new Size copied from the given one.
  4393. */
  4394. Size.prototype.clone = function () {
  4395. return new Size(this.width, this.height);
  4396. };
  4397. /**
  4398. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4399. */
  4400. Size.prototype.equals = function (other) {
  4401. if (!other) {
  4402. return false;
  4403. }
  4404. return (this.width === other.width) && (this.height === other.height);
  4405. };
  4406. Object.defineProperty(Size.prototype, "surface", {
  4407. /**
  4408. * Returns the surface of the Size : width * height (float).
  4409. */
  4410. get: function () {
  4411. return this.width * this.height;
  4412. },
  4413. enumerable: true,
  4414. configurable: true
  4415. });
  4416. /**
  4417. * Returns a new Size set to (0.0, 0.0)
  4418. */
  4419. Size.Zero = function () {
  4420. return new Size(0.0, 0.0);
  4421. };
  4422. /**
  4423. * Returns a new Size set as the addition result of the current Size and the given one.
  4424. */
  4425. Size.prototype.add = function (otherSize) {
  4426. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4427. return r;
  4428. };
  4429. /**
  4430. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4431. */
  4432. Size.prototype.subtract = function (otherSize) {
  4433. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4434. return r;
  4435. };
  4436. /**
  4437. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4438. */
  4439. Size.Lerp = function (start, end, amount) {
  4440. var w = start.width + ((end.width - start.width) * amount);
  4441. var h = start.height + ((end.height - start.height) * amount);
  4442. return new Size(w, h);
  4443. };
  4444. return Size;
  4445. }());
  4446. BABYLON.Size = Size;
  4447. /**
  4448. * Class used to store quaternion data
  4449. * @see https://en.wikipedia.org/wiki/Quaternion
  4450. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4451. */
  4452. var Quaternion = /** @class */ (function () {
  4453. /**
  4454. * Creates a new Quaternion from the given floats
  4455. * @param x defines the first component (0 by default)
  4456. * @param y defines the second component (0 by default)
  4457. * @param z defines the third component (0 by default)
  4458. * @param w defines the fourth component (1.0 by default)
  4459. */
  4460. function Quaternion(
  4461. /** defines the first component (0 by default) */
  4462. x,
  4463. /** defines the second component (0 by default) */
  4464. y,
  4465. /** defines the third component (0 by default) */
  4466. z,
  4467. /** defines the fourth component (1.0 by default) */
  4468. w) {
  4469. if (x === void 0) { x = 0.0; }
  4470. if (y === void 0) { y = 0.0; }
  4471. if (z === void 0) { z = 0.0; }
  4472. if (w === void 0) { w = 1.0; }
  4473. this.x = x;
  4474. this.y = y;
  4475. this.z = z;
  4476. this.w = w;
  4477. }
  4478. /**
  4479. * Gets a string representation for the current quaternion
  4480. * @returns a string with the Quaternion coordinates
  4481. */
  4482. Quaternion.prototype.toString = function () {
  4483. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4484. };
  4485. /**
  4486. * Gets the class name of the quaternion
  4487. * @returns the string "Quaternion"
  4488. */
  4489. Quaternion.prototype.getClassName = function () {
  4490. return "Quaternion";
  4491. };
  4492. /**
  4493. * Gets a hash code for this quaternion
  4494. * @returns the quaternion hash code
  4495. */
  4496. Quaternion.prototype.getHashCode = function () {
  4497. var hash = this.x || 0;
  4498. hash = (hash * 397) ^ (this.y || 0);
  4499. hash = (hash * 397) ^ (this.z || 0);
  4500. hash = (hash * 397) ^ (this.w || 0);
  4501. return hash;
  4502. };
  4503. /**
  4504. * Copy the quaternion to an array
  4505. * @returns a new array populated with 4 elements from the quaternion coordinates
  4506. */
  4507. Quaternion.prototype.asArray = function () {
  4508. return [this.x, this.y, this.z, this.w];
  4509. };
  4510. /**
  4511. * Check if two quaternions are equals
  4512. * @param otherQuaternion defines the second operand
  4513. * @return true if the current quaternion and the given one coordinates are strictly equals
  4514. */
  4515. Quaternion.prototype.equals = function (otherQuaternion) {
  4516. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4517. };
  4518. /**
  4519. * Clone the current quaternion
  4520. * @returns a new quaternion copied from the current one
  4521. */
  4522. Quaternion.prototype.clone = function () {
  4523. return new Quaternion(this.x, this.y, this.z, this.w);
  4524. };
  4525. /**
  4526. * Copy a quaternion to the current one
  4527. * @param other defines the other quaternion
  4528. * @returns the updated current quaternion
  4529. */
  4530. Quaternion.prototype.copyFrom = function (other) {
  4531. this.x = other.x;
  4532. this.y = other.y;
  4533. this.z = other.z;
  4534. this.w = other.w;
  4535. return this;
  4536. };
  4537. /**
  4538. * Updates the current quaternion with the given float coordinates
  4539. * @param x defines the x coordinate
  4540. * @param y defines the y coordinate
  4541. * @param z defines the z coordinate
  4542. * @param w defines the w coordinate
  4543. * @returns the updated current quaternion
  4544. */
  4545. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4546. this.x = x;
  4547. this.y = y;
  4548. this.z = z;
  4549. this.w = w;
  4550. return this;
  4551. };
  4552. /**
  4553. * Updates the current quaternion from the given float coordinates
  4554. * @param x defines the x coordinate
  4555. * @param y defines the y coordinate
  4556. * @param z defines the z coordinate
  4557. * @param w defines the w coordinate
  4558. * @returns the updated current quaternion
  4559. */
  4560. Quaternion.prototype.set = function (x, y, z, w) {
  4561. return this.copyFromFloats(x, y, z, w);
  4562. };
  4563. /**
  4564. * Adds two quaternions
  4565. * @param other defines the second operand
  4566. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4567. */
  4568. Quaternion.prototype.add = function (other) {
  4569. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4570. };
  4571. /**
  4572. * Add a quaternion to the current one
  4573. * @param other defines the quaternion to add
  4574. * @returns the current quaternion
  4575. */
  4576. Quaternion.prototype.addInPlace = function (other) {
  4577. this.x += other.x;
  4578. this.y += other.y;
  4579. this.z += other.z;
  4580. this.w += other.w;
  4581. return this;
  4582. };
  4583. /**
  4584. * Subtract two quaternions
  4585. * @param other defines the second operand
  4586. * @returns a new quaternion as the subtraction result of the given one from the current one
  4587. */
  4588. Quaternion.prototype.subtract = function (other) {
  4589. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4590. };
  4591. /**
  4592. * Multiplies the current quaternion by a scale factor
  4593. * @param value defines the scale factor
  4594. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4595. */
  4596. Quaternion.prototype.scale = function (value) {
  4597. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4598. };
  4599. /**
  4600. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4601. * @param scale defines the scale factor
  4602. * @param result defines the Quaternion object where to store the result
  4603. * @returns the unmodified current quaternion
  4604. */
  4605. Quaternion.prototype.scaleToRef = function (scale, result) {
  4606. result.x = this.x * scale;
  4607. result.y = this.y * scale;
  4608. result.z = this.z * scale;
  4609. result.w = this.w * scale;
  4610. return this;
  4611. };
  4612. /**
  4613. * Multiplies in place the current quaternion by a scale factor
  4614. * @param value defines the scale factor
  4615. * @returns the current modified quaternion
  4616. */
  4617. Quaternion.prototype.scaleInPlace = function (value) {
  4618. this.x *= value;
  4619. this.y *= value;
  4620. this.z *= value;
  4621. this.w *= value;
  4622. return this;
  4623. };
  4624. /**
  4625. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4626. * @param scale defines the scale factor
  4627. * @param result defines the Quaternion object where to store the result
  4628. * @returns the unmodified current quaternion
  4629. */
  4630. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4631. result.x += this.x * scale;
  4632. result.y += this.y * scale;
  4633. result.z += this.z * scale;
  4634. result.w += this.w * scale;
  4635. return this;
  4636. };
  4637. /**
  4638. * Multiplies two quaternions
  4639. * @param q1 defines the second operand
  4640. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4641. */
  4642. Quaternion.prototype.multiply = function (q1) {
  4643. var result = new Quaternion(0, 0, 0, 1.0);
  4644. this.multiplyToRef(q1, result);
  4645. return result;
  4646. };
  4647. /**
  4648. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4649. * @param q1 defines the second operand
  4650. * @param result defines the target quaternion
  4651. * @returns the current quaternion
  4652. */
  4653. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4654. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4655. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4656. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4657. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4658. result.copyFromFloats(x, y, z, w);
  4659. return this;
  4660. };
  4661. /**
  4662. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4663. * @param q1 defines the second operand
  4664. * @returns the currentupdated quaternion
  4665. */
  4666. Quaternion.prototype.multiplyInPlace = function (q1) {
  4667. this.multiplyToRef(q1, this);
  4668. return this;
  4669. };
  4670. /**
  4671. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4672. * @param ref defines the target quaternion
  4673. * @returns the current quaternion
  4674. */
  4675. Quaternion.prototype.conjugateToRef = function (ref) {
  4676. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4677. return this;
  4678. };
  4679. /**
  4680. * Conjugates in place (1-q) the current quaternion
  4681. * @returns the current updated quaternion
  4682. */
  4683. Quaternion.prototype.conjugateInPlace = function () {
  4684. this.x *= -1;
  4685. this.y *= -1;
  4686. this.z *= -1;
  4687. return this;
  4688. };
  4689. /**
  4690. * Conjugates in place (1-q) the current quaternion
  4691. * @returns a new quaternion
  4692. */
  4693. Quaternion.prototype.conjugate = function () {
  4694. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4695. return result;
  4696. };
  4697. /**
  4698. * Gets length of current quaternion
  4699. * @returns the quaternion length (float)
  4700. */
  4701. Quaternion.prototype.length = function () {
  4702. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4703. };
  4704. /**
  4705. * Normalize in place the current quaternion
  4706. * @returns the current updated quaternion
  4707. */
  4708. Quaternion.prototype.normalize = function () {
  4709. var length = 1.0 / this.length();
  4710. this.x *= length;
  4711. this.y *= length;
  4712. this.z *= length;
  4713. this.w *= length;
  4714. return this;
  4715. };
  4716. /**
  4717. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4718. * @param order is a reserved parameter and is ignore for now
  4719. * @returns a new Vector3 containing the Euler angles
  4720. */
  4721. Quaternion.prototype.toEulerAngles = function (order) {
  4722. if (order === void 0) { order = "YZX"; }
  4723. var result = Vector3.Zero();
  4724. this.toEulerAnglesToRef(result, order);
  4725. return result;
  4726. };
  4727. /**
  4728. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4729. * @param result defines the vector which will be filled with the Euler angles
  4730. * @param order is a reserved parameter and is ignore for now
  4731. * @returns the current unchanged quaternion
  4732. */
  4733. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4734. if (order === void 0) { order = "YZX"; }
  4735. var qz = this.z;
  4736. var qx = this.x;
  4737. var qy = this.y;
  4738. var qw = this.w;
  4739. var sqw = qw * qw;
  4740. var sqz = qz * qz;
  4741. var sqx = qx * qx;
  4742. var sqy = qy * qy;
  4743. var zAxisY = qy * qz - qx * qw;
  4744. var limit = .4999999;
  4745. if (zAxisY < -limit) {
  4746. result.y = 2 * Math.atan2(qy, qw);
  4747. result.x = Math.PI / 2;
  4748. result.z = 0;
  4749. }
  4750. else if (zAxisY > limit) {
  4751. result.y = 2 * Math.atan2(qy, qw);
  4752. result.x = -Math.PI / 2;
  4753. result.z = 0;
  4754. }
  4755. else {
  4756. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4757. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4758. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4759. }
  4760. return this;
  4761. };
  4762. /**
  4763. * Updates the given rotation matrix with the current quaternion values
  4764. * @param result defines the target matrix
  4765. * @returns the current unchanged quaternion
  4766. */
  4767. Quaternion.prototype.toRotationMatrix = function (result) {
  4768. var xx = this.x * this.x;
  4769. var yy = this.y * this.y;
  4770. var zz = this.z * this.z;
  4771. var xy = this.x * this.y;
  4772. var zw = this.z * this.w;
  4773. var zx = this.z * this.x;
  4774. var yw = this.y * this.w;
  4775. var yz = this.y * this.z;
  4776. var xw = this.x * this.w;
  4777. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4778. result.m[1] = 2.0 * (xy + zw);
  4779. result.m[2] = 2.0 * (zx - yw);
  4780. result.m[3] = 0;
  4781. result.m[4] = 2.0 * (xy - zw);
  4782. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4783. result.m[6] = 2.0 * (yz + xw);
  4784. result.m[7] = 0;
  4785. result.m[8] = 2.0 * (zx + yw);
  4786. result.m[9] = 2.0 * (yz - xw);
  4787. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4788. result.m[11] = 0;
  4789. result.m[12] = 0;
  4790. result.m[13] = 0;
  4791. result.m[14] = 0;
  4792. result.m[15] = 1.0;
  4793. result._markAsUpdated();
  4794. return this;
  4795. };
  4796. /**
  4797. * Updates the current quaternion from the given rotation matrix values
  4798. * @param matrix defines the source matrix
  4799. * @returns the current updated quaternion
  4800. */
  4801. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4802. Quaternion.FromRotationMatrixToRef(matrix, this);
  4803. return this;
  4804. };
  4805. // Statics
  4806. /**
  4807. * Creates a new quaternion from a rotation matrix
  4808. * @param matrix defines the source matrix
  4809. * @returns a new quaternion created from the given rotation matrix values
  4810. */
  4811. Quaternion.FromRotationMatrix = function (matrix) {
  4812. var result = new Quaternion();
  4813. Quaternion.FromRotationMatrixToRef(matrix, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Updates the given quaternion with the given rotation matrix values
  4818. * @param matrix defines the source matrix
  4819. * @param result defines the target quaternion
  4820. */
  4821. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4822. var data = matrix.m;
  4823. var m11 = data[0], m12 = data[4], m13 = data[8];
  4824. var m21 = data[1], m22 = data[5], m23 = data[9];
  4825. var m31 = data[2], m32 = data[6], m33 = data[10];
  4826. var trace = m11 + m22 + m33;
  4827. var s;
  4828. if (trace > 0) {
  4829. s = 0.5 / Math.sqrt(trace + 1.0);
  4830. result.w = 0.25 / s;
  4831. result.x = (m32 - m23) * s;
  4832. result.y = (m13 - m31) * s;
  4833. result.z = (m21 - m12) * s;
  4834. }
  4835. else if (m11 > m22 && m11 > m33) {
  4836. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4837. result.w = (m32 - m23) / s;
  4838. result.x = 0.25 * s;
  4839. result.y = (m12 + m21) / s;
  4840. result.z = (m13 + m31) / s;
  4841. }
  4842. else if (m22 > m33) {
  4843. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4844. result.w = (m13 - m31) / s;
  4845. result.x = (m12 + m21) / s;
  4846. result.y = 0.25 * s;
  4847. result.z = (m23 + m32) / s;
  4848. }
  4849. else {
  4850. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4851. result.w = (m21 - m12) / s;
  4852. result.x = (m13 + m31) / s;
  4853. result.y = (m23 + m32) / s;
  4854. result.z = 0.25 * s;
  4855. }
  4856. };
  4857. /**
  4858. * Returns the dot product (float) between the quaternions "left" and "right"
  4859. * @param left defines the left operand
  4860. * @param right defines the right operand
  4861. * @returns the dot product
  4862. */
  4863. Quaternion.Dot = function (left, right) {
  4864. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4865. };
  4866. /**
  4867. * Checks if the two quaternions are close to each other
  4868. * @param quat0 defines the first quaternion to check
  4869. * @param quat1 defines the second quaternion to check
  4870. * @returns true if the two quaternions are close to each other
  4871. */
  4872. Quaternion.AreClose = function (quat0, quat1) {
  4873. var dot = Quaternion.Dot(quat0, quat1);
  4874. return dot >= 0;
  4875. };
  4876. /**
  4877. * Creates an empty quaternion
  4878. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4879. */
  4880. Quaternion.Zero = function () {
  4881. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4882. };
  4883. /**
  4884. * Inverse a given quaternion
  4885. * @param q defines the source quaternion
  4886. * @returns a new quaternion as the inverted current quaternion
  4887. */
  4888. Quaternion.Inverse = function (q) {
  4889. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4890. };
  4891. /**
  4892. * Creates an identity quaternion
  4893. * @returns the identity quaternion
  4894. */
  4895. Quaternion.Identity = function () {
  4896. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4897. };
  4898. /**
  4899. * Gets a boolean indicating if the given quaternion is identity
  4900. * @param quaternion defines the quaternion to check
  4901. * @returns true if the quaternion is identity
  4902. */
  4903. Quaternion.IsIdentity = function (quaternion) {
  4904. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4905. };
  4906. /**
  4907. * Creates a quaternion from a rotation around an axis
  4908. * @param axis defines the axis to use
  4909. * @param angle defines the angle to use
  4910. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4911. */
  4912. Quaternion.RotationAxis = function (axis, angle) {
  4913. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4914. };
  4915. /**
  4916. * Creates a rotation around an axis and stores it into the given quaternion
  4917. * @param axis defines the axis to use
  4918. * @param angle defines the angle to use
  4919. * @param result defines the target quaternion
  4920. * @returns the target quaternion
  4921. */
  4922. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4923. var sin = Math.sin(angle / 2);
  4924. axis.normalize();
  4925. result.w = Math.cos(angle / 2);
  4926. result.x = axis.x * sin;
  4927. result.y = axis.y * sin;
  4928. result.z = axis.z * sin;
  4929. return result;
  4930. };
  4931. /**
  4932. * Creates a new quaternion from data stored into an array
  4933. * @param array defines the data source
  4934. * @param offset defines the offset in the source array where the data starts
  4935. * @returns a new quaternion
  4936. */
  4937. Quaternion.FromArray = function (array, offset) {
  4938. if (!offset) {
  4939. offset = 0;
  4940. }
  4941. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4942. };
  4943. /**
  4944. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4945. * @param yaw defines the rotation around Y axis
  4946. * @param pitch defines the rotation around X axis
  4947. * @param roll defines the rotation around Z axis
  4948. * @returns the new quaternion
  4949. */
  4950. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4951. var q = new Quaternion();
  4952. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4953. return q;
  4954. };
  4955. /**
  4956. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4957. * @param yaw defines the rotation around Y axis
  4958. * @param pitch defines the rotation around X axis
  4959. * @param roll defines the rotation around Z axis
  4960. * @param result defines the target quaternion
  4961. */
  4962. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4963. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4964. var halfRoll = roll * 0.5;
  4965. var halfPitch = pitch * 0.5;
  4966. var halfYaw = yaw * 0.5;
  4967. var sinRoll = Math.sin(halfRoll);
  4968. var cosRoll = Math.cos(halfRoll);
  4969. var sinPitch = Math.sin(halfPitch);
  4970. var cosPitch = Math.cos(halfPitch);
  4971. var sinYaw = Math.sin(halfYaw);
  4972. var cosYaw = Math.cos(halfYaw);
  4973. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4974. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4975. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4976. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4977. };
  4978. /**
  4979. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4980. * @param alpha defines the rotation around first axis
  4981. * @param beta defines the rotation around second axis
  4982. * @param gamma defines the rotation around third axis
  4983. * @returns the new quaternion
  4984. */
  4985. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4986. var result = new Quaternion();
  4987. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4988. return result;
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4992. * @param alpha defines the rotation around first axis
  4993. * @param beta defines the rotation around second axis
  4994. * @param gamma defines the rotation around third axis
  4995. * @param result defines the target quaternion
  4996. */
  4997. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4998. // Produces a quaternion from Euler angles in the z-x-z orientation
  4999. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5000. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5001. var halfBeta = beta * 0.5;
  5002. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5003. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5004. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5005. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5006. };
  5007. /**
  5008. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5009. * @param axis1 defines the first axis
  5010. * @param axis2 defines the second axis
  5011. * @param axis3 defines the third axis
  5012. * @returns the new quaternion
  5013. */
  5014. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5015. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5016. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5017. return quat;
  5018. };
  5019. /**
  5020. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5021. * @param axis1 defines the first axis
  5022. * @param axis2 defines the second axis
  5023. * @param axis3 defines the third axis
  5024. * @param ref defines the target quaternion
  5025. */
  5026. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5027. var rotMat = MathTmp.Matrix[0];
  5028. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5029. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5030. };
  5031. /**
  5032. * Interpolates between two quaternions
  5033. * @param left defines first quaternion
  5034. * @param right defines second quaternion
  5035. * @param amount defines the gradient to use
  5036. * @returns the new interpolated quaternion
  5037. */
  5038. Quaternion.Slerp = function (left, right, amount) {
  5039. var result = Quaternion.Identity();
  5040. Quaternion.SlerpToRef(left, right, amount, result);
  5041. return result;
  5042. };
  5043. /**
  5044. * Interpolates between two quaternions and stores it into a target quaternion
  5045. * @param left defines first quaternion
  5046. * @param right defines second quaternion
  5047. * @param amount defines the gradient to use
  5048. * @param result defines the target quaternion
  5049. */
  5050. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5051. var num2;
  5052. var num3;
  5053. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5054. var flag = false;
  5055. if (num4 < 0) {
  5056. flag = true;
  5057. num4 = -num4;
  5058. }
  5059. if (num4 > 0.999999) {
  5060. num3 = 1 - amount;
  5061. num2 = flag ? -amount : amount;
  5062. }
  5063. else {
  5064. var num5 = Math.acos(num4);
  5065. var num6 = (1.0 / Math.sin(num5));
  5066. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5067. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5068. }
  5069. result.x = (num3 * left.x) + (num2 * right.x);
  5070. result.y = (num3 * left.y) + (num2 * right.y);
  5071. result.z = (num3 * left.z) + (num2 * right.z);
  5072. result.w = (num3 * left.w) + (num2 * right.w);
  5073. };
  5074. /**
  5075. * Interpolate between two quaternions using Hermite interpolation
  5076. * @param value1 defines first quaternion
  5077. * @param tangent1 defines the incoming tangent
  5078. * @param value2 defines second quaternion
  5079. * @param tangent2 defines the outgoing tangent
  5080. * @param amount defines the target quaternion
  5081. * @returns the new interpolated quaternion
  5082. */
  5083. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5084. var squared = amount * amount;
  5085. var cubed = amount * squared;
  5086. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5087. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5088. var part3 = (cubed - (2.0 * squared)) + amount;
  5089. var part4 = cubed - squared;
  5090. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5091. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5092. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5093. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5094. return new Quaternion(x, y, z, w);
  5095. };
  5096. return Quaternion;
  5097. }());
  5098. BABYLON.Quaternion = Quaternion;
  5099. /**
  5100. * Class used to store matrix data (4x4)
  5101. */
  5102. var Matrix = /** @class */ (function () {
  5103. /**
  5104. * Creates an empty matrix (filled with zeros)
  5105. */
  5106. function Matrix() {
  5107. this._isIdentity = false;
  5108. this._isIdentityDirty = true;
  5109. /**
  5110. * Gets or sets the internal data of the matrix
  5111. */
  5112. this.m = new Float32Array(16);
  5113. this._markAsUpdated();
  5114. }
  5115. /** @hidden */
  5116. Matrix.prototype._markAsUpdated = function () {
  5117. this.updateFlag = Matrix._updateFlagSeed++;
  5118. this._isIdentityDirty = true;
  5119. };
  5120. // Properties
  5121. /**
  5122. * Check if the current matrix is indentity
  5123. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5124. * @returns true is the matrix is the identity matrix
  5125. */
  5126. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5127. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5128. if (this._isIdentityDirty) {
  5129. this._isIdentityDirty = false;
  5130. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5131. this._isIdentity = false;
  5132. }
  5133. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5134. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5135. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5136. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5137. this._isIdentity = false;
  5138. }
  5139. else {
  5140. this._isIdentity = true;
  5141. }
  5142. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5143. this._isIdentity = false;
  5144. }
  5145. }
  5146. return this._isIdentity;
  5147. };
  5148. /**
  5149. * Gets the determinant of the matrix
  5150. * @returns the matrix determinant
  5151. */
  5152. Matrix.prototype.determinant = function () {
  5153. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5154. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5155. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5156. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5157. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5158. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5159. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5160. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5161. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5162. };
  5163. // Methods
  5164. /**
  5165. * Returns the matrix as a Float32Array
  5166. * @returns the matrix underlying array
  5167. */
  5168. Matrix.prototype.toArray = function () {
  5169. return this.m;
  5170. };
  5171. /**
  5172. * Returns the matrix as a Float32Array
  5173. * @returns the matrix underlying array.
  5174. */
  5175. Matrix.prototype.asArray = function () {
  5176. return this.toArray();
  5177. };
  5178. /**
  5179. * Inverts the current matrix in place
  5180. * @returns the current inverted matrix
  5181. */
  5182. Matrix.prototype.invert = function () {
  5183. this.invertToRef(this);
  5184. return this;
  5185. };
  5186. /**
  5187. * Sets all the matrix elements to zero
  5188. * @returns the current matrix
  5189. */
  5190. Matrix.prototype.reset = function () {
  5191. for (var index = 0; index < 16; index++) {
  5192. this.m[index] = 0.0;
  5193. }
  5194. this._markAsUpdated();
  5195. return this;
  5196. };
  5197. /**
  5198. * Adds the current matrix with a second one
  5199. * @param other defines the matrix to add
  5200. * @returns a new matrix as the addition of the current matrix and the given one
  5201. */
  5202. Matrix.prototype.add = function (other) {
  5203. var result = new Matrix();
  5204. this.addToRef(other, result);
  5205. return result;
  5206. };
  5207. /**
  5208. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5209. * @param other defines the matrix to add
  5210. * @param result defines the target matrix
  5211. * @returns the current matrix
  5212. */
  5213. Matrix.prototype.addToRef = function (other, result) {
  5214. for (var index = 0; index < 16; index++) {
  5215. result.m[index] = this.m[index] + other.m[index];
  5216. }
  5217. result._markAsUpdated();
  5218. return this;
  5219. };
  5220. /**
  5221. * Adds in place the given matrix to the current matrix
  5222. * @param other defines the second operand
  5223. * @returns the current updated matrix
  5224. */
  5225. Matrix.prototype.addToSelf = function (other) {
  5226. for (var index = 0; index < 16; index++) {
  5227. this.m[index] += other.m[index];
  5228. }
  5229. this._markAsUpdated();
  5230. return this;
  5231. };
  5232. /**
  5233. * Sets the given matrix to the current inverted Matrix
  5234. * @param other defines the target matrix
  5235. * @returns the unmodified current matrix
  5236. */
  5237. Matrix.prototype.invertToRef = function (other) {
  5238. var l1 = this.m[0];
  5239. var l2 = this.m[1];
  5240. var l3 = this.m[2];
  5241. var l4 = this.m[3];
  5242. var l5 = this.m[4];
  5243. var l6 = this.m[5];
  5244. var l7 = this.m[6];
  5245. var l8 = this.m[7];
  5246. var l9 = this.m[8];
  5247. var l10 = this.m[9];
  5248. var l11 = this.m[10];
  5249. var l12 = this.m[11];
  5250. var l13 = this.m[12];
  5251. var l14 = this.m[13];
  5252. var l15 = this.m[14];
  5253. var l16 = this.m[15];
  5254. var l17 = (l11 * l16) - (l12 * l15);
  5255. var l18 = (l10 * l16) - (l12 * l14);
  5256. var l19 = (l10 * l15) - (l11 * l14);
  5257. var l20 = (l9 * l16) - (l12 * l13);
  5258. var l21 = (l9 * l15) - (l11 * l13);
  5259. var l22 = (l9 * l14) - (l10 * l13);
  5260. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5261. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5262. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5263. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5264. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5265. var l28 = (l7 * l16) - (l8 * l15);
  5266. var l29 = (l6 * l16) - (l8 * l14);
  5267. var l30 = (l6 * l15) - (l7 * l14);
  5268. var l31 = (l5 * l16) - (l8 * l13);
  5269. var l32 = (l5 * l15) - (l7 * l13);
  5270. var l33 = (l5 * l14) - (l6 * l13);
  5271. var l34 = (l7 * l12) - (l8 * l11);
  5272. var l35 = (l6 * l12) - (l8 * l10);
  5273. var l36 = (l6 * l11) - (l7 * l10);
  5274. var l37 = (l5 * l12) - (l8 * l9);
  5275. var l38 = (l5 * l11) - (l7 * l9);
  5276. var l39 = (l5 * l10) - (l6 * l9);
  5277. other.m[0] = l23 * l27;
  5278. other.m[4] = l24 * l27;
  5279. other.m[8] = l25 * l27;
  5280. other.m[12] = l26 * l27;
  5281. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5282. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5283. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5284. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5285. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5286. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5287. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5288. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5289. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5290. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5291. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5292. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5293. other._markAsUpdated();
  5294. return this;
  5295. };
  5296. /**
  5297. * Inserts the translation vector (using 3 floats) in the current matrix
  5298. * @param x defines the 1st component of the translation
  5299. * @param y defines the 2nd component of the translation
  5300. * @param z defines the 3rd component of the translation
  5301. * @returns the current updated matrix
  5302. */
  5303. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5304. this.m[12] = x;
  5305. this.m[13] = y;
  5306. this.m[14] = z;
  5307. this._markAsUpdated();
  5308. return this;
  5309. };
  5310. /**
  5311. * Inserts the translation vector in the current matrix
  5312. * @param vector3 defines the translation to insert
  5313. * @returns the current updated matrix
  5314. */
  5315. Matrix.prototype.setTranslation = function (vector3) {
  5316. this.m[12] = vector3.x;
  5317. this.m[13] = vector3.y;
  5318. this.m[14] = vector3.z;
  5319. this._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Gets the translation value of the current matrix
  5324. * @returns a new Vector3 as the extracted translation from the matrix
  5325. */
  5326. Matrix.prototype.getTranslation = function () {
  5327. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5328. };
  5329. /**
  5330. * Fill a Vector3 with the extracted translation from the matrix
  5331. * @param result defines the Vector3 where to store the translation
  5332. * @returns the current matrix
  5333. */
  5334. Matrix.prototype.getTranslationToRef = function (result) {
  5335. result.x = this.m[12];
  5336. result.y = this.m[13];
  5337. result.z = this.m[14];
  5338. return this;
  5339. };
  5340. /**
  5341. * Remove rotation and scaling part from the matrix
  5342. * @returns the updated matrix
  5343. */
  5344. Matrix.prototype.removeRotationAndScaling = function () {
  5345. this.setRowFromFloats(0, 1, 0, 0, 0);
  5346. this.setRowFromFloats(1, 0, 1, 0, 0);
  5347. this.setRowFromFloats(2, 0, 0, 1, 0);
  5348. return this;
  5349. };
  5350. /**
  5351. * Multiply two matrices
  5352. * @param other defines the second operand
  5353. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5354. */
  5355. Matrix.prototype.multiply = function (other) {
  5356. var result = new Matrix();
  5357. this.multiplyToRef(other, result);
  5358. return result;
  5359. };
  5360. /**
  5361. * Copy the current matrix from the given one
  5362. * @param other defines the source matrix
  5363. * @returns the current updated matrix
  5364. */
  5365. Matrix.prototype.copyFrom = function (other) {
  5366. for (var index = 0; index < 16; index++) {
  5367. this.m[index] = other.m[index];
  5368. }
  5369. this._markAsUpdated();
  5370. return this;
  5371. };
  5372. /**
  5373. * Populates the given array from the starting index with the current matrix values
  5374. * @param array defines the target array
  5375. * @param offset defines the offset in the target array where to start storing values
  5376. * @returns the current matrix
  5377. */
  5378. Matrix.prototype.copyToArray = function (array, offset) {
  5379. if (offset === void 0) { offset = 0; }
  5380. for (var index = 0; index < 16; index++) {
  5381. array[offset + index] = this.m[index];
  5382. }
  5383. return this;
  5384. };
  5385. /**
  5386. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5387. * @param other defines the second operand
  5388. * @param result defines the matrix where to store the multiplication
  5389. * @returns the current matrix
  5390. */
  5391. Matrix.prototype.multiplyToRef = function (other, result) {
  5392. this.multiplyToArray(other, result.m, 0);
  5393. result._markAsUpdated();
  5394. return this;
  5395. };
  5396. /**
  5397. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5398. * @param other defines the second operand
  5399. * @param result defines the array where to store the multiplication
  5400. * @param offset defines the offset in the target array where to start storing values
  5401. * @returns the current matrix
  5402. */
  5403. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5404. var tm0 = this.m[0];
  5405. var tm1 = this.m[1];
  5406. var tm2 = this.m[2];
  5407. var tm3 = this.m[3];
  5408. var tm4 = this.m[4];
  5409. var tm5 = this.m[5];
  5410. var tm6 = this.m[6];
  5411. var tm7 = this.m[7];
  5412. var tm8 = this.m[8];
  5413. var tm9 = this.m[9];
  5414. var tm10 = this.m[10];
  5415. var tm11 = this.m[11];
  5416. var tm12 = this.m[12];
  5417. var tm13 = this.m[13];
  5418. var tm14 = this.m[14];
  5419. var tm15 = this.m[15];
  5420. var om0 = other.m[0];
  5421. var om1 = other.m[1];
  5422. var om2 = other.m[2];
  5423. var om3 = other.m[3];
  5424. var om4 = other.m[4];
  5425. var om5 = other.m[5];
  5426. var om6 = other.m[6];
  5427. var om7 = other.m[7];
  5428. var om8 = other.m[8];
  5429. var om9 = other.m[9];
  5430. var om10 = other.m[10];
  5431. var om11 = other.m[11];
  5432. var om12 = other.m[12];
  5433. var om13 = other.m[13];
  5434. var om14 = other.m[14];
  5435. var om15 = other.m[15];
  5436. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5437. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5438. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5439. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5440. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5441. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5442. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5443. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5444. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5445. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5446. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5447. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5448. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5449. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5450. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5451. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5452. return this;
  5453. };
  5454. /**
  5455. * Check equality between this matrix and a second one
  5456. * @param value defines the second matrix to compare
  5457. * @returns true is the current matrix and the given one values are strictly equal
  5458. */
  5459. Matrix.prototype.equals = function (value) {
  5460. return value &&
  5461. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5462. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5463. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5464. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5465. };
  5466. /**
  5467. * Clone the current matrix
  5468. * @returns a new matrix from the current matrix
  5469. */
  5470. Matrix.prototype.clone = function () {
  5471. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5472. };
  5473. /**
  5474. * Returns the name of the current matrix class
  5475. * @returns the string "Matrix"
  5476. */
  5477. Matrix.prototype.getClassName = function () {
  5478. return "Matrix";
  5479. };
  5480. /**
  5481. * Gets the hash code of the current matrix
  5482. * @returns the hash code
  5483. */
  5484. Matrix.prototype.getHashCode = function () {
  5485. var hash = this.m[0] || 0;
  5486. for (var i = 1; i < 16; i++) {
  5487. hash = (hash * 397) ^ (this.m[i] || 0);
  5488. }
  5489. return hash;
  5490. };
  5491. /**
  5492. * Decomposes the current Matrix into a translation, rotation and scaling components
  5493. * @param scale defines the scale vector3 given as a reference to update
  5494. * @param rotation defines the rotation quaternion given as a reference to update
  5495. * @param translation defines the translation vector3 given as a reference to update
  5496. * @returns true if operation was successful
  5497. */
  5498. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5499. if (translation) {
  5500. translation.x = this.m[12];
  5501. translation.y = this.m[13];
  5502. translation.z = this.m[14];
  5503. }
  5504. scale = scale || MathTmp.Vector3[0];
  5505. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5506. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5507. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5508. if (this.determinant() <= 0) {
  5509. scale.y *= -1;
  5510. }
  5511. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5512. if (rotation) {
  5513. rotation.x = 0;
  5514. rotation.y = 0;
  5515. rotation.z = 0;
  5516. rotation.w = 1;
  5517. }
  5518. return false;
  5519. }
  5520. if (rotation) {
  5521. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5522. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5523. }
  5524. return true;
  5525. };
  5526. /**
  5527. * Gets specific row of the matrix
  5528. * @param index defines the number of the row to get
  5529. * @returns the index-th row of the current matrix as a new Vector4
  5530. */
  5531. Matrix.prototype.getRow = function (index) {
  5532. if (index < 0 || index > 3) {
  5533. return null;
  5534. }
  5535. var i = index * 4;
  5536. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5537. };
  5538. /**
  5539. * Sets the index-th row of the current matrix to the vector4 values
  5540. * @param index defines the number of the row to set
  5541. * @param row defines the target vector4
  5542. * @returns the updated current matrix
  5543. */
  5544. Matrix.prototype.setRow = function (index, row) {
  5545. if (index < 0 || index > 3) {
  5546. return this;
  5547. }
  5548. var i = index * 4;
  5549. this.m[i + 0] = row.x;
  5550. this.m[i + 1] = row.y;
  5551. this.m[i + 2] = row.z;
  5552. this.m[i + 3] = row.w;
  5553. this._markAsUpdated();
  5554. return this;
  5555. };
  5556. /**
  5557. * Compute the transpose of the matrix
  5558. * @returns the new transposed matrix
  5559. */
  5560. Matrix.prototype.transpose = function () {
  5561. return Matrix.Transpose(this);
  5562. };
  5563. /**
  5564. * Compute the transpose of the matrix and store it in a given matrix
  5565. * @param result defines the target matrix
  5566. * @returns the current matrix
  5567. */
  5568. Matrix.prototype.transposeToRef = function (result) {
  5569. Matrix.TransposeToRef(this, result);
  5570. return this;
  5571. };
  5572. /**
  5573. * Sets the index-th row of the current matrix with the given 4 x float values
  5574. * @param index defines the row index
  5575. * @param x defines the x component to set
  5576. * @param y defines the y component to set
  5577. * @param z defines the z component to set
  5578. * @param w defines the w component to set
  5579. * @returns the updated current matrix
  5580. */
  5581. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5582. if (index < 0 || index > 3) {
  5583. return this;
  5584. }
  5585. var i = index * 4;
  5586. this.m[i + 0] = x;
  5587. this.m[i + 1] = y;
  5588. this.m[i + 2] = z;
  5589. this.m[i + 3] = w;
  5590. this._markAsUpdated();
  5591. return this;
  5592. };
  5593. /**
  5594. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5595. * @param scale defines the scale factor
  5596. * @returns a new matrix
  5597. */
  5598. Matrix.prototype.scale = function (scale) {
  5599. var result = new Matrix();
  5600. this.scaleToRef(scale, result);
  5601. return result;
  5602. };
  5603. /**
  5604. * Scale the current matrix values by a factor to a given result matrix
  5605. * @param scale defines the scale factor
  5606. * @param result defines the matrix to store the result
  5607. * @returns the current matrix
  5608. */
  5609. Matrix.prototype.scaleToRef = function (scale, result) {
  5610. for (var index = 0; index < 16; index++) {
  5611. result.m[index] = this.m[index] * scale;
  5612. }
  5613. result._markAsUpdated();
  5614. return this;
  5615. };
  5616. /**
  5617. * Scale the current matrix values by a factor and add the result to a given matrix
  5618. * @param scale defines the scale factor
  5619. * @param result defines the Matrix to store the result
  5620. * @returns the current matrix
  5621. */
  5622. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5623. for (var index = 0; index < 16; index++) {
  5624. result.m[index] += this.m[index] * scale;
  5625. }
  5626. result._markAsUpdated();
  5627. return this;
  5628. };
  5629. /**
  5630. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5631. * @param ref matrix to store the result
  5632. */
  5633. Matrix.prototype.toNormalMatrix = function (ref) {
  5634. this.invertToRef(ref);
  5635. ref.transpose();
  5636. var m = ref.m;
  5637. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5638. };
  5639. /**
  5640. * Gets only rotation part of the current matrix
  5641. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5642. */
  5643. Matrix.prototype.getRotationMatrix = function () {
  5644. var result = Matrix.Identity();
  5645. this.getRotationMatrixToRef(result);
  5646. return result;
  5647. };
  5648. /**
  5649. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5650. * @param result defines the target matrix to store data to
  5651. * @returns the current matrix
  5652. */
  5653. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5654. var m = this.m;
  5655. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5656. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5657. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5658. if (this.determinant() <= 0) {
  5659. sy *= -1;
  5660. }
  5661. if (sx === 0 || sy === 0 || sz === 0) {
  5662. Matrix.IdentityToRef(result);
  5663. }
  5664. else {
  5665. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5666. }
  5667. return this;
  5668. };
  5669. // Statics
  5670. /**
  5671. * Creates a matrix from an array
  5672. * @param array defines the source array
  5673. * @param offset defines an offset in the source array
  5674. * @returns a new Matrix set from the starting index of the given array
  5675. */
  5676. Matrix.FromArray = function (array, offset) {
  5677. var result = new Matrix();
  5678. if (!offset) {
  5679. offset = 0;
  5680. }
  5681. Matrix.FromArrayToRef(array, offset, result);
  5682. return result;
  5683. };
  5684. /**
  5685. * Copy the content of an array into a given matrix
  5686. * @param array defines the source array
  5687. * @param offset defines an offset in the source array
  5688. * @param result defines the target matrix
  5689. */
  5690. Matrix.FromArrayToRef = function (array, offset, result) {
  5691. for (var index = 0; index < 16; index++) {
  5692. result.m[index] = array[index + offset];
  5693. }
  5694. result._markAsUpdated();
  5695. };
  5696. /**
  5697. * Stores an array into a matrix after having multiplied each component by a given factor
  5698. * @param array defines the source array
  5699. * @param offset defines the offset in the source array
  5700. * @param scale defines the scaling factor
  5701. * @param result defines the target matrix
  5702. */
  5703. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5704. for (var index = 0; index < 16; index++) {
  5705. result.m[index] = array[index + offset] * scale;
  5706. }
  5707. result._markAsUpdated();
  5708. };
  5709. /**
  5710. * Stores a list of values (16) inside a given matrix
  5711. * @param initialM11 defines 1st value of 1st row
  5712. * @param initialM12 defines 2nd value of 1st row
  5713. * @param initialM13 defines 3rd value of 1st row
  5714. * @param initialM14 defines 4th value of 1st row
  5715. * @param initialM21 defines 1st value of 2nd row
  5716. * @param initialM22 defines 2nd value of 2nd row
  5717. * @param initialM23 defines 3rd value of 2nd row
  5718. * @param initialM24 defines 4th value of 2nd row
  5719. * @param initialM31 defines 1st value of 3rd row
  5720. * @param initialM32 defines 2nd value of 3rd row
  5721. * @param initialM33 defines 3rd value of 3rd row
  5722. * @param initialM34 defines 4th value of 3rd row
  5723. * @param initialM41 defines 1st value of 4th row
  5724. * @param initialM42 defines 2nd value of 4th row
  5725. * @param initialM43 defines 3rd value of 4th row
  5726. * @param initialM44 defines 4th value of 4th row
  5727. * @param result defines the target matrix
  5728. */
  5729. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5730. result.m[0] = initialM11;
  5731. result.m[1] = initialM12;
  5732. result.m[2] = initialM13;
  5733. result.m[3] = initialM14;
  5734. result.m[4] = initialM21;
  5735. result.m[5] = initialM22;
  5736. result.m[6] = initialM23;
  5737. result.m[7] = initialM24;
  5738. result.m[8] = initialM31;
  5739. result.m[9] = initialM32;
  5740. result.m[10] = initialM33;
  5741. result.m[11] = initialM34;
  5742. result.m[12] = initialM41;
  5743. result.m[13] = initialM42;
  5744. result.m[14] = initialM43;
  5745. result.m[15] = initialM44;
  5746. result._markAsUpdated();
  5747. };
  5748. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5749. /**
  5750. * Gets an identity matrix that must not be updated
  5751. */
  5752. get: function () {
  5753. return Matrix._identityReadOnly;
  5754. },
  5755. enumerable: true,
  5756. configurable: true
  5757. });
  5758. /**
  5759. * Creates new matrix from a list of values (16)
  5760. * @param initialM11 defines 1st value of 1st row
  5761. * @param initialM12 defines 2nd value of 1st row
  5762. * @param initialM13 defines 3rd value of 1st row
  5763. * @param initialM14 defines 4th value of 1st row
  5764. * @param initialM21 defines 1st value of 2nd row
  5765. * @param initialM22 defines 2nd value of 2nd row
  5766. * @param initialM23 defines 3rd value of 2nd row
  5767. * @param initialM24 defines 4th value of 2nd row
  5768. * @param initialM31 defines 1st value of 3rd row
  5769. * @param initialM32 defines 2nd value of 3rd row
  5770. * @param initialM33 defines 3rd value of 3rd row
  5771. * @param initialM34 defines 4th value of 3rd row
  5772. * @param initialM41 defines 1st value of 4th row
  5773. * @param initialM42 defines 2nd value of 4th row
  5774. * @param initialM43 defines 3rd value of 4th row
  5775. * @param initialM44 defines 4th value of 4th row
  5776. * @returns the new matrix
  5777. */
  5778. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5779. var result = new Matrix();
  5780. result.m[0] = initialM11;
  5781. result.m[1] = initialM12;
  5782. result.m[2] = initialM13;
  5783. result.m[3] = initialM14;
  5784. result.m[4] = initialM21;
  5785. result.m[5] = initialM22;
  5786. result.m[6] = initialM23;
  5787. result.m[7] = initialM24;
  5788. result.m[8] = initialM31;
  5789. result.m[9] = initialM32;
  5790. result.m[10] = initialM33;
  5791. result.m[11] = initialM34;
  5792. result.m[12] = initialM41;
  5793. result.m[13] = initialM42;
  5794. result.m[14] = initialM43;
  5795. result.m[15] = initialM44;
  5796. return result;
  5797. };
  5798. /**
  5799. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5800. * @param scale defines the scale vector3
  5801. * @param rotation defines the rotation quaternion
  5802. * @param translation defines the translation vector3
  5803. * @returns a new matrix
  5804. */
  5805. Matrix.Compose = function (scale, rotation, translation) {
  5806. var result = Matrix.Identity();
  5807. Matrix.ComposeToRef(scale, rotation, translation, result);
  5808. return result;
  5809. };
  5810. /**
  5811. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5812. * @param scale defines the scale vector3
  5813. * @param rotation defines the rotation quaternion
  5814. * @param translation defines the translation vector3
  5815. * @param result defines the target matrix
  5816. */
  5817. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5818. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5819. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5820. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5821. result.setTranslation(translation);
  5822. };
  5823. /**
  5824. * Creates a new identity matrix
  5825. * @returns a new identity matrix
  5826. */
  5827. Matrix.Identity = function () {
  5828. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5829. };
  5830. /**
  5831. * Creates a new identity matrix and stores the result in a given matrix
  5832. * @param result defines the target matrix
  5833. */
  5834. Matrix.IdentityToRef = function (result) {
  5835. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5836. };
  5837. /**
  5838. * Creates a new zero matrix
  5839. * @returns a new zero matrix
  5840. */
  5841. Matrix.Zero = function () {
  5842. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5843. };
  5844. /**
  5845. * Creates a new rotation matrix for "angle" radians around the X axis
  5846. * @param angle defines the angle (in radians) to use
  5847. * @return the new matrix
  5848. */
  5849. Matrix.RotationX = function (angle) {
  5850. var result = new Matrix();
  5851. Matrix.RotationXToRef(angle, result);
  5852. return result;
  5853. };
  5854. /**
  5855. * Creates a new matrix as the invert of a given matrix
  5856. * @param source defines the source matrix
  5857. * @returns the new matrix
  5858. */
  5859. Matrix.Invert = function (source) {
  5860. var result = new Matrix();
  5861. source.invertToRef(result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5866. * @param angle defines the angle (in radians) to use
  5867. * @param result defines the target matrix
  5868. */
  5869. Matrix.RotationXToRef = function (angle, result) {
  5870. var s = Math.sin(angle);
  5871. var c = Math.cos(angle);
  5872. result.m[0] = 1.0;
  5873. result.m[15] = 1.0;
  5874. result.m[5] = c;
  5875. result.m[10] = c;
  5876. result.m[9] = -s;
  5877. result.m[6] = s;
  5878. result.m[1] = 0.0;
  5879. result.m[2] = 0.0;
  5880. result.m[3] = 0.0;
  5881. result.m[4] = 0.0;
  5882. result.m[7] = 0.0;
  5883. result.m[8] = 0.0;
  5884. result.m[11] = 0.0;
  5885. result.m[12] = 0.0;
  5886. result.m[13] = 0.0;
  5887. result.m[14] = 0.0;
  5888. result._markAsUpdated();
  5889. };
  5890. /**
  5891. * Creates a new rotation matrix for "angle" radians around the Y axis
  5892. * @param angle defines the angle (in radians) to use
  5893. * @return the new matrix
  5894. */
  5895. Matrix.RotationY = function (angle) {
  5896. var result = new Matrix();
  5897. Matrix.RotationYToRef(angle, result);
  5898. return result;
  5899. };
  5900. /**
  5901. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5902. * @param angle defines the angle (in radians) to use
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.RotationYToRef = function (angle, result) {
  5906. var s = Math.sin(angle);
  5907. var c = Math.cos(angle);
  5908. result.m[5] = 1.0;
  5909. result.m[15] = 1.0;
  5910. result.m[0] = c;
  5911. result.m[2] = -s;
  5912. result.m[8] = s;
  5913. result.m[10] = c;
  5914. result.m[1] = 0.0;
  5915. result.m[3] = 0.0;
  5916. result.m[4] = 0.0;
  5917. result.m[6] = 0.0;
  5918. result.m[7] = 0.0;
  5919. result.m[9] = 0.0;
  5920. result.m[11] = 0.0;
  5921. result.m[12] = 0.0;
  5922. result.m[13] = 0.0;
  5923. result.m[14] = 0.0;
  5924. result._markAsUpdated();
  5925. };
  5926. /**
  5927. * Creates a new rotation matrix for "angle" radians around the Z axis
  5928. * @param angle defines the angle (in radians) to use
  5929. * @return the new matrix
  5930. */
  5931. Matrix.RotationZ = function (angle) {
  5932. var result = new Matrix();
  5933. Matrix.RotationZToRef(angle, result);
  5934. return result;
  5935. };
  5936. /**
  5937. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5938. * @param angle defines the angle (in radians) to use
  5939. * @param result defines the target matrix
  5940. */
  5941. Matrix.RotationZToRef = function (angle, result) {
  5942. var s = Math.sin(angle);
  5943. var c = Math.cos(angle);
  5944. result.m[10] = 1.0;
  5945. result.m[15] = 1.0;
  5946. result.m[0] = c;
  5947. result.m[1] = s;
  5948. result.m[4] = -s;
  5949. result.m[5] = c;
  5950. result.m[2] = 0.0;
  5951. result.m[3] = 0.0;
  5952. result.m[6] = 0.0;
  5953. result.m[7] = 0.0;
  5954. result.m[8] = 0.0;
  5955. result.m[9] = 0.0;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result._markAsUpdated();
  5961. };
  5962. /**
  5963. * Creates a new rotation matrix for "angle" radians around the given axis
  5964. * @param axis defines the axis to use
  5965. * @param angle defines the angle (in radians) to use
  5966. * @return the new matrix
  5967. */
  5968. Matrix.RotationAxis = function (axis, angle) {
  5969. var result = Matrix.Zero();
  5970. Matrix.RotationAxisToRef(axis, angle, result);
  5971. return result;
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5975. * @param axis defines the axis to use
  5976. * @param angle defines the angle (in radians) to use
  5977. * @param result defines the target matrix
  5978. */
  5979. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5980. var s = Math.sin(-angle);
  5981. var c = Math.cos(-angle);
  5982. var c1 = 1 - c;
  5983. axis.normalize();
  5984. result.m[0] = (axis.x * axis.x) * c1 + c;
  5985. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5986. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5987. result.m[3] = 0.0;
  5988. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5989. result.m[5] = (axis.y * axis.y) * c1 + c;
  5990. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5991. result.m[7] = 0.0;
  5992. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5993. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5994. result.m[10] = (axis.z * axis.z) * c1 + c;
  5995. result.m[11] = 0.0;
  5996. result.m[15] = 1.0;
  5997. result._markAsUpdated();
  5998. };
  5999. /**
  6000. * Creates a rotation matrix
  6001. * @param yaw defines the yaw angle in radians (Y axis)
  6002. * @param pitch defines the pitch angle in radians (X axis)
  6003. * @param roll defines the roll angle in radians (X axis)
  6004. * @returns the new rotation matrix
  6005. */
  6006. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6007. var result = new Matrix();
  6008. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6009. return result;
  6010. };
  6011. /**
  6012. * Creates a rotation matrix and stores it in a given matrix
  6013. * @param yaw defines the yaw angle in radians (Y axis)
  6014. * @param pitch defines the pitch angle in radians (X axis)
  6015. * @param roll defines the roll angle in radians (X axis)
  6016. * @param result defines the target matrix
  6017. */
  6018. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6019. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6020. this._tempQuaternion.toRotationMatrix(result);
  6021. };
  6022. /**
  6023. * Creates a scaling matrix
  6024. * @param x defines the scale factor on X axis
  6025. * @param y defines the scale factor on Y axis
  6026. * @param z defines the scale factor on Z axis
  6027. * @returns the new matrix
  6028. */
  6029. Matrix.Scaling = function (x, y, z) {
  6030. var result = Matrix.Zero();
  6031. Matrix.ScalingToRef(x, y, z, result);
  6032. return result;
  6033. };
  6034. /**
  6035. * Creates a scaling matrix and stores it in a given matrix
  6036. * @param x defines the scale factor on X axis
  6037. * @param y defines the scale factor on Y axis
  6038. * @param z defines the scale factor on Z axis
  6039. * @param result defines the target matrix
  6040. */
  6041. Matrix.ScalingToRef = function (x, y, z, result) {
  6042. result.m[0] = x;
  6043. result.m[1] = 0.0;
  6044. result.m[2] = 0.0;
  6045. result.m[3] = 0.0;
  6046. result.m[4] = 0.0;
  6047. result.m[5] = y;
  6048. result.m[6] = 0.0;
  6049. result.m[7] = 0.0;
  6050. result.m[8] = 0.0;
  6051. result.m[9] = 0.0;
  6052. result.m[10] = z;
  6053. result.m[11] = 0.0;
  6054. result.m[12] = 0.0;
  6055. result.m[13] = 0.0;
  6056. result.m[14] = 0.0;
  6057. result.m[15] = 1.0;
  6058. result._markAsUpdated();
  6059. };
  6060. /**
  6061. * Creates a translation matrix
  6062. * @param x defines the translation on X axis
  6063. * @param y defines the translation on Y axis
  6064. * @param z defines the translationon Z axis
  6065. * @returns the new matrix
  6066. */
  6067. Matrix.Translation = function (x, y, z) {
  6068. var result = Matrix.Identity();
  6069. Matrix.TranslationToRef(x, y, z, result);
  6070. return result;
  6071. };
  6072. /**
  6073. * Creates a translation matrix and stores it in a given matrix
  6074. * @param x defines the translation on X axis
  6075. * @param y defines the translation on Y axis
  6076. * @param z defines the translationon Z axis
  6077. * @param result defines the target matrix
  6078. */
  6079. Matrix.TranslationToRef = function (x, y, z, result) {
  6080. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6081. };
  6082. /**
  6083. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6084. * @param startValue defines the start value
  6085. * @param endValue defines the end value
  6086. * @param gradient defines the gradient factor
  6087. * @returns the new matrix
  6088. */
  6089. Matrix.Lerp = function (startValue, endValue, gradient) {
  6090. var result = Matrix.Zero();
  6091. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6092. return result;
  6093. };
  6094. /**
  6095. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6096. * @param startValue defines the start value
  6097. * @param endValue defines the end value
  6098. * @param gradient defines the gradient factor
  6099. * @param result defines the Matrix object where to store data
  6100. */
  6101. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6102. for (var index = 0; index < 16; index++) {
  6103. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6104. }
  6105. result._markAsUpdated();
  6106. };
  6107. /**
  6108. * Builds a new matrix whose values are computed by:
  6109. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6110. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6111. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6112. * @param startValue defines the first matrix
  6113. * @param endValue defines the second matrix
  6114. * @param gradient defines the gradient between the two matrices
  6115. * @returns the new matrix
  6116. */
  6117. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6118. var result = Matrix.Zero();
  6119. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6120. return result;
  6121. };
  6122. /**
  6123. * Update a matrix to values which are computed by:
  6124. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6125. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6126. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6127. * @param startValue defines the first matrix
  6128. * @param endValue defines the second matrix
  6129. * @param gradient defines the gradient between the two matrices
  6130. * @param result defines the target matrix
  6131. */
  6132. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6133. var startScale = MathTmp.Vector3[0];
  6134. var startRotation = MathTmp.Quaternion[0];
  6135. var startTranslation = MathTmp.Vector3[1];
  6136. startValue.decompose(startScale, startRotation, startTranslation);
  6137. var endScale = MathTmp.Vector3[2];
  6138. var endRotation = MathTmp.Quaternion[1];
  6139. var endTranslation = MathTmp.Vector3[3];
  6140. endValue.decompose(endScale, endRotation, endTranslation);
  6141. var resultScale = MathTmp.Vector3[4];
  6142. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6143. var resultRotation = MathTmp.Quaternion[2];
  6144. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6145. var resultTranslation = MathTmp.Vector3[5];
  6146. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6147. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6148. };
  6149. /**
  6150. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6151. * This function works in left handed mode
  6152. * @param eye defines the final position of the entity
  6153. * @param target defines where the entity should look at
  6154. * @param up defines the up vector for the entity
  6155. * @returns the new matrix
  6156. */
  6157. Matrix.LookAtLH = function (eye, target, up) {
  6158. var result = Matrix.Zero();
  6159. Matrix.LookAtLHToRef(eye, target, up, result);
  6160. return result;
  6161. };
  6162. /**
  6163. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6164. * This function works in left handed mode
  6165. * @param eye defines the final position of the entity
  6166. * @param target defines where the entity should look at
  6167. * @param up defines the up vector for the entity
  6168. * @param result defines the target matrix
  6169. */
  6170. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6171. // Z axis
  6172. target.subtractToRef(eye, this._zAxis);
  6173. this._zAxis.normalize();
  6174. // X axis
  6175. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6176. if (this._xAxis.lengthSquared() === 0) {
  6177. this._xAxis.x = 1.0;
  6178. }
  6179. else {
  6180. this._xAxis.normalize();
  6181. }
  6182. // Y axis
  6183. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6184. this._yAxis.normalize();
  6185. // Eye angles
  6186. var ex = -Vector3.Dot(this._xAxis, eye);
  6187. var ey = -Vector3.Dot(this._yAxis, eye);
  6188. var ez = -Vector3.Dot(this._zAxis, eye);
  6189. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6190. };
  6191. /**
  6192. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6193. * This function works in right handed mode
  6194. * @param eye defines the final position of the entity
  6195. * @param target defines where the entity should look at
  6196. * @param up defines the up vector for the entity
  6197. * @returns the new matrix
  6198. */
  6199. Matrix.LookAtRH = function (eye, target, up) {
  6200. var result = Matrix.Zero();
  6201. Matrix.LookAtRHToRef(eye, target, up, result);
  6202. return result;
  6203. };
  6204. /**
  6205. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6206. * This function works in right handed mode
  6207. * @param eye defines the final position of the entity
  6208. * @param target defines where the entity should look at
  6209. * @param up defines the up vector for the entity
  6210. * @param result defines the target matrix
  6211. */
  6212. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6213. // Z axis
  6214. eye.subtractToRef(target, this._zAxis);
  6215. this._zAxis.normalize();
  6216. // X axis
  6217. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6218. if (this._xAxis.lengthSquared() === 0) {
  6219. this._xAxis.x = 1.0;
  6220. }
  6221. else {
  6222. this._xAxis.normalize();
  6223. }
  6224. // Y axis
  6225. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6226. this._yAxis.normalize();
  6227. // Eye angles
  6228. var ex = -Vector3.Dot(this._xAxis, eye);
  6229. var ey = -Vector3.Dot(this._yAxis, eye);
  6230. var ez = -Vector3.Dot(this._zAxis, eye);
  6231. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6232. };
  6233. /**
  6234. * Create a left-handed orthographic projection matrix
  6235. * @param width defines the viewport width
  6236. * @param height defines the viewport height
  6237. * @param znear defines the near clip plane
  6238. * @param zfar defines the far clip plane
  6239. * @returns a new matrix as a left-handed orthographic projection matrix
  6240. */
  6241. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6242. var matrix = Matrix.Zero();
  6243. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6244. return matrix;
  6245. };
  6246. /**
  6247. * Store a left-handed orthographic projection to a given matrix
  6248. * @param width defines the viewport width
  6249. * @param height defines the viewport height
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @param result defines the target matrix
  6253. */
  6254. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6255. var n = znear;
  6256. var f = zfar;
  6257. var a = 2.0 / width;
  6258. var b = 2.0 / height;
  6259. var c = 2.0 / (f - n);
  6260. var d = -(f + n) / (f - n);
  6261. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6262. };
  6263. /**
  6264. * Create a left-handed orthographic projection matrix
  6265. * @param left defines the viewport left coordinate
  6266. * @param right defines the viewport right coordinate
  6267. * @param bottom defines the viewport bottom coordinate
  6268. * @param top defines the viewport top coordinate
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @returns a new matrix as a left-handed orthographic projection matrix
  6272. */
  6273. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6274. var matrix = Matrix.Zero();
  6275. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6276. return matrix;
  6277. };
  6278. /**
  6279. * Stores a left-handed orthographic projection into a given matrix
  6280. * @param left defines the viewport left coordinate
  6281. * @param right defines the viewport right coordinate
  6282. * @param bottom defines the viewport bottom coordinate
  6283. * @param top defines the viewport top coordinate
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @param result defines the target matrix
  6287. */
  6288. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6289. var n = znear;
  6290. var f = zfar;
  6291. var a = 2.0 / (right - left);
  6292. var b = 2.0 / (top - bottom);
  6293. var c = 2.0 / (f - n);
  6294. var d = -(f + n) / (f - n);
  6295. var i0 = (left + right) / (left - right);
  6296. var i1 = (top + bottom) / (bottom - top);
  6297. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6298. };
  6299. /**
  6300. * Creates a right-handed orthographic projection matrix
  6301. * @param left defines the viewport left coordinate
  6302. * @param right defines the viewport right coordinate
  6303. * @param bottom defines the viewport bottom coordinate
  6304. * @param top defines the viewport top coordinate
  6305. * @param znear defines the near clip plane
  6306. * @param zfar defines the far clip plane
  6307. * @returns a new matrix as a right-handed orthographic projection matrix
  6308. */
  6309. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6310. var matrix = Matrix.Zero();
  6311. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6312. return matrix;
  6313. };
  6314. /**
  6315. * Stores a right-handed orthographic projection into a given matrix
  6316. * @param left defines the viewport left coordinate
  6317. * @param right defines the viewport right coordinate
  6318. * @param bottom defines the viewport bottom coordinate
  6319. * @param top defines the viewport top coordinate
  6320. * @param znear defines the near clip plane
  6321. * @param zfar defines the far clip plane
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6325. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6326. result.m[10] *= -1.0;
  6327. };
  6328. /**
  6329. * Creates a left-handed perspective projection matrix
  6330. * @param width defines the viewport width
  6331. * @param height defines the viewport height
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @returns a new matrix as a left-handed perspective projection matrix
  6335. */
  6336. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6337. var matrix = Matrix.Zero();
  6338. var n = znear;
  6339. var f = zfar;
  6340. var a = 2.0 * n / width;
  6341. var b = 2.0 * n / height;
  6342. var c = (f + n) / (f - n);
  6343. var d = -2.0 * f * n / (f - n);
  6344. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6345. return matrix;
  6346. };
  6347. /**
  6348. * Creates a left-handed perspective projection matrix
  6349. * @param fov defines the horizontal field of view
  6350. * @param aspect defines the aspect ratio
  6351. * @param znear defines the near clip plane
  6352. * @param zfar defines the far clip plane
  6353. * @returns a new matrix as a left-handed perspective projection matrix
  6354. */
  6355. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6356. var matrix = Matrix.Zero();
  6357. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6358. return matrix;
  6359. };
  6360. /**
  6361. * Stores a left-handed perspective projection into a given matrix
  6362. * @param fov defines the horizontal field of view
  6363. * @param aspect defines the aspect ratio
  6364. * @param znear defines the near clip plane
  6365. * @param zfar defines the far clip plane
  6366. * @param result defines the target matrix
  6367. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6368. */
  6369. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6370. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6371. var n = znear;
  6372. var f = zfar;
  6373. var t = 1.0 / (Math.tan(fov * 0.5));
  6374. var a = isVerticalFovFixed ? (t / aspect) : t;
  6375. var b = isVerticalFovFixed ? t : (t * aspect);
  6376. var c = (f + n) / (f - n);
  6377. var d = -2.0 * f * n / (f - n);
  6378. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6379. };
  6380. /**
  6381. * Creates a right-handed perspective projection matrix
  6382. * @param fov defines the horizontal field of view
  6383. * @param aspect defines the aspect ratio
  6384. * @param znear defines the near clip plane
  6385. * @param zfar defines the far clip plane
  6386. * @returns a new matrix as a right-handed perspective projection matrix
  6387. */
  6388. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6389. var matrix = Matrix.Zero();
  6390. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6391. return matrix;
  6392. };
  6393. /**
  6394. * Stores a right-handed perspective projection into a given matrix
  6395. * @param fov defines the horizontal field of view
  6396. * @param aspect defines the aspect ratio
  6397. * @param znear defines the near clip plane
  6398. * @param zfar defines the far clip plane
  6399. * @param result defines the target matrix
  6400. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6401. */
  6402. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6403. //alternatively this could be expressed as:
  6404. // m = PerspectiveFovLHToRef
  6405. // m[10] *= -1.0;
  6406. // m[11] *= -1.0;
  6407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6408. var n = znear;
  6409. var f = zfar;
  6410. var t = 1.0 / (Math.tan(fov * 0.5));
  6411. var a = isVerticalFovFixed ? (t / aspect) : t;
  6412. var b = isVerticalFovFixed ? t : (t * aspect);
  6413. var c = -(f + n) / (f - n);
  6414. var d = -2 * f * n / (f - n);
  6415. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6416. };
  6417. /**
  6418. * Stores a perspective projection for WebVR info a given matrix
  6419. * @param fov defines the field of view
  6420. * @param znear defines the near clip plane
  6421. * @param zfar defines the far clip plane
  6422. * @param result defines the target matrix
  6423. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6424. */
  6425. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6426. if (rightHanded === void 0) { rightHanded = false; }
  6427. var rightHandedFactor = rightHanded ? -1 : 1;
  6428. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6429. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6430. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6431. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6432. var xScale = 2.0 / (leftTan + rightTan);
  6433. var yScale = 2.0 / (upTan + downTan);
  6434. result.m[0] = xScale;
  6435. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6436. result.m[5] = yScale;
  6437. result.m[6] = result.m[7] = 0.0;
  6438. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6439. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6440. result.m[10] = -zfar / (znear - zfar);
  6441. result.m[11] = 1.0 * rightHandedFactor;
  6442. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6443. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6444. result._markAsUpdated();
  6445. };
  6446. /**
  6447. * Computes a complete transformation matrix
  6448. * @param viewport defines the viewport to use
  6449. * @param world defines the world matrix
  6450. * @param view defines the view matrix
  6451. * @param projection defines the projection matrix
  6452. * @param zmin defines the near clip plane
  6453. * @param zmax defines the far clip plane
  6454. * @returns the transformation matrix
  6455. */
  6456. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6457. var cw = viewport.width;
  6458. var ch = viewport.height;
  6459. var cx = viewport.x;
  6460. var cy = viewport.y;
  6461. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6462. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6463. };
  6464. /**
  6465. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6466. * @param matrix defines the matrix to use
  6467. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6468. */
  6469. Matrix.GetAsMatrix2x2 = function (matrix) {
  6470. return new Float32Array([
  6471. matrix.m[0], matrix.m[1],
  6472. matrix.m[4], matrix.m[5]
  6473. ]);
  6474. };
  6475. /**
  6476. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6477. * @param matrix defines the matrix to use
  6478. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6479. */
  6480. Matrix.GetAsMatrix3x3 = function (matrix) {
  6481. return new Float32Array([
  6482. matrix.m[0], matrix.m[1], matrix.m[2],
  6483. matrix.m[4], matrix.m[5], matrix.m[6],
  6484. matrix.m[8], matrix.m[9], matrix.m[10]
  6485. ]);
  6486. };
  6487. /**
  6488. * Compute the transpose of a given matrix
  6489. * @param matrix defines the matrix to transpose
  6490. * @returns the new matrix
  6491. */
  6492. Matrix.Transpose = function (matrix) {
  6493. var result = new Matrix();
  6494. Matrix.TransposeToRef(matrix, result);
  6495. return result;
  6496. };
  6497. /**
  6498. * Compute the transpose of a matrix and store it in a target matrix
  6499. * @param matrix defines the matrix to transpose
  6500. * @param result defines the target matrix
  6501. */
  6502. Matrix.TransposeToRef = function (matrix, result) {
  6503. result.m[0] = matrix.m[0];
  6504. result.m[1] = matrix.m[4];
  6505. result.m[2] = matrix.m[8];
  6506. result.m[3] = matrix.m[12];
  6507. result.m[4] = matrix.m[1];
  6508. result.m[5] = matrix.m[5];
  6509. result.m[6] = matrix.m[9];
  6510. result.m[7] = matrix.m[13];
  6511. result.m[8] = matrix.m[2];
  6512. result.m[9] = matrix.m[6];
  6513. result.m[10] = matrix.m[10];
  6514. result.m[11] = matrix.m[14];
  6515. result.m[12] = matrix.m[3];
  6516. result.m[13] = matrix.m[7];
  6517. result.m[14] = matrix.m[11];
  6518. result.m[15] = matrix.m[15];
  6519. };
  6520. /**
  6521. * Computes a reflection matrix from a plane
  6522. * @param plane defines the reflection plane
  6523. * @returns a new matrix
  6524. */
  6525. Matrix.Reflection = function (plane) {
  6526. var matrix = new Matrix();
  6527. Matrix.ReflectionToRef(plane, matrix);
  6528. return matrix;
  6529. };
  6530. /**
  6531. * Computes a reflection matrix from a plane
  6532. * @param plane defines the reflection plane
  6533. * @param result defines the target matrix
  6534. */
  6535. Matrix.ReflectionToRef = function (plane, result) {
  6536. plane.normalize();
  6537. var x = plane.normal.x;
  6538. var y = plane.normal.y;
  6539. var z = plane.normal.z;
  6540. var temp = -2 * x;
  6541. var temp2 = -2 * y;
  6542. var temp3 = -2 * z;
  6543. result.m[0] = (temp * x) + 1;
  6544. result.m[1] = temp2 * x;
  6545. result.m[2] = temp3 * x;
  6546. result.m[3] = 0.0;
  6547. result.m[4] = temp * y;
  6548. result.m[5] = (temp2 * y) + 1;
  6549. result.m[6] = temp3 * y;
  6550. result.m[7] = 0.0;
  6551. result.m[8] = temp * z;
  6552. result.m[9] = temp2 * z;
  6553. result.m[10] = (temp3 * z) + 1;
  6554. result.m[11] = 0.0;
  6555. result.m[12] = temp * plane.d;
  6556. result.m[13] = temp2 * plane.d;
  6557. result.m[14] = temp3 * plane.d;
  6558. result.m[15] = 1.0;
  6559. result._markAsUpdated();
  6560. };
  6561. /**
  6562. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6563. * @param xaxis defines the value of the 1st axis
  6564. * @param yaxis defines the value of the 2nd axis
  6565. * @param zaxis defines the value of the 3rd axis
  6566. * @param result defines the target matrix
  6567. */
  6568. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6569. result.m[0] = xaxis.x;
  6570. result.m[1] = xaxis.y;
  6571. result.m[2] = xaxis.z;
  6572. result.m[3] = 0.0;
  6573. result.m[4] = yaxis.x;
  6574. result.m[5] = yaxis.y;
  6575. result.m[6] = yaxis.z;
  6576. result.m[7] = 0.0;
  6577. result.m[8] = zaxis.x;
  6578. result.m[9] = zaxis.y;
  6579. result.m[10] = zaxis.z;
  6580. result.m[11] = 0.0;
  6581. result.m[12] = 0.0;
  6582. result.m[13] = 0.0;
  6583. result.m[14] = 0.0;
  6584. result.m[15] = 1.0;
  6585. result._markAsUpdated();
  6586. };
  6587. /**
  6588. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6589. * @param quat defines the quaternion to use
  6590. * @param result defines the target matrix
  6591. */
  6592. Matrix.FromQuaternionToRef = function (quat, result) {
  6593. var xx = quat.x * quat.x;
  6594. var yy = quat.y * quat.y;
  6595. var zz = quat.z * quat.z;
  6596. var xy = quat.x * quat.y;
  6597. var zw = quat.z * quat.w;
  6598. var zx = quat.z * quat.x;
  6599. var yw = quat.y * quat.w;
  6600. var yz = quat.y * quat.z;
  6601. var xw = quat.x * quat.w;
  6602. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6603. result.m[1] = 2.0 * (xy + zw);
  6604. result.m[2] = 2.0 * (zx - yw);
  6605. result.m[3] = 0.0;
  6606. result.m[4] = 2.0 * (xy - zw);
  6607. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6608. result.m[6] = 2.0 * (yz + xw);
  6609. result.m[7] = 0.0;
  6610. result.m[8] = 2.0 * (zx + yw);
  6611. result.m[9] = 2.0 * (yz - xw);
  6612. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6613. result.m[11] = 0.0;
  6614. result.m[12] = 0.0;
  6615. result.m[13] = 0.0;
  6616. result.m[14] = 0.0;
  6617. result.m[15] = 1.0;
  6618. result._markAsUpdated();
  6619. };
  6620. Matrix._tempQuaternion = new Quaternion();
  6621. Matrix._xAxis = Vector3.Zero();
  6622. Matrix._yAxis = Vector3.Zero();
  6623. Matrix._zAxis = Vector3.Zero();
  6624. Matrix._updateFlagSeed = 0;
  6625. Matrix._identityReadOnly = Matrix.Identity();
  6626. return Matrix;
  6627. }());
  6628. BABYLON.Matrix = Matrix;
  6629. var Plane = /** @class */ (function () {
  6630. /**
  6631. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6632. */
  6633. function Plane(a, b, c, d) {
  6634. this.normal = new Vector3(a, b, c);
  6635. this.d = d;
  6636. }
  6637. /**
  6638. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6639. */
  6640. Plane.prototype.asArray = function () {
  6641. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6642. };
  6643. // Methods
  6644. /**
  6645. * Returns a new plane copied from the current Plane.
  6646. */
  6647. Plane.prototype.clone = function () {
  6648. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6649. };
  6650. /**
  6651. * Returns the string "Plane".
  6652. */
  6653. Plane.prototype.getClassName = function () {
  6654. return "Plane";
  6655. };
  6656. /**
  6657. * Returns the Plane hash code.
  6658. */
  6659. Plane.prototype.getHashCode = function () {
  6660. var hash = this.normal.getHashCode();
  6661. hash = (hash * 397) ^ (this.d || 0);
  6662. return hash;
  6663. };
  6664. /**
  6665. * Normalize the current Plane in place.
  6666. * Returns the updated Plane.
  6667. */
  6668. Plane.prototype.normalize = function () {
  6669. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6670. var magnitude = 0.0;
  6671. if (norm !== 0) {
  6672. magnitude = 1.0 / norm;
  6673. }
  6674. this.normal.x *= magnitude;
  6675. this.normal.y *= magnitude;
  6676. this.normal.z *= magnitude;
  6677. this.d *= magnitude;
  6678. return this;
  6679. };
  6680. /**
  6681. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6682. */
  6683. Plane.prototype.transform = function (transformation) {
  6684. var transposedMatrix = Matrix.Transpose(transformation);
  6685. var x = this.normal.x;
  6686. var y = this.normal.y;
  6687. var z = this.normal.z;
  6688. var d = this.d;
  6689. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6690. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6691. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6692. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6693. return new Plane(normalX, normalY, normalZ, finalD);
  6694. };
  6695. /**
  6696. * Returns the dot product (float) of the point coordinates and the plane normal.
  6697. */
  6698. Plane.prototype.dotCoordinate = function (point) {
  6699. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6700. };
  6701. /**
  6702. * Updates the current Plane from the plane defined by the three given points.
  6703. * Returns the updated Plane.
  6704. */
  6705. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6706. var x1 = point2.x - point1.x;
  6707. var y1 = point2.y - point1.y;
  6708. var z1 = point2.z - point1.z;
  6709. var x2 = point3.x - point1.x;
  6710. var y2 = point3.y - point1.y;
  6711. var z2 = point3.z - point1.z;
  6712. var yz = (y1 * z2) - (z1 * y2);
  6713. var xz = (z1 * x2) - (x1 * z2);
  6714. var xy = (x1 * y2) - (y1 * x2);
  6715. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6716. var invPyth;
  6717. if (pyth !== 0) {
  6718. invPyth = 1.0 / pyth;
  6719. }
  6720. else {
  6721. invPyth = 0.0;
  6722. }
  6723. this.normal.x = yz * invPyth;
  6724. this.normal.y = xz * invPyth;
  6725. this.normal.z = xy * invPyth;
  6726. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6727. return this;
  6728. };
  6729. /**
  6730. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6731. */
  6732. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6733. var dot = Vector3.Dot(this.normal, direction);
  6734. return (dot <= epsilon);
  6735. };
  6736. /**
  6737. * Returns the signed distance (float) from the given point to the Plane.
  6738. */
  6739. Plane.prototype.signedDistanceTo = function (point) {
  6740. return Vector3.Dot(point, this.normal) + this.d;
  6741. };
  6742. // Statics
  6743. /**
  6744. * Returns a new Plane from the given array.
  6745. */
  6746. Plane.FromArray = function (array) {
  6747. return new Plane(array[0], array[1], array[2], array[3]);
  6748. };
  6749. /**
  6750. * Returns a new Plane defined by the three given points.
  6751. */
  6752. Plane.FromPoints = function (point1, point2, point3) {
  6753. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6754. result.copyFromPoints(point1, point2, point3);
  6755. return result;
  6756. };
  6757. /**
  6758. * Returns a new Plane the normal vector to this plane at the given origin point.
  6759. * Note : the vector "normal" is updated because normalized.
  6760. */
  6761. Plane.FromPositionAndNormal = function (origin, normal) {
  6762. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6763. normal.normalize();
  6764. result.normal = normal;
  6765. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6766. return result;
  6767. };
  6768. /**
  6769. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6770. */
  6771. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6772. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6773. return Vector3.Dot(point, normal) + d;
  6774. };
  6775. return Plane;
  6776. }());
  6777. BABYLON.Plane = Plane;
  6778. var Viewport = /** @class */ (function () {
  6779. /**
  6780. * Creates a Viewport object located at (x, y) and sized (width, height).
  6781. */
  6782. function Viewport(x, y, width, height) {
  6783. this.x = x;
  6784. this.y = y;
  6785. this.width = width;
  6786. this.height = height;
  6787. }
  6788. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6789. if (renderWidthOrEngine.getRenderWidth) {
  6790. var engine = renderWidthOrEngine;
  6791. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6792. }
  6793. var renderWidth = renderWidthOrEngine;
  6794. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6795. };
  6796. /**
  6797. * Returns a new Viewport copied from the current one.
  6798. */
  6799. Viewport.prototype.clone = function () {
  6800. return new Viewport(this.x, this.y, this.width, this.height);
  6801. };
  6802. return Viewport;
  6803. }());
  6804. BABYLON.Viewport = Viewport;
  6805. var Frustum = /** @class */ (function () {
  6806. function Frustum() {
  6807. }
  6808. /**
  6809. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6810. */
  6811. Frustum.GetPlanes = function (transform) {
  6812. var frustumPlanes = [];
  6813. for (var index = 0; index < 6; index++) {
  6814. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6815. }
  6816. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6817. return frustumPlanes;
  6818. };
  6819. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6820. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6821. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6822. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6823. frustumPlane.d = transform.m[15] + transform.m[14];
  6824. frustumPlane.normalize();
  6825. };
  6826. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6827. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6828. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6829. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6830. frustumPlane.d = transform.m[15] - transform.m[14];
  6831. frustumPlane.normalize();
  6832. };
  6833. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6834. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6835. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6836. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6837. frustumPlane.d = transform.m[15] + transform.m[12];
  6838. frustumPlane.normalize();
  6839. };
  6840. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6841. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6842. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6843. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6844. frustumPlane.d = transform.m[15] - transform.m[12];
  6845. frustumPlane.normalize();
  6846. };
  6847. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6848. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6849. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6850. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6851. frustumPlane.d = transform.m[15] - transform.m[13];
  6852. frustumPlane.normalize();
  6853. };
  6854. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6855. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6856. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6857. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6858. frustumPlane.d = transform.m[15] + transform.m[13];
  6859. frustumPlane.normalize();
  6860. };
  6861. /**
  6862. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6863. */
  6864. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6865. // Near
  6866. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6867. // Far
  6868. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6869. // Left
  6870. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6871. // Right
  6872. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6873. // Top
  6874. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6875. // Bottom
  6876. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6877. };
  6878. return Frustum;
  6879. }());
  6880. BABYLON.Frustum = Frustum;
  6881. /** Defines supported spaces */
  6882. var Space;
  6883. (function (Space) {
  6884. /** Local (object) space */
  6885. Space[Space["LOCAL"] = 0] = "LOCAL";
  6886. /** World space */
  6887. Space[Space["WORLD"] = 1] = "WORLD";
  6888. /** Bone space */
  6889. Space[Space["BONE"] = 2] = "BONE";
  6890. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6891. /** Defines the 3 main axes */
  6892. var Axis = /** @class */ (function () {
  6893. function Axis() {
  6894. }
  6895. /** X axis */
  6896. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6897. /** Y axis */
  6898. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6899. /** Z axis */
  6900. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6901. return Axis;
  6902. }());
  6903. BABYLON.Axis = Axis;
  6904. ;
  6905. var BezierCurve = /** @class */ (function () {
  6906. function BezierCurve() {
  6907. }
  6908. /**
  6909. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6910. */
  6911. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6912. // Extract X (which is equal to time here)
  6913. var f0 = 1 - 3 * x2 + 3 * x1;
  6914. var f1 = 3 * x2 - 6 * x1;
  6915. var f2 = 3 * x1;
  6916. var refinedT = t;
  6917. for (var i = 0; i < 5; i++) {
  6918. var refinedT2 = refinedT * refinedT;
  6919. var refinedT3 = refinedT2 * refinedT;
  6920. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6921. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6922. refinedT -= (x - t) * slope;
  6923. refinedT = Math.min(1, Math.max(0, refinedT));
  6924. }
  6925. // Resolve cubic bezier for the given x
  6926. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6927. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6928. Math.pow(refinedT, 3);
  6929. };
  6930. return BezierCurve;
  6931. }());
  6932. BABYLON.BezierCurve = BezierCurve;
  6933. /**
  6934. * Defines potential orientation for back face culling
  6935. */
  6936. var Orientation;
  6937. (function (Orientation) {
  6938. /**
  6939. * Clockwise
  6940. */
  6941. Orientation[Orientation["CW"] = 0] = "CW";
  6942. /** Counter clockwise */
  6943. Orientation[Orientation["CCW"] = 1] = "CCW";
  6944. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6945. /**
  6946. * Defines angle representation
  6947. */
  6948. var Angle = /** @class */ (function () {
  6949. /**
  6950. * Creates an Angle object of "radians" radians (float).
  6951. */
  6952. function Angle(radians) {
  6953. this._radians = radians;
  6954. if (this._radians < 0.0)
  6955. this._radians += (2.0 * Math.PI);
  6956. }
  6957. /**
  6958. * Get value in degrees
  6959. * @returns the Angle value in degrees (float)
  6960. */
  6961. Angle.prototype.degrees = function () {
  6962. return this._radians * 180.0 / Math.PI;
  6963. };
  6964. /**
  6965. * Get value in radians
  6966. * @returns the Angle value in radians (float)
  6967. */
  6968. Angle.prototype.radians = function () {
  6969. return this._radians;
  6970. };
  6971. /**
  6972. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6973. * @param a defines first vector
  6974. * @param b defines second vector
  6975. * @returns a new Angle
  6976. */
  6977. Angle.BetweenTwoPoints = function (a, b) {
  6978. var delta = b.subtract(a);
  6979. var theta = Math.atan2(delta.y, delta.x);
  6980. return new Angle(theta);
  6981. };
  6982. /**
  6983. * Gets a new Angle object from the given float in radians
  6984. * @param radians defines the angle value in radians
  6985. * @returns a new Angle
  6986. */
  6987. Angle.FromRadians = function (radians) {
  6988. return new Angle(radians);
  6989. };
  6990. /**
  6991. * Gets a new Angle object from the given float in degrees
  6992. * @param degrees defines the angle value in degrees
  6993. * @returns a new Angle
  6994. */
  6995. Angle.FromDegrees = function (degrees) {
  6996. return new Angle(degrees * Math.PI / 180.0);
  6997. };
  6998. return Angle;
  6999. }());
  7000. BABYLON.Angle = Angle;
  7001. var Arc2 = /** @class */ (function () {
  7002. /**
  7003. * Creates an Arc object from the three given points : start, middle and end.
  7004. */
  7005. function Arc2(startPoint, midPoint, endPoint) {
  7006. this.startPoint = startPoint;
  7007. this.midPoint = midPoint;
  7008. this.endPoint = endPoint;
  7009. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7010. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7011. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7012. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7013. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7014. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7015. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7016. var a1 = this.startAngle.degrees();
  7017. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7018. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7019. // angles correction
  7020. if (a2 - a1 > +180.0)
  7021. a2 -= 360.0;
  7022. if (a2 - a1 < -180.0)
  7023. a2 += 360.0;
  7024. if (a3 - a2 > +180.0)
  7025. a3 -= 360.0;
  7026. if (a3 - a2 < -180.0)
  7027. a3 += 360.0;
  7028. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7029. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7030. }
  7031. return Arc2;
  7032. }());
  7033. BABYLON.Arc2 = Arc2;
  7034. var Path2 = /** @class */ (function () {
  7035. /**
  7036. * Creates a Path2 object from the starting 2D coordinates x and y.
  7037. */
  7038. function Path2(x, y) {
  7039. this._points = new Array();
  7040. this._length = 0.0;
  7041. this.closed = false;
  7042. this._points.push(new Vector2(x, y));
  7043. }
  7044. /**
  7045. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7046. * Returns the updated Path2.
  7047. */
  7048. Path2.prototype.addLineTo = function (x, y) {
  7049. if (this.closed) {
  7050. return this;
  7051. }
  7052. var newPoint = new Vector2(x, y);
  7053. var previousPoint = this._points[this._points.length - 1];
  7054. this._points.push(newPoint);
  7055. this._length += newPoint.subtract(previousPoint).length();
  7056. return this;
  7057. };
  7058. /**
  7059. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7060. * Returns the updated Path2.
  7061. */
  7062. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7063. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7064. if (this.closed) {
  7065. return this;
  7066. }
  7067. var startPoint = this._points[this._points.length - 1];
  7068. var midPoint = new Vector2(midX, midY);
  7069. var endPoint = new Vector2(endX, endY);
  7070. var arc = new Arc2(startPoint, midPoint, endPoint);
  7071. var increment = arc.angle.radians() / numberOfSegments;
  7072. if (arc.orientation === Orientation.CW)
  7073. increment *= -1;
  7074. var currentAngle = arc.startAngle.radians() + increment;
  7075. for (var i = 0; i < numberOfSegments; i++) {
  7076. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7077. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7078. this.addLineTo(x, y);
  7079. currentAngle += increment;
  7080. }
  7081. return this;
  7082. };
  7083. /**
  7084. * Closes the Path2.
  7085. * Returns the Path2.
  7086. */
  7087. Path2.prototype.close = function () {
  7088. this.closed = true;
  7089. return this;
  7090. };
  7091. /**
  7092. * Returns the Path2 total length (float).
  7093. */
  7094. Path2.prototype.length = function () {
  7095. var result = this._length;
  7096. if (!this.closed) {
  7097. var lastPoint = this._points[this._points.length - 1];
  7098. var firstPoint = this._points[0];
  7099. result += (firstPoint.subtract(lastPoint).length());
  7100. }
  7101. return result;
  7102. };
  7103. /**
  7104. * Returns the Path2 internal array of points.
  7105. */
  7106. Path2.prototype.getPoints = function () {
  7107. return this._points;
  7108. };
  7109. /**
  7110. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7111. */
  7112. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7113. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7114. return Vector2.Zero();
  7115. }
  7116. var lengthPosition = normalizedLengthPosition * this.length();
  7117. var previousOffset = 0;
  7118. for (var i = 0; i < this._points.length; i++) {
  7119. var j = (i + 1) % this._points.length;
  7120. var a = this._points[i];
  7121. var b = this._points[j];
  7122. var bToA = b.subtract(a);
  7123. var nextOffset = (bToA.length() + previousOffset);
  7124. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7125. var dir = bToA.normalize();
  7126. var localOffset = lengthPosition - previousOffset;
  7127. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7128. }
  7129. previousOffset = nextOffset;
  7130. }
  7131. return Vector2.Zero();
  7132. };
  7133. /**
  7134. * Returns a new Path2 starting at the coordinates (x, y).
  7135. */
  7136. Path2.StartingAt = function (x, y) {
  7137. return new Path2(x, y);
  7138. };
  7139. return Path2;
  7140. }());
  7141. BABYLON.Path2 = Path2;
  7142. var Path3D = /** @class */ (function () {
  7143. /**
  7144. * new Path3D(path, normal, raw)
  7145. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7146. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7147. * path : an array of Vector3, the curve axis of the Path3D
  7148. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7149. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7150. */
  7151. function Path3D(path, firstNormal, raw) {
  7152. if (firstNormal === void 0) { firstNormal = null; }
  7153. this.path = path;
  7154. this._curve = new Array();
  7155. this._distances = new Array();
  7156. this._tangents = new Array();
  7157. this._normals = new Array();
  7158. this._binormals = new Array();
  7159. for (var p = 0; p < path.length; p++) {
  7160. this._curve[p] = path[p].clone(); // hard copy
  7161. }
  7162. this._raw = raw || false;
  7163. this._compute(firstNormal);
  7164. }
  7165. /**
  7166. * Returns the Path3D array of successive Vector3 designing its curve.
  7167. */
  7168. Path3D.prototype.getCurve = function () {
  7169. return this._curve;
  7170. };
  7171. /**
  7172. * Returns an array populated with tangent vectors on each Path3D curve point.
  7173. */
  7174. Path3D.prototype.getTangents = function () {
  7175. return this._tangents;
  7176. };
  7177. /**
  7178. * Returns an array populated with normal vectors on each Path3D curve point.
  7179. */
  7180. Path3D.prototype.getNormals = function () {
  7181. return this._normals;
  7182. };
  7183. /**
  7184. * Returns an array populated with binormal vectors on each Path3D curve point.
  7185. */
  7186. Path3D.prototype.getBinormals = function () {
  7187. return this._binormals;
  7188. };
  7189. /**
  7190. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7191. */
  7192. Path3D.prototype.getDistances = function () {
  7193. return this._distances;
  7194. };
  7195. /**
  7196. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7197. * Returns the same object updated.
  7198. */
  7199. Path3D.prototype.update = function (path, firstNormal) {
  7200. if (firstNormal === void 0) { firstNormal = null; }
  7201. for (var p = 0; p < path.length; p++) {
  7202. this._curve[p].x = path[p].x;
  7203. this._curve[p].y = path[p].y;
  7204. this._curve[p].z = path[p].z;
  7205. }
  7206. this._compute(firstNormal);
  7207. return this;
  7208. };
  7209. // private function compute() : computes tangents, normals and binormals
  7210. Path3D.prototype._compute = function (firstNormal) {
  7211. var l = this._curve.length;
  7212. // first and last tangents
  7213. this._tangents[0] = this._getFirstNonNullVector(0);
  7214. if (!this._raw) {
  7215. this._tangents[0].normalize();
  7216. }
  7217. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7218. if (!this._raw) {
  7219. this._tangents[l - 1].normalize();
  7220. }
  7221. // normals and binormals at first point : arbitrary vector with _normalVector()
  7222. var tg0 = this._tangents[0];
  7223. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7224. this._normals[0] = pp0;
  7225. if (!this._raw) {
  7226. this._normals[0].normalize();
  7227. }
  7228. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7229. if (!this._raw) {
  7230. this._binormals[0].normalize();
  7231. }
  7232. this._distances[0] = 0.0;
  7233. // normals and binormals : next points
  7234. var prev; // previous vector (segment)
  7235. var cur; // current vector (segment)
  7236. var curTang; // current tangent
  7237. // previous normal
  7238. var prevBinor; // previous binormal
  7239. for (var i = 1; i < l; i++) {
  7240. // tangents
  7241. prev = this._getLastNonNullVector(i);
  7242. if (i < l - 1) {
  7243. cur = this._getFirstNonNullVector(i);
  7244. this._tangents[i] = prev.add(cur);
  7245. this._tangents[i].normalize();
  7246. }
  7247. this._distances[i] = this._distances[i - 1] + prev.length();
  7248. // normals and binormals
  7249. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7250. curTang = this._tangents[i];
  7251. prevBinor = this._binormals[i - 1];
  7252. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7253. if (!this._raw) {
  7254. this._normals[i].normalize();
  7255. }
  7256. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7257. if (!this._raw) {
  7258. this._binormals[i].normalize();
  7259. }
  7260. }
  7261. };
  7262. // private function getFirstNonNullVector(index)
  7263. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7264. Path3D.prototype._getFirstNonNullVector = function (index) {
  7265. var i = 1;
  7266. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7267. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7268. i++;
  7269. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7270. }
  7271. return nNVector;
  7272. };
  7273. // private function getLastNonNullVector(index)
  7274. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7275. Path3D.prototype._getLastNonNullVector = function (index) {
  7276. var i = 1;
  7277. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7278. while (nLVector.length() === 0 && index > i + 1) {
  7279. i++;
  7280. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7281. }
  7282. return nLVector;
  7283. };
  7284. // private function normalVector(v0, vt, va) :
  7285. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7286. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7287. Path3D.prototype._normalVector = function (v0, vt, va) {
  7288. var normal0;
  7289. var tgl = vt.length();
  7290. if (tgl === 0.0) {
  7291. tgl = 1.0;
  7292. }
  7293. if (va === undefined || va === null) {
  7294. var point;
  7295. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7296. point = new Vector3(0.0, -1.0, 0.0);
  7297. }
  7298. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7299. point = new Vector3(1.0, 0.0, 0.0);
  7300. }
  7301. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7302. point = new Vector3(0.0, 0.0, 1.0);
  7303. }
  7304. else {
  7305. point = Vector3.Zero();
  7306. }
  7307. normal0 = Vector3.Cross(vt, point);
  7308. }
  7309. else {
  7310. normal0 = Vector3.Cross(vt, va);
  7311. Vector3.CrossToRef(normal0, vt, normal0);
  7312. }
  7313. normal0.normalize();
  7314. return normal0;
  7315. };
  7316. return Path3D;
  7317. }());
  7318. BABYLON.Path3D = Path3D;
  7319. var Curve3 = /** @class */ (function () {
  7320. /**
  7321. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7322. * A Curve3 is designed from a series of successive Vector3.
  7323. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7324. */
  7325. function Curve3(points) {
  7326. this._length = 0.0;
  7327. this._points = points;
  7328. this._length = this._computeLength(points);
  7329. }
  7330. /**
  7331. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7332. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7333. * @param v1 (Vector3) the control point
  7334. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7335. * @param nbPoints (integer) the wanted number of points in the curve
  7336. */
  7337. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7338. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7339. var bez = new Array();
  7340. var equation = function (t, val0, val1, val2) {
  7341. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7342. return res;
  7343. };
  7344. for (var i = 0; i <= nbPoints; i++) {
  7345. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7346. }
  7347. return new Curve3(bez);
  7348. };
  7349. /**
  7350. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7351. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7352. * @param v1 (Vector3) the first control point
  7353. * @param v2 (Vector3) the second control point
  7354. * @param v3 (Vector3) the end point of the Cubic Bezier
  7355. * @param nbPoints (integer) the wanted number of points in the curve
  7356. */
  7357. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7358. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7359. var bez = new Array();
  7360. var equation = function (t, val0, val1, val2, val3) {
  7361. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7362. return res;
  7363. };
  7364. for (var i = 0; i <= nbPoints; i++) {
  7365. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7366. }
  7367. return new Curve3(bez);
  7368. };
  7369. /**
  7370. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7371. * @param p1 (Vector3) the origin point of the Hermite Spline
  7372. * @param t1 (Vector3) the tangent vector at the origin point
  7373. * @param p2 (Vector3) the end point of the Hermite Spline
  7374. * @param t2 (Vector3) the tangent vector at the end point
  7375. * @param nbPoints (integer) the wanted number of points in the curve
  7376. */
  7377. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7378. var hermite = new Array();
  7379. var step = 1.0 / nbPoints;
  7380. for (var i = 0; i <= nbPoints; i++) {
  7381. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7382. }
  7383. return new Curve3(hermite);
  7384. };
  7385. /**
  7386. * Returns a Curve3 object along a CatmullRom Spline curve :
  7387. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7388. * @param nbPoints (integer) the wanted number of points between each curve control points
  7389. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7390. */
  7391. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7392. var catmullRom = new Array();
  7393. var step = 1.0 / nbPoints;
  7394. var amount = 0.0;
  7395. if (closed) {
  7396. var pointsCount = points.length;
  7397. for (var i = 0; i < pointsCount; i++) {
  7398. amount = 0;
  7399. for (var c = 0; c < nbPoints; c++) {
  7400. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7401. amount += step;
  7402. }
  7403. }
  7404. catmullRom.push(catmullRom[0]);
  7405. }
  7406. else {
  7407. var totalPoints = new Array();
  7408. totalPoints.push(points[0].clone());
  7409. Array.prototype.push.apply(totalPoints, points);
  7410. totalPoints.push(points[points.length - 1].clone());
  7411. for (var i = 0; i < totalPoints.length - 3; i++) {
  7412. amount = 0;
  7413. for (var c = 0; c < nbPoints; c++) {
  7414. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7415. amount += step;
  7416. }
  7417. }
  7418. i--;
  7419. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7420. }
  7421. return new Curve3(catmullRom);
  7422. };
  7423. /**
  7424. * Returns the Curve3 stored array of successive Vector3
  7425. */
  7426. Curve3.prototype.getPoints = function () {
  7427. return this._points;
  7428. };
  7429. /**
  7430. * Returns the computed length (float) of the curve.
  7431. */
  7432. Curve3.prototype.length = function () {
  7433. return this._length;
  7434. };
  7435. /**
  7436. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7437. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7438. * curveA and curveB keep unchanged.
  7439. */
  7440. Curve3.prototype.continue = function (curve) {
  7441. var lastPoint = this._points[this._points.length - 1];
  7442. var continuedPoints = this._points.slice();
  7443. var curvePoints = curve.getPoints();
  7444. for (var i = 1; i < curvePoints.length; i++) {
  7445. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7446. }
  7447. var continuedCurve = new Curve3(continuedPoints);
  7448. return continuedCurve;
  7449. };
  7450. Curve3.prototype._computeLength = function (path) {
  7451. var l = 0;
  7452. for (var i = 1; i < path.length; i++) {
  7453. l += (path[i].subtract(path[i - 1])).length();
  7454. }
  7455. return l;
  7456. };
  7457. return Curve3;
  7458. }());
  7459. BABYLON.Curve3 = Curve3;
  7460. // Vertex formats
  7461. var PositionNormalVertex = /** @class */ (function () {
  7462. function PositionNormalVertex(position, normal) {
  7463. if (position === void 0) { position = Vector3.Zero(); }
  7464. if (normal === void 0) { normal = Vector3.Up(); }
  7465. this.position = position;
  7466. this.normal = normal;
  7467. }
  7468. PositionNormalVertex.prototype.clone = function () {
  7469. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7470. };
  7471. return PositionNormalVertex;
  7472. }());
  7473. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7474. var PositionNormalTextureVertex = /** @class */ (function () {
  7475. function PositionNormalTextureVertex(position, normal, uv) {
  7476. if (position === void 0) { position = Vector3.Zero(); }
  7477. if (normal === void 0) { normal = Vector3.Up(); }
  7478. if (uv === void 0) { uv = Vector2.Zero(); }
  7479. this.position = position;
  7480. this.normal = normal;
  7481. this.uv = uv;
  7482. }
  7483. PositionNormalTextureVertex.prototype.clone = function () {
  7484. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7485. };
  7486. return PositionNormalTextureVertex;
  7487. }());
  7488. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7489. // Temporary pre-allocated objects for engine internal use
  7490. // usage in any internal function :
  7491. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7492. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7493. var Tmp = /** @class */ (function () {
  7494. function Tmp() {
  7495. }
  7496. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7497. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7498. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7499. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7500. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7501. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7502. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero(),
  7505. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7506. return Tmp;
  7507. }());
  7508. BABYLON.Tmp = Tmp;
  7509. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7510. var MathTmp = /** @class */ (function () {
  7511. function MathTmp() {
  7512. }
  7513. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7514. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7515. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7516. return MathTmp;
  7517. }());
  7518. })(BABYLON || (BABYLON = {}));
  7519. //# sourceMappingURL=babylon.math.js.map
  7520. var BABYLON;
  7521. (function (BABYLON) {
  7522. var Scalar = /** @class */ (function () {
  7523. function Scalar() {
  7524. }
  7525. /**
  7526. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7527. */
  7528. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7529. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7530. var num = a - b;
  7531. return -epsilon <= num && num <= epsilon;
  7532. };
  7533. /**
  7534. * Returns a string : the upper case translation of the number i to hexadecimal.
  7535. */
  7536. Scalar.ToHex = function (i) {
  7537. var str = i.toString(16);
  7538. if (i <= 15) {
  7539. return ("0" + str).toUpperCase();
  7540. }
  7541. return str.toUpperCase();
  7542. };
  7543. /**
  7544. * Returns -1 if value is negative and +1 is value is positive.
  7545. * Returns the value itself if it's equal to zero.
  7546. */
  7547. Scalar.Sign = function (value) {
  7548. value = +value; // convert to a number
  7549. if (value === 0 || isNaN(value))
  7550. return value;
  7551. return value > 0 ? 1 : -1;
  7552. };
  7553. /**
  7554. * Returns the value itself if it's between min and max.
  7555. * Returns min if the value is lower than min.
  7556. * Returns max if the value is greater than max.
  7557. */
  7558. Scalar.Clamp = function (value, min, max) {
  7559. if (min === void 0) { min = 0; }
  7560. if (max === void 0) { max = 1; }
  7561. return Math.min(max, Math.max(min, value));
  7562. };
  7563. /**
  7564. * Returns the log2 of value.
  7565. */
  7566. Scalar.Log2 = function (value) {
  7567. return Math.log(value) * Math.LOG2E;
  7568. };
  7569. /**
  7570. * Loops the value, so that it is never larger than length and never smaller than 0.
  7571. *
  7572. * This is similar to the modulo operator but it works with floating point numbers.
  7573. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7574. * With t = 5 and length = 2.5, the result would be 0.0.
  7575. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7576. */
  7577. Scalar.Repeat = function (value, length) {
  7578. return value - Math.floor(value / length) * length;
  7579. };
  7580. /**
  7581. * Normalize the value between 0.0 and 1.0 using min and max values
  7582. */
  7583. Scalar.Normalize = function (value, min, max) {
  7584. return (value - min) / (max - min);
  7585. };
  7586. /**
  7587. * Denormalize the value from 0.0 and 1.0 using min and max values
  7588. */
  7589. Scalar.Denormalize = function (normalized, min, max) {
  7590. return (normalized * (max - min) + min);
  7591. };
  7592. /**
  7593. * Calculates the shortest difference between two given angles given in degrees.
  7594. */
  7595. Scalar.DeltaAngle = function (current, target) {
  7596. var num = Scalar.Repeat(target - current, 360.0);
  7597. if (num > 180.0) {
  7598. num -= 360.0;
  7599. }
  7600. return num;
  7601. };
  7602. /**
  7603. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7604. *
  7605. * The returned value will move back and forth between 0 and length
  7606. */
  7607. Scalar.PingPong = function (tx, length) {
  7608. var t = Scalar.Repeat(tx, length * 2.0);
  7609. return length - Math.abs(t - length);
  7610. };
  7611. /**
  7612. * Interpolates between min and max with smoothing at the limits.
  7613. *
  7614. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7615. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7616. */
  7617. Scalar.SmoothStep = function (from, to, tx) {
  7618. var t = Scalar.Clamp(tx);
  7619. t = -2.0 * t * t * t + 3.0 * t * t;
  7620. return to * t + from * (1.0 - t);
  7621. };
  7622. /**
  7623. * Moves a value current towards target.
  7624. *
  7625. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7626. * Negative values of maxDelta pushes the value away from target.
  7627. */
  7628. Scalar.MoveTowards = function (current, target, maxDelta) {
  7629. var result = 0;
  7630. if (Math.abs(target - current) <= maxDelta) {
  7631. result = target;
  7632. }
  7633. else {
  7634. result = current + Scalar.Sign(target - current) * maxDelta;
  7635. }
  7636. return result;
  7637. };
  7638. /**
  7639. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7640. *
  7641. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7642. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7643. */
  7644. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7645. var num = Scalar.DeltaAngle(current, target);
  7646. var result = 0;
  7647. if (-maxDelta < num && num < maxDelta) {
  7648. result = target;
  7649. }
  7650. else {
  7651. target = current + num;
  7652. result = Scalar.MoveTowards(current, target, maxDelta);
  7653. }
  7654. return result;
  7655. };
  7656. /**
  7657. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7658. */
  7659. Scalar.Lerp = function (start, end, amount) {
  7660. return start + ((end - start) * amount);
  7661. };
  7662. /**
  7663. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7664. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7665. */
  7666. Scalar.LerpAngle = function (start, end, amount) {
  7667. var num = Scalar.Repeat(end - start, 360.0);
  7668. if (num > 180.0) {
  7669. num -= 360.0;
  7670. }
  7671. return start + num * Scalar.Clamp(amount);
  7672. };
  7673. /**
  7674. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7675. */
  7676. Scalar.InverseLerp = function (a, b, value) {
  7677. var result = 0;
  7678. if (a != b) {
  7679. result = Scalar.Clamp((value - a) / (b - a));
  7680. }
  7681. else {
  7682. result = 0.0;
  7683. }
  7684. return result;
  7685. };
  7686. /**
  7687. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7688. */
  7689. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7690. var squared = amount * amount;
  7691. var cubed = amount * squared;
  7692. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7693. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7694. var part3 = (cubed - (2.0 * squared)) + amount;
  7695. var part4 = cubed - squared;
  7696. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7697. };
  7698. /**
  7699. * Returns a random float number between and min and max values
  7700. */
  7701. Scalar.RandomRange = function (min, max) {
  7702. if (min === max)
  7703. return min;
  7704. return ((Math.random() * (max - min)) + min);
  7705. };
  7706. /**
  7707. * This function returns percentage of a number in a given range.
  7708. *
  7709. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7710. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7711. */
  7712. Scalar.RangeToPercent = function (number, min, max) {
  7713. return ((number - min) / (max - min));
  7714. };
  7715. /**
  7716. * This function returns number that corresponds to the percentage in a given range.
  7717. *
  7718. * PercentToRange(0.34,0,100) will return 34.
  7719. */
  7720. Scalar.PercentToRange = function (percent, min, max) {
  7721. return ((max - min) * percent + min);
  7722. };
  7723. /**
  7724. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7725. * @param angle The angle to normalize in radian.
  7726. * @return The converted angle.
  7727. */
  7728. Scalar.NormalizeRadians = function (angle) {
  7729. // More precise but slower version kept for reference.
  7730. // angle = angle % Tools.TwoPi;
  7731. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7732. //if (angle > Math.PI) {
  7733. // angle -= Tools.TwoPi;
  7734. //}
  7735. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7736. return angle;
  7737. };
  7738. /**
  7739. * Two pi constants convenient for computation.
  7740. */
  7741. Scalar.TwoPi = Math.PI * 2;
  7742. return Scalar;
  7743. }());
  7744. BABYLON.Scalar = Scalar;
  7745. })(BABYLON || (BABYLON = {}));
  7746. //# sourceMappingURL=babylon.math.scalar.js.map
  7747. //# sourceMappingURL=babylon.mixins.js.map
  7748. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7749. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7750. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7751. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7752. //# sourceMappingURL=babylon.webgl2.js.map
  7753. var BABYLON;
  7754. (function (BABYLON) {
  7755. var __decoratorInitialStore = {};
  7756. var __mergedStore = {};
  7757. var _copySource = function (creationFunction, source, instanciate) {
  7758. var destination = creationFunction();
  7759. // Tags
  7760. if (BABYLON.Tags) {
  7761. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7762. }
  7763. var classStore = getMergedStore(destination);
  7764. // Properties
  7765. for (var property in classStore) {
  7766. var propertyDescriptor = classStore[property];
  7767. var sourceProperty = source[property];
  7768. var propertyType = propertyDescriptor.type;
  7769. if (sourceProperty !== undefined && sourceProperty !== null) {
  7770. switch (propertyType) {
  7771. case 0: // Value
  7772. case 6: // Mesh reference
  7773. case 11: // Camera reference
  7774. destination[property] = sourceProperty;
  7775. break;
  7776. case 1: // Texture
  7777. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7778. break;
  7779. case 2: // Color3
  7780. case 3: // FresnelParameters
  7781. case 4: // Vector2
  7782. case 5: // Vector3
  7783. case 7: // Color Curves
  7784. case 10: // Quaternion
  7785. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7786. break;
  7787. }
  7788. }
  7789. }
  7790. return destination;
  7791. };
  7792. function getDirectStore(target) {
  7793. var classKey = target.getClassName();
  7794. if (!__decoratorInitialStore[classKey]) {
  7795. __decoratorInitialStore[classKey] = {};
  7796. }
  7797. return __decoratorInitialStore[classKey];
  7798. }
  7799. /**
  7800. * Return the list of properties flagged as serializable
  7801. * @param target: host object
  7802. */
  7803. function getMergedStore(target) {
  7804. var classKey = target.getClassName();
  7805. if (__mergedStore[classKey]) {
  7806. return __mergedStore[classKey];
  7807. }
  7808. __mergedStore[classKey] = {};
  7809. var store = __mergedStore[classKey];
  7810. var currentTarget = target;
  7811. var currentKey = classKey;
  7812. while (currentKey) {
  7813. var initialStore = __decoratorInitialStore[currentKey];
  7814. for (var property in initialStore) {
  7815. store[property] = initialStore[property];
  7816. }
  7817. var parent_1 = void 0;
  7818. var done = false;
  7819. do {
  7820. parent_1 = Object.getPrototypeOf(currentTarget);
  7821. if (!parent_1.getClassName) {
  7822. done = true;
  7823. break;
  7824. }
  7825. if (parent_1.getClassName() !== currentKey) {
  7826. break;
  7827. }
  7828. currentTarget = parent_1;
  7829. } while (parent_1);
  7830. if (done) {
  7831. break;
  7832. }
  7833. currentKey = parent_1.getClassName();
  7834. currentTarget = parent_1;
  7835. }
  7836. return store;
  7837. }
  7838. function generateSerializableMember(type, sourceName) {
  7839. return function (target, propertyKey) {
  7840. var classStore = getDirectStore(target);
  7841. if (!classStore[propertyKey]) {
  7842. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7843. }
  7844. };
  7845. }
  7846. function generateExpandMember(setCallback, targetKey) {
  7847. if (targetKey === void 0) { targetKey = null; }
  7848. return function (target, propertyKey) {
  7849. var key = targetKey || ("_" + propertyKey);
  7850. Object.defineProperty(target, propertyKey, {
  7851. get: function () {
  7852. return this[key];
  7853. },
  7854. set: function (value) {
  7855. if (this[key] === value) {
  7856. return;
  7857. }
  7858. this[key] = value;
  7859. target[setCallback].apply(this);
  7860. },
  7861. enumerable: true,
  7862. configurable: true
  7863. });
  7864. };
  7865. }
  7866. function expandToProperty(callback, targetKey) {
  7867. if (targetKey === void 0) { targetKey = null; }
  7868. return generateExpandMember(callback, targetKey);
  7869. }
  7870. BABYLON.expandToProperty = expandToProperty;
  7871. function serialize(sourceName) {
  7872. return generateSerializableMember(0, sourceName); // value member
  7873. }
  7874. BABYLON.serialize = serialize;
  7875. function serializeAsTexture(sourceName) {
  7876. return generateSerializableMember(1, sourceName); // texture member
  7877. }
  7878. BABYLON.serializeAsTexture = serializeAsTexture;
  7879. function serializeAsColor3(sourceName) {
  7880. return generateSerializableMember(2, sourceName); // color3 member
  7881. }
  7882. BABYLON.serializeAsColor3 = serializeAsColor3;
  7883. function serializeAsFresnelParameters(sourceName) {
  7884. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7885. }
  7886. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7887. function serializeAsVector2(sourceName) {
  7888. return generateSerializableMember(4, sourceName); // vector2 member
  7889. }
  7890. BABYLON.serializeAsVector2 = serializeAsVector2;
  7891. function serializeAsVector3(sourceName) {
  7892. return generateSerializableMember(5, sourceName); // vector3 member
  7893. }
  7894. BABYLON.serializeAsVector3 = serializeAsVector3;
  7895. function serializeAsMeshReference(sourceName) {
  7896. return generateSerializableMember(6, sourceName); // mesh reference member
  7897. }
  7898. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7899. function serializeAsColorCurves(sourceName) {
  7900. return generateSerializableMember(7, sourceName); // color curves
  7901. }
  7902. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7903. function serializeAsColor4(sourceName) {
  7904. return generateSerializableMember(8, sourceName); // color 4
  7905. }
  7906. BABYLON.serializeAsColor4 = serializeAsColor4;
  7907. function serializeAsImageProcessingConfiguration(sourceName) {
  7908. return generateSerializableMember(9, sourceName); // image processing
  7909. }
  7910. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7911. function serializeAsQuaternion(sourceName) {
  7912. return generateSerializableMember(10, sourceName); // quaternion member
  7913. }
  7914. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7915. /**
  7916. * Decorator used to define property that can be serialized as reference to a camera
  7917. * @param sourceName defines the name of the property to decorate
  7918. */
  7919. function serializeAsCameraReference(sourceName) {
  7920. return generateSerializableMember(11, sourceName); // camera reference member
  7921. }
  7922. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7923. var SerializationHelper = /** @class */ (function () {
  7924. function SerializationHelper() {
  7925. }
  7926. SerializationHelper.Serialize = function (entity, serializationObject) {
  7927. if (!serializationObject) {
  7928. serializationObject = {};
  7929. }
  7930. // Tags
  7931. if (BABYLON.Tags) {
  7932. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7933. }
  7934. var serializedProperties = getMergedStore(entity);
  7935. // Properties
  7936. for (var property in serializedProperties) {
  7937. var propertyDescriptor = serializedProperties[property];
  7938. var targetPropertyName = propertyDescriptor.sourceName || property;
  7939. var propertyType = propertyDescriptor.type;
  7940. var sourceProperty = entity[property];
  7941. if (sourceProperty !== undefined && sourceProperty !== null) {
  7942. switch (propertyType) {
  7943. case 0: // Value
  7944. serializationObject[targetPropertyName] = sourceProperty;
  7945. break;
  7946. case 1: // Texture
  7947. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7948. break;
  7949. case 2: // Color3
  7950. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7951. break;
  7952. case 3: // FresnelParameters
  7953. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7954. break;
  7955. case 4: // Vector2
  7956. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7957. break;
  7958. case 5: // Vector3
  7959. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7960. break;
  7961. case 6: // Mesh reference
  7962. serializationObject[targetPropertyName] = sourceProperty.id;
  7963. break;
  7964. case 7: // Color Curves
  7965. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7966. break;
  7967. case 8: // Color 4
  7968. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7969. break;
  7970. case 9: // Image Processing
  7971. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7972. break;
  7973. case 10: // Quaternion
  7974. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7975. break;
  7976. case 11: // Camera reference
  7977. serializationObject[targetPropertyName] = sourceProperty.id;
  7978. break;
  7979. }
  7980. }
  7981. }
  7982. return serializationObject;
  7983. };
  7984. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7985. if (rootUrl === void 0) { rootUrl = null; }
  7986. var destination = creationFunction();
  7987. if (!rootUrl) {
  7988. rootUrl = "";
  7989. }
  7990. // Tags
  7991. if (BABYLON.Tags) {
  7992. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7993. }
  7994. var classStore = getMergedStore(destination);
  7995. // Properties
  7996. for (var property in classStore) {
  7997. var propertyDescriptor = classStore[property];
  7998. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7999. var propertyType = propertyDescriptor.type;
  8000. if (sourceProperty !== undefined && sourceProperty !== null) {
  8001. var dest = destination;
  8002. switch (propertyType) {
  8003. case 0: // Value
  8004. dest[property] = sourceProperty;
  8005. break;
  8006. case 1: // Texture
  8007. if (scene) {
  8008. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8009. }
  8010. break;
  8011. case 2: // Color3
  8012. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8013. break;
  8014. case 3: // FresnelParameters
  8015. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8016. break;
  8017. case 4: // Vector2
  8018. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8019. break;
  8020. case 5: // Vector3
  8021. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8022. break;
  8023. case 6: // Mesh reference
  8024. if (scene) {
  8025. dest[property] = scene.getLastMeshByID(sourceProperty);
  8026. }
  8027. break;
  8028. case 7: // Color Curves
  8029. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8030. break;
  8031. case 8: // Color 4
  8032. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8033. break;
  8034. case 9: // Image Processing
  8035. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8036. break;
  8037. case 10: // Quaternion
  8038. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8039. break;
  8040. case 11: // Camera reference
  8041. if (scene) {
  8042. dest[property] = scene.getCameraByID(sourceProperty);
  8043. }
  8044. break;
  8045. }
  8046. }
  8047. }
  8048. return destination;
  8049. };
  8050. SerializationHelper.Clone = function (creationFunction, source) {
  8051. return _copySource(creationFunction, source, false);
  8052. };
  8053. SerializationHelper.Instanciate = function (creationFunction, source) {
  8054. return _copySource(creationFunction, source, true);
  8055. };
  8056. return SerializationHelper;
  8057. }());
  8058. BABYLON.SerializationHelper = SerializationHelper;
  8059. })(BABYLON || (BABYLON = {}));
  8060. //# sourceMappingURL=babylon.decorators.js.map
  8061. var BABYLON;
  8062. (function (BABYLON) {
  8063. /**
  8064. * Wrapper class for promise with external resolve and reject.
  8065. */
  8066. var Deferred = /** @class */ (function () {
  8067. /**
  8068. * Constructor for this deferred object.
  8069. */
  8070. function Deferred() {
  8071. var _this = this;
  8072. this.promise = new Promise(function (resolve, reject) {
  8073. _this._resolve = resolve;
  8074. _this._reject = reject;
  8075. });
  8076. }
  8077. Object.defineProperty(Deferred.prototype, "resolve", {
  8078. /**
  8079. * The resolve method of the promise associated with this deferred object.
  8080. */
  8081. get: function () {
  8082. return this._resolve;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Deferred.prototype, "reject", {
  8088. /**
  8089. * The reject method of the promise associated with this deferred object.
  8090. */
  8091. get: function () {
  8092. return this._reject;
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. return Deferred;
  8098. }());
  8099. BABYLON.Deferred = Deferred;
  8100. })(BABYLON || (BABYLON = {}));
  8101. //# sourceMappingURL=babylon.deferred.js.map
  8102. var BABYLON;
  8103. (function (BABYLON) {
  8104. /**
  8105. * A class serves as a medium between the observable and its observers
  8106. */
  8107. var EventState = /** @class */ (function () {
  8108. /**
  8109. * Create a new EventState
  8110. * @param mask defines the mask associated with this state
  8111. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8112. * @param target defines the original target of the state
  8113. * @param currentTarget defines the current target of the state
  8114. */
  8115. function EventState(mask, skipNextObservers, target, currentTarget) {
  8116. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8117. this.initalize(mask, skipNextObservers, target, currentTarget);
  8118. }
  8119. /**
  8120. * Initialize the current event state
  8121. * @param mask defines the mask associated with this state
  8122. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8123. * @param target defines the original target of the state
  8124. * @param currentTarget defines the current target of the state
  8125. * @returns the current event state
  8126. */
  8127. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8128. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8129. this.mask = mask;
  8130. this.skipNextObservers = skipNextObservers;
  8131. this.target = target;
  8132. this.currentTarget = currentTarget;
  8133. return this;
  8134. };
  8135. return EventState;
  8136. }());
  8137. BABYLON.EventState = EventState;
  8138. /**
  8139. * Represent an Observer registered to a given Observable object.
  8140. */
  8141. var Observer = /** @class */ (function () {
  8142. /**
  8143. * Creates a new observer
  8144. * @param callback defines the callback to call when the observer is notified
  8145. * @param mask defines the mask of the observer (used to filter notifications)
  8146. * @param scope defines the current scope used to restore the JS context
  8147. */
  8148. function Observer(
  8149. /**
  8150. * Defines the callback to call when the observer is notified
  8151. */
  8152. callback,
  8153. /**
  8154. * Defines the mask of the observer (used to filter notifications)
  8155. */
  8156. mask,
  8157. /**
  8158. * Defines the current scope used to restore the JS context
  8159. */
  8160. scope) {
  8161. if (scope === void 0) { scope = null; }
  8162. this.callback = callback;
  8163. this.mask = mask;
  8164. this.scope = scope;
  8165. /** @hidden */
  8166. this._willBeUnregistered = false;
  8167. /**
  8168. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8169. */
  8170. this.unregisterOnNextCall = false;
  8171. }
  8172. return Observer;
  8173. }());
  8174. BABYLON.Observer = Observer;
  8175. /**
  8176. * Represent a list of observers registered to multiple Observables object.
  8177. */
  8178. var MultiObserver = /** @class */ (function () {
  8179. function MultiObserver() {
  8180. }
  8181. /**
  8182. * Release associated resources
  8183. */
  8184. MultiObserver.prototype.dispose = function () {
  8185. if (this._observers && this._observables) {
  8186. for (var index = 0; index < this._observers.length; index++) {
  8187. this._observables[index].remove(this._observers[index]);
  8188. }
  8189. }
  8190. this._observers = null;
  8191. this._observables = null;
  8192. };
  8193. /**
  8194. * Raise a callback when one of the observable will notify
  8195. * @param observables defines a list of observables to watch
  8196. * @param callback defines the callback to call on notification
  8197. * @param mask defines the mask used to filter notifications
  8198. * @param scope defines the current scope used to restore the JS context
  8199. * @returns the new MultiObserver
  8200. */
  8201. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8202. if (mask === void 0) { mask = -1; }
  8203. if (scope === void 0) { scope = null; }
  8204. var result = new MultiObserver();
  8205. result._observers = new Array();
  8206. result._observables = observables;
  8207. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8208. var observable = observables_1[_i];
  8209. var observer = observable.add(callback, mask, false, scope);
  8210. if (observer) {
  8211. result._observers.push(observer);
  8212. }
  8213. }
  8214. return result;
  8215. };
  8216. return MultiObserver;
  8217. }());
  8218. BABYLON.MultiObserver = MultiObserver;
  8219. /**
  8220. * The Observable class is a simple implementation of the Observable pattern.
  8221. *
  8222. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8223. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8224. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8225. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8226. */
  8227. var Observable = /** @class */ (function () {
  8228. /**
  8229. * Creates a new observable
  8230. * @param onObserverAdded defines a callback to call when a new observer is added
  8231. */
  8232. function Observable(onObserverAdded) {
  8233. this._observers = new Array();
  8234. this._eventState = new EventState(0);
  8235. if (onObserverAdded) {
  8236. this._onObserverAdded = onObserverAdded;
  8237. }
  8238. }
  8239. /**
  8240. * Create a new Observer with the specified callback
  8241. * @param callback the callback that will be executed for that Observer
  8242. * @param mask the mask used to filter observers
  8243. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8244. * @param scope optional scope for the callback to be called from
  8245. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8246. * @returns the new observer created for the callback
  8247. */
  8248. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8249. if (mask === void 0) { mask = -1; }
  8250. if (insertFirst === void 0) { insertFirst = false; }
  8251. if (scope === void 0) { scope = null; }
  8252. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8253. if (!callback) {
  8254. return null;
  8255. }
  8256. var observer = new Observer(callback, mask, scope);
  8257. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8258. if (insertFirst) {
  8259. this._observers.unshift(observer);
  8260. }
  8261. else {
  8262. this._observers.push(observer);
  8263. }
  8264. if (this._onObserverAdded) {
  8265. this._onObserverAdded(observer);
  8266. }
  8267. return observer;
  8268. };
  8269. /**
  8270. * Create a new Observer with the specified callback and unregisters after the next notification
  8271. * @param callback the callback that will be executed for that Observer
  8272. * @returns the new observer created for the callback
  8273. */
  8274. Observable.prototype.addOnce = function (callback) {
  8275. return this.add(callback, undefined, undefined, undefined, true);
  8276. };
  8277. /**
  8278. * Remove an Observer from the Observable object
  8279. * @param observer the instance of the Observer to remove
  8280. * @returns false if it doesn't belong to this Observable
  8281. */
  8282. Observable.prototype.remove = function (observer) {
  8283. if (!observer) {
  8284. return false;
  8285. }
  8286. var index = this._observers.indexOf(observer);
  8287. if (index !== -1) {
  8288. this._observers.splice(index, 1);
  8289. return true;
  8290. }
  8291. return false;
  8292. };
  8293. /**
  8294. * Remove a callback from the Observable object
  8295. * @param callback the callback to remove
  8296. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8297. * @returns false if it doesn't belong to this Observable
  8298. */
  8299. Observable.prototype.removeCallback = function (callback, scope) {
  8300. for (var index = 0; index < this._observers.length; index++) {
  8301. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8302. this._observers.splice(index, 1);
  8303. return true;
  8304. }
  8305. }
  8306. return false;
  8307. };
  8308. Observable.prototype._deferUnregister = function (observer) {
  8309. var _this = this;
  8310. observer.unregisterOnNextCall = false;
  8311. observer._willBeUnregistered = true;
  8312. BABYLON.Tools.SetImmediate(function () {
  8313. _this.remove(observer);
  8314. });
  8315. };
  8316. /**
  8317. * Notify all Observers by calling their respective callback with the given data
  8318. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8319. * @param eventData defines the data to send to all observers
  8320. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8321. * @param target defines the original target of the state
  8322. * @param currentTarget defines the current target of the state
  8323. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8324. */
  8325. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8326. if (mask === void 0) { mask = -1; }
  8327. if (!this._observers.length) {
  8328. return true;
  8329. }
  8330. var state = this._eventState;
  8331. state.mask = mask;
  8332. state.target = target;
  8333. state.currentTarget = currentTarget;
  8334. state.skipNextObservers = false;
  8335. state.lastReturnValue = eventData;
  8336. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8337. var obs = _a[_i];
  8338. if (obs._willBeUnregistered) {
  8339. continue;
  8340. }
  8341. if (obs.mask & mask) {
  8342. if (obs.scope) {
  8343. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8344. }
  8345. else {
  8346. state.lastReturnValue = obs.callback(eventData, state);
  8347. }
  8348. if (obs.unregisterOnNextCall) {
  8349. this._deferUnregister(obs);
  8350. }
  8351. }
  8352. if (state.skipNextObservers) {
  8353. return false;
  8354. }
  8355. }
  8356. return true;
  8357. };
  8358. /**
  8359. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8360. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8361. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8362. * and it is crucial that all callbacks will be executed.
  8363. * The order of the callbacks is kept, callbacks are not executed parallel.
  8364. *
  8365. * @param eventData The data to be sent to each callback
  8366. * @param mask is used to filter observers defaults to -1
  8367. * @param target defines the callback target (see EventState)
  8368. * @param currentTarget defines he current object in the bubbling phase
  8369. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8370. */
  8371. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8372. var _this = this;
  8373. if (mask === void 0) { mask = -1; }
  8374. // create an empty promise
  8375. var p = Promise.resolve(eventData);
  8376. // no observers? return this promise.
  8377. if (!this._observers.length) {
  8378. return p;
  8379. }
  8380. var state = this._eventState;
  8381. state.mask = mask;
  8382. state.target = target;
  8383. state.currentTarget = currentTarget;
  8384. state.skipNextObservers = false;
  8385. // execute one callback after another (not using Promise.all, the order is important)
  8386. this._observers.forEach(function (obs) {
  8387. if (state.skipNextObservers) {
  8388. return;
  8389. }
  8390. if (obs._willBeUnregistered) {
  8391. return;
  8392. }
  8393. if (obs.mask & mask) {
  8394. if (obs.scope) {
  8395. p = p.then(function (lastReturnedValue) {
  8396. state.lastReturnValue = lastReturnedValue;
  8397. return obs.callback.apply(obs.scope, [eventData, state]);
  8398. });
  8399. }
  8400. else {
  8401. p = p.then(function (lastReturnedValue) {
  8402. state.lastReturnValue = lastReturnedValue;
  8403. return obs.callback(eventData, state);
  8404. });
  8405. }
  8406. if (obs.unregisterOnNextCall) {
  8407. _this._deferUnregister(obs);
  8408. }
  8409. }
  8410. });
  8411. // return the eventData
  8412. return p.then(function () { return eventData; });
  8413. };
  8414. /**
  8415. * Notify a specific observer
  8416. * @param observer defines the observer to notify
  8417. * @param eventData defines the data to be sent to each callback
  8418. * @param mask is used to filter observers defaults to -1
  8419. */
  8420. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8421. if (mask === void 0) { mask = -1; }
  8422. var state = this._eventState;
  8423. state.mask = mask;
  8424. state.skipNextObservers = false;
  8425. observer.callback(eventData, state);
  8426. };
  8427. /**
  8428. * Gets a boolean indicating if the observable has at least one observer
  8429. * @returns true is the Observable has at least one Observer registered
  8430. */
  8431. Observable.prototype.hasObservers = function () {
  8432. return this._observers.length > 0;
  8433. };
  8434. /**
  8435. * Clear the list of observers
  8436. */
  8437. Observable.prototype.clear = function () {
  8438. this._observers = new Array();
  8439. this._onObserverAdded = null;
  8440. };
  8441. /**
  8442. * Clone the current observable
  8443. * @returns a new observable
  8444. */
  8445. Observable.prototype.clone = function () {
  8446. var result = new Observable();
  8447. result._observers = this._observers.slice(0);
  8448. return result;
  8449. };
  8450. /**
  8451. * Does this observable handles observer registered with a given mask
  8452. * @param mask defines the mask to be tested
  8453. * @return whether or not one observer registered with the given mask is handeled
  8454. **/
  8455. Observable.prototype.hasSpecificMask = function (mask) {
  8456. if (mask === void 0) { mask = -1; }
  8457. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8458. var obs = _a[_i];
  8459. if (obs.mask & mask || obs.mask === mask) {
  8460. return true;
  8461. }
  8462. }
  8463. return false;
  8464. };
  8465. return Observable;
  8466. }());
  8467. BABYLON.Observable = Observable;
  8468. })(BABYLON || (BABYLON = {}));
  8469. //# sourceMappingURL=babylon.observable.js.map
  8470. var BABYLON;
  8471. (function (BABYLON) {
  8472. var SmartArray = /** @class */ (function () {
  8473. function SmartArray(capacity) {
  8474. this.length = 0;
  8475. this.data = new Array(capacity);
  8476. this._id = SmartArray._GlobalId++;
  8477. }
  8478. SmartArray.prototype.push = function (value) {
  8479. this.data[this.length++] = value;
  8480. if (this.length > this.data.length) {
  8481. this.data.length *= 2;
  8482. }
  8483. };
  8484. SmartArray.prototype.forEach = function (func) {
  8485. for (var index = 0; index < this.length; index++) {
  8486. func(this.data[index]);
  8487. }
  8488. };
  8489. SmartArray.prototype.sort = function (compareFn) {
  8490. this.data.sort(compareFn);
  8491. };
  8492. SmartArray.prototype.reset = function () {
  8493. this.length = 0;
  8494. };
  8495. SmartArray.prototype.dispose = function () {
  8496. this.reset();
  8497. if (this.data) {
  8498. this.data.length = 0;
  8499. this.data = [];
  8500. }
  8501. };
  8502. SmartArray.prototype.concat = function (array) {
  8503. if (array.length === 0) {
  8504. return;
  8505. }
  8506. if (this.length + array.length > this.data.length) {
  8507. this.data.length = (this.length + array.length) * 2;
  8508. }
  8509. for (var index = 0; index < array.length; index++) {
  8510. this.data[this.length++] = (array.data || array)[index];
  8511. }
  8512. };
  8513. SmartArray.prototype.indexOf = function (value) {
  8514. var position = this.data.indexOf(value);
  8515. if (position >= this.length) {
  8516. return -1;
  8517. }
  8518. return position;
  8519. };
  8520. SmartArray.prototype.contains = function (value) {
  8521. return this.data.indexOf(value) !== -1;
  8522. };
  8523. // Statics
  8524. SmartArray._GlobalId = 0;
  8525. return SmartArray;
  8526. }());
  8527. BABYLON.SmartArray = SmartArray;
  8528. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8529. __extends(SmartArrayNoDuplicate, _super);
  8530. function SmartArrayNoDuplicate() {
  8531. var _this = _super !== null && _super.apply(this, arguments) || this;
  8532. _this._duplicateId = 0;
  8533. return _this;
  8534. }
  8535. SmartArrayNoDuplicate.prototype.push = function (value) {
  8536. _super.prototype.push.call(this, value);
  8537. if (!value.__smartArrayFlags) {
  8538. value.__smartArrayFlags = {};
  8539. }
  8540. value.__smartArrayFlags[this._id] = this._duplicateId;
  8541. };
  8542. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8543. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8544. return false;
  8545. }
  8546. this.push(value);
  8547. return true;
  8548. };
  8549. SmartArrayNoDuplicate.prototype.reset = function () {
  8550. _super.prototype.reset.call(this);
  8551. this._duplicateId++;
  8552. };
  8553. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8554. if (array.length === 0) {
  8555. return;
  8556. }
  8557. if (this.length + array.length > this.data.length) {
  8558. this.data.length = (this.length + array.length) * 2;
  8559. }
  8560. for (var index = 0; index < array.length; index++) {
  8561. var item = (array.data || array)[index];
  8562. this.pushNoDuplicate(item);
  8563. }
  8564. };
  8565. return SmartArrayNoDuplicate;
  8566. }(SmartArray));
  8567. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8568. })(BABYLON || (BABYLON = {}));
  8569. //# sourceMappingURL=babylon.smartArray.js.map
  8570. var BABYLON;
  8571. (function (BABYLON) {
  8572. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8573. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8574. var LoadFileError = /** @class */ (function (_super) {
  8575. __extends(LoadFileError, _super);
  8576. function LoadFileError(message, request) {
  8577. var _this = _super.call(this, message) || this;
  8578. _this.request = request;
  8579. _this.name = "LoadFileError";
  8580. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8581. return _this;
  8582. }
  8583. // Polyfill for Object.setPrototypeOf if necessary.
  8584. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8585. return LoadFileError;
  8586. }(Error));
  8587. BABYLON.LoadFileError = LoadFileError;
  8588. var RetryStrategy = /** @class */ (function () {
  8589. function RetryStrategy() {
  8590. }
  8591. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8592. if (maxRetries === void 0) { maxRetries = 3; }
  8593. if (baseInterval === void 0) { baseInterval = 500; }
  8594. return function (url, request, retryIndex) {
  8595. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8596. return -1;
  8597. }
  8598. return Math.pow(2, retryIndex) * baseInterval;
  8599. };
  8600. };
  8601. return RetryStrategy;
  8602. }());
  8603. BABYLON.RetryStrategy = RetryStrategy;
  8604. // Screenshots
  8605. var screenshotCanvas;
  8606. var cloneValue = function (source, destinationObject) {
  8607. if (!source)
  8608. return null;
  8609. if (source instanceof BABYLON.Mesh) {
  8610. return null;
  8611. }
  8612. if (source instanceof BABYLON.SubMesh) {
  8613. return source.clone(destinationObject);
  8614. }
  8615. else if (source.clone) {
  8616. return source.clone();
  8617. }
  8618. return null;
  8619. };
  8620. var Tools = /** @class */ (function () {
  8621. function Tools() {
  8622. }
  8623. /**
  8624. * Interpolates between a and b via alpha
  8625. * @param a The lower value (returned when alpha = 0)
  8626. * @param b The upper value (returned when alpha = 1)
  8627. * @param alpha The interpolation-factor
  8628. * @return The mixed value
  8629. */
  8630. Tools.Mix = function (a, b, alpha) {
  8631. return a * (1 - alpha) + b * alpha;
  8632. };
  8633. Tools.Instantiate = function (className) {
  8634. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8635. return Tools.RegisteredExternalClasses[className];
  8636. }
  8637. var arr = className.split(".");
  8638. var fn = (window || this);
  8639. for (var i = 0, len = arr.length; i < len; i++) {
  8640. fn = fn[arr[i]];
  8641. }
  8642. if (typeof fn !== "function") {
  8643. return null;
  8644. }
  8645. return fn;
  8646. };
  8647. /**
  8648. * Provides a slice function that will work even on IE
  8649. * @param data defines the array to slice
  8650. * @param start defines the start of the data (optional)
  8651. * @param end defines the end of the data (optional)
  8652. * @returns the new sliced array
  8653. */
  8654. Tools.Slice = function (data, start, end) {
  8655. if (data.slice) {
  8656. return data.slice(start, end);
  8657. }
  8658. return Array.prototype.slice.call(data, start, end);
  8659. };
  8660. Tools.SetImmediate = function (action) {
  8661. if (window.setImmediate) {
  8662. window.setImmediate(action);
  8663. }
  8664. else {
  8665. setTimeout(action, 1);
  8666. }
  8667. };
  8668. Tools.IsExponentOfTwo = function (value) {
  8669. var count = 1;
  8670. do {
  8671. count *= 2;
  8672. } while (count < value);
  8673. return count === value;
  8674. };
  8675. /**
  8676. * Returns the nearest 32-bit single precision float representation of a Number
  8677. * @param value A Number. If the parameter is of a different type, it will get converted
  8678. * to a number or to NaN if it cannot be converted
  8679. * @returns number
  8680. */
  8681. Tools.FloatRound = function (value) {
  8682. if (Math.fround) {
  8683. return Math.fround(value);
  8684. }
  8685. return (Tools._tmpFloatArray[0] = value);
  8686. };
  8687. /**
  8688. * Find the next highest power of two.
  8689. * @param x Number to start search from.
  8690. * @return Next highest power of two.
  8691. */
  8692. Tools.CeilingPOT = function (x) {
  8693. x--;
  8694. x |= x >> 1;
  8695. x |= x >> 2;
  8696. x |= x >> 4;
  8697. x |= x >> 8;
  8698. x |= x >> 16;
  8699. x++;
  8700. return x;
  8701. };
  8702. /**
  8703. * Find the next lowest power of two.
  8704. * @param x Number to start search from.
  8705. * @return Next lowest power of two.
  8706. */
  8707. Tools.FloorPOT = function (x) {
  8708. x = x | (x >> 1);
  8709. x = x | (x >> 2);
  8710. x = x | (x >> 4);
  8711. x = x | (x >> 8);
  8712. x = x | (x >> 16);
  8713. return x - (x >> 1);
  8714. };
  8715. /**
  8716. * Find the nearest power of two.
  8717. * @param x Number to start search from.
  8718. * @return Next nearest power of two.
  8719. */
  8720. Tools.NearestPOT = function (x) {
  8721. var c = Tools.CeilingPOT(x);
  8722. var f = Tools.FloorPOT(x);
  8723. return (c - x) > (x - f) ? f : c;
  8724. };
  8725. Tools.GetExponentOfTwo = function (value, max, mode) {
  8726. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8727. var pot;
  8728. switch (mode) {
  8729. case BABYLON.Engine.SCALEMODE_FLOOR:
  8730. pot = Tools.FloorPOT(value);
  8731. break;
  8732. case BABYLON.Engine.SCALEMODE_NEAREST:
  8733. pot = Tools.NearestPOT(value);
  8734. break;
  8735. case BABYLON.Engine.SCALEMODE_CEILING:
  8736. default:
  8737. pot = Tools.CeilingPOT(value);
  8738. break;
  8739. }
  8740. return Math.min(pot, max);
  8741. };
  8742. Tools.GetFilename = function (path) {
  8743. var index = path.lastIndexOf("/");
  8744. if (index < 0)
  8745. return path;
  8746. return path.substring(index + 1);
  8747. };
  8748. /**
  8749. * Extracts the "folder" part of a path (everything before the filename).
  8750. * @param uri The URI to extract the info from
  8751. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8752. * @returns The "folder" part of the path
  8753. */
  8754. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8755. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8756. var index = uri.lastIndexOf("/");
  8757. if (index < 0) {
  8758. if (returnUnchangedIfNoSlash) {
  8759. return uri;
  8760. }
  8761. return "";
  8762. }
  8763. return uri.substring(0, index + 1);
  8764. };
  8765. Tools.GetDOMTextContent = function (element) {
  8766. var result = "";
  8767. var child = element.firstChild;
  8768. while (child) {
  8769. if (child.nodeType === 3) {
  8770. result += child.textContent;
  8771. }
  8772. child = child.nextSibling;
  8773. }
  8774. return result;
  8775. };
  8776. Tools.ToDegrees = function (angle) {
  8777. return angle * 180 / Math.PI;
  8778. };
  8779. Tools.ToRadians = function (angle) {
  8780. return angle * Math.PI / 180;
  8781. };
  8782. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8783. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8784. var output = "";
  8785. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8786. var i = 0;
  8787. var bytes = new Uint8Array(buffer);
  8788. while (i < bytes.length) {
  8789. chr1 = bytes[i++];
  8790. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8791. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8792. enc1 = chr1 >> 2;
  8793. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8794. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8795. enc4 = chr3 & 63;
  8796. if (isNaN(chr2)) {
  8797. enc3 = enc4 = 64;
  8798. }
  8799. else if (isNaN(chr3)) {
  8800. enc4 = 64;
  8801. }
  8802. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8803. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8804. }
  8805. return "data:image/png;base64," + output;
  8806. };
  8807. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8808. if (bias === void 0) { bias = null; }
  8809. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8810. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8811. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8812. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8813. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8814. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8815. }
  8816. if (bias) {
  8817. minimum.x -= minimum.x * bias.x + bias.y;
  8818. minimum.y -= minimum.y * bias.x + bias.y;
  8819. minimum.z -= minimum.z * bias.x + bias.y;
  8820. maximum.x += maximum.x * bias.x + bias.y;
  8821. maximum.y += maximum.y * bias.x + bias.y;
  8822. maximum.z += maximum.z * bias.x + bias.y;
  8823. }
  8824. return {
  8825. minimum: minimum,
  8826. maximum: maximum
  8827. };
  8828. };
  8829. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8830. if (bias === void 0) { bias = null; }
  8831. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8832. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8833. if (!stride) {
  8834. stride = 3;
  8835. }
  8836. for (var index = start; index < start + count; index++) {
  8837. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8838. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8839. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8840. }
  8841. if (bias) {
  8842. minimum.x -= minimum.x * bias.x + bias.y;
  8843. minimum.y -= minimum.y * bias.x + bias.y;
  8844. minimum.z -= minimum.z * bias.x + bias.y;
  8845. maximum.x += maximum.x * bias.x + bias.y;
  8846. maximum.y += maximum.y * bias.x + bias.y;
  8847. maximum.z += maximum.z * bias.x + bias.y;
  8848. }
  8849. return {
  8850. minimum: minimum,
  8851. maximum: maximum
  8852. };
  8853. };
  8854. Tools.Vector2ArrayFeeder = function (array) {
  8855. return function (index) {
  8856. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8857. var length = isFloatArray ? array.length / 2 : array.length;
  8858. if (index >= length) {
  8859. return null;
  8860. }
  8861. if (isFloatArray) {
  8862. var fa = array;
  8863. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8864. }
  8865. var a = array;
  8866. return a[index];
  8867. };
  8868. };
  8869. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8870. if (bias === void 0) { bias = null; }
  8871. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8872. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8873. var i = 0;
  8874. var cur = feeder(i++);
  8875. while (cur) {
  8876. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8877. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8878. cur = feeder(i++);
  8879. }
  8880. if (bias) {
  8881. minimum.x -= minimum.x * bias.x + bias.y;
  8882. minimum.y -= minimum.y * bias.x + bias.y;
  8883. maximum.x += maximum.x * bias.x + bias.y;
  8884. maximum.y += maximum.y * bias.x + bias.y;
  8885. }
  8886. return {
  8887. minimum: minimum,
  8888. maximum: maximum
  8889. };
  8890. };
  8891. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8892. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8893. return null;
  8894. return Array.isArray(obj) ? obj : [obj];
  8895. };
  8896. // Misc.
  8897. Tools.GetPointerPrefix = function () {
  8898. var eventPrefix = "pointer";
  8899. // Check if pointer events are supported
  8900. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8901. eventPrefix = "mouse";
  8902. }
  8903. return eventPrefix;
  8904. };
  8905. /**
  8906. * @param func - the function to be called
  8907. * @param requester - the object that will request the next frame. Falls back to window.
  8908. */
  8909. Tools.QueueNewFrame = function (func, requester) {
  8910. if (!Tools.IsWindowObjectExist()) {
  8911. return setTimeout(func, 16);
  8912. }
  8913. if (!requester) {
  8914. requester = window;
  8915. }
  8916. if (requester.requestAnimationFrame) {
  8917. return requester.requestAnimationFrame(func);
  8918. }
  8919. else if (requester.msRequestAnimationFrame) {
  8920. return requester.msRequestAnimationFrame(func);
  8921. }
  8922. else if (requester.webkitRequestAnimationFrame) {
  8923. return requester.webkitRequestAnimationFrame(func);
  8924. }
  8925. else if (requester.mozRequestAnimationFrame) {
  8926. return requester.mozRequestAnimationFrame(func);
  8927. }
  8928. else if (requester.oRequestAnimationFrame) {
  8929. return requester.oRequestAnimationFrame(func);
  8930. }
  8931. else {
  8932. return window.setTimeout(func, 16);
  8933. }
  8934. };
  8935. Tools.RequestFullscreen = function (element) {
  8936. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8937. if (!requestFunction)
  8938. return;
  8939. requestFunction.call(element);
  8940. };
  8941. Tools.ExitFullscreen = function () {
  8942. if (document.exitFullscreen) {
  8943. document.exitFullscreen();
  8944. }
  8945. else if (document.mozCancelFullScreen) {
  8946. document.mozCancelFullScreen();
  8947. }
  8948. else if (document.webkitCancelFullScreen) {
  8949. document.webkitCancelFullScreen();
  8950. }
  8951. else if (document.msCancelFullScreen) {
  8952. document.msCancelFullScreen();
  8953. }
  8954. };
  8955. Tools.SetCorsBehavior = function (url, element) {
  8956. if (url && url.indexOf("data:") === 0) {
  8957. return;
  8958. }
  8959. if (Tools.CorsBehavior) {
  8960. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8961. element.crossOrigin = Tools.CorsBehavior;
  8962. }
  8963. else {
  8964. var result = Tools.CorsBehavior(url);
  8965. if (result) {
  8966. element.crossOrigin = result;
  8967. }
  8968. }
  8969. }
  8970. };
  8971. // External files
  8972. Tools.CleanUrl = function (url) {
  8973. url = url.replace(/#/mg, "%23");
  8974. return url;
  8975. };
  8976. /**
  8977. * Loads an image as an HTMLImageElement.
  8978. * @param input url string, ArrayBuffer, or Blob to load
  8979. * @param onLoad callback called when the image successfully loads
  8980. * @param onError callback called when the image fails to load
  8981. * @param database database for caching
  8982. * @returns the HTMLImageElement of the loaded image
  8983. */
  8984. Tools.LoadImage = function (input, onLoad, onError, database) {
  8985. var url;
  8986. var usingObjectURL = false;
  8987. if (input instanceof ArrayBuffer) {
  8988. url = URL.createObjectURL(new Blob([input]));
  8989. usingObjectURL = true;
  8990. }
  8991. else if (input instanceof Blob) {
  8992. url = URL.createObjectURL(input);
  8993. usingObjectURL = true;
  8994. }
  8995. else {
  8996. url = Tools.CleanUrl(input);
  8997. url = Tools.PreprocessUrl(input);
  8998. }
  8999. var img = new Image();
  9000. Tools.SetCorsBehavior(url, img);
  9001. var loadHandler = function () {
  9002. if (usingObjectURL && img.src) {
  9003. URL.revokeObjectURL(img.src);
  9004. }
  9005. img.removeEventListener("load", loadHandler);
  9006. img.removeEventListener("error", errorHandler);
  9007. onLoad(img);
  9008. };
  9009. var errorHandler = function (err) {
  9010. if (usingObjectURL && img.src) {
  9011. URL.revokeObjectURL(img.src);
  9012. }
  9013. img.removeEventListener("load", loadHandler);
  9014. img.removeEventListener("error", errorHandler);
  9015. Tools.Error("Error while trying to load image: " + input);
  9016. if (onError) {
  9017. onError("Error while trying to load image: " + input, err);
  9018. }
  9019. };
  9020. img.addEventListener("load", loadHandler);
  9021. img.addEventListener("error", errorHandler);
  9022. var noIndexedDB = function () {
  9023. img.src = url;
  9024. };
  9025. var loadFromIndexedDB = function () {
  9026. if (database) {
  9027. database.loadImageFromDB(url, img);
  9028. }
  9029. };
  9030. //ANY database to do!
  9031. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9032. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9033. }
  9034. else {
  9035. if (url.indexOf("file:") !== -1) {
  9036. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9037. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9038. try {
  9039. var blobURL;
  9040. try {
  9041. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9042. }
  9043. catch (ex) {
  9044. // Chrome doesn't support oneTimeOnly parameter
  9045. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9046. }
  9047. img.src = blobURL;
  9048. usingObjectURL = true;
  9049. }
  9050. catch (e) {
  9051. img.src = "";
  9052. }
  9053. return img;
  9054. }
  9055. }
  9056. noIndexedDB();
  9057. }
  9058. return img;
  9059. };
  9060. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9061. url = Tools.CleanUrl(url);
  9062. url = Tools.PreprocessUrl(url);
  9063. // If file and file input are set
  9064. if (url.indexOf("file:") !== -1) {
  9065. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9066. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9067. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9068. }
  9069. }
  9070. var loadUrl = Tools.BaseUrl + url;
  9071. var aborted = false;
  9072. var fileRequest = {
  9073. onCompleteObservable: new BABYLON.Observable(),
  9074. abort: function () { return aborted = true; },
  9075. };
  9076. var requestFile = function () {
  9077. var request = new XMLHttpRequest();
  9078. var retryHandle = null;
  9079. fileRequest.abort = function () {
  9080. aborted = true;
  9081. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9082. request.abort();
  9083. }
  9084. if (retryHandle !== null) {
  9085. clearTimeout(retryHandle);
  9086. retryHandle = null;
  9087. }
  9088. };
  9089. var retryLoop = function (retryIndex) {
  9090. request.open('GET', loadUrl, true);
  9091. if (useArrayBuffer) {
  9092. request.responseType = "arraybuffer";
  9093. }
  9094. if (onProgress) {
  9095. request.addEventListener("progress", onProgress);
  9096. }
  9097. var onLoadEnd = function () {
  9098. request.removeEventListener("loadend", onLoadEnd);
  9099. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9100. fileRequest.onCompleteObservable.clear();
  9101. };
  9102. request.addEventListener("loadend", onLoadEnd);
  9103. var onReadyStateChange = function () {
  9104. if (aborted) {
  9105. return;
  9106. }
  9107. // In case of undefined state in some browsers.
  9108. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9109. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9110. request.removeEventListener("readystatechange", onReadyStateChange);
  9111. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9112. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9113. return;
  9114. }
  9115. var retryStrategy = Tools.DefaultRetryStrategy;
  9116. if (retryStrategy) {
  9117. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9118. if (waitTime !== -1) {
  9119. // Prevent the request from completing for retry.
  9120. request.removeEventListener("loadend", onLoadEnd);
  9121. request = new XMLHttpRequest();
  9122. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9123. return;
  9124. }
  9125. }
  9126. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9127. if (onError) {
  9128. onError(request, e);
  9129. }
  9130. else {
  9131. throw e;
  9132. }
  9133. }
  9134. };
  9135. request.addEventListener("readystatechange", onReadyStateChange);
  9136. request.send();
  9137. };
  9138. retryLoop(0);
  9139. };
  9140. // Caching all files
  9141. if (database && database.enableSceneOffline) {
  9142. var noIndexedDB_1 = function () {
  9143. if (!aborted) {
  9144. requestFile();
  9145. }
  9146. };
  9147. var loadFromIndexedDB = function () {
  9148. // TODO: database needs to support aborting and should return a IFileRequest
  9149. if (aborted) {
  9150. return;
  9151. }
  9152. if (database) {
  9153. database.loadFileFromDB(url, function (data) {
  9154. if (!aborted) {
  9155. onSuccess(data);
  9156. }
  9157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9158. }, onProgress ? function (event) {
  9159. if (!aborted) {
  9160. onProgress(event);
  9161. }
  9162. } : undefined, noIndexedDB_1, useArrayBuffer);
  9163. }
  9164. };
  9165. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9166. }
  9167. else {
  9168. requestFile();
  9169. }
  9170. return fileRequest;
  9171. };
  9172. /**
  9173. * Load a script (identified by an url). When the url returns, the
  9174. * content of this file is added into a new script element, attached to the DOM (body element)
  9175. */
  9176. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9177. var head = document.getElementsByTagName('head')[0];
  9178. var script = document.createElement('script');
  9179. script.type = 'text/javascript';
  9180. script.src = scriptUrl;
  9181. script.onload = function () {
  9182. if (onSuccess) {
  9183. onSuccess();
  9184. }
  9185. };
  9186. script.onerror = function (e) {
  9187. if (onError) {
  9188. onError("Unable to load script '" + scriptUrl + "'", e);
  9189. }
  9190. };
  9191. head.appendChild(script);
  9192. };
  9193. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9194. var reader = new FileReader();
  9195. var request = {
  9196. onCompleteObservable: new BABYLON.Observable(),
  9197. abort: function () { return reader.abort(); },
  9198. };
  9199. reader.onloadend = function (e) {
  9200. request.onCompleteObservable.notifyObservers(request);
  9201. };
  9202. reader.onload = function (e) {
  9203. //target doesn't have result from ts 1.3
  9204. callback(e.target['result']);
  9205. };
  9206. reader.onprogress = progressCallback;
  9207. reader.readAsDataURL(fileToLoad);
  9208. return request;
  9209. };
  9210. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9211. var reader = new FileReader();
  9212. var request = {
  9213. onCompleteObservable: new BABYLON.Observable(),
  9214. abort: function () { return reader.abort(); },
  9215. };
  9216. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9217. reader.onerror = function (e) {
  9218. Tools.Log("Error while reading file: " + fileToLoad.name);
  9219. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9220. };
  9221. reader.onload = function (e) {
  9222. //target doesn't have result from ts 1.3
  9223. callback(e.target['result']);
  9224. };
  9225. if (progressCallBack) {
  9226. reader.onprogress = progressCallBack;
  9227. }
  9228. if (!useArrayBuffer) {
  9229. // Asynchronous read
  9230. reader.readAsText(fileToLoad);
  9231. }
  9232. else {
  9233. reader.readAsArrayBuffer(fileToLoad);
  9234. }
  9235. return request;
  9236. };
  9237. //returns a downloadable url to a file content.
  9238. Tools.FileAsURL = function (content) {
  9239. var fileBlob = new Blob([content]);
  9240. var url = window.URL || window.webkitURL;
  9241. var link = url.createObjectURL(fileBlob);
  9242. return link;
  9243. };
  9244. // Misc.
  9245. Tools.Format = function (value, decimals) {
  9246. if (decimals === void 0) { decimals = 2; }
  9247. return value.toFixed(decimals);
  9248. };
  9249. Tools.CheckExtends = function (v, min, max) {
  9250. if (v.x < min.x)
  9251. min.x = v.x;
  9252. if (v.y < min.y)
  9253. min.y = v.y;
  9254. if (v.z < min.z)
  9255. min.z = v.z;
  9256. if (v.x > max.x)
  9257. max.x = v.x;
  9258. if (v.y > max.y)
  9259. max.y = v.y;
  9260. if (v.z > max.z)
  9261. max.z = v.z;
  9262. };
  9263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9264. for (var prop in source) {
  9265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9266. continue;
  9267. }
  9268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9269. continue;
  9270. }
  9271. var sourceValue = source[prop];
  9272. var typeOfSourceValue = typeof sourceValue;
  9273. if (typeOfSourceValue === "function") {
  9274. continue;
  9275. }
  9276. try {
  9277. if (typeOfSourceValue === "object") {
  9278. if (sourceValue instanceof Array) {
  9279. destination[prop] = [];
  9280. if (sourceValue.length > 0) {
  9281. if (typeof sourceValue[0] == "object") {
  9282. for (var index = 0; index < sourceValue.length; index++) {
  9283. var clonedValue = cloneValue(sourceValue[index], destination);
  9284. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9285. destination[prop].push(clonedValue);
  9286. }
  9287. }
  9288. }
  9289. else {
  9290. destination[prop] = sourceValue.slice(0);
  9291. }
  9292. }
  9293. }
  9294. else {
  9295. destination[prop] = cloneValue(sourceValue, destination);
  9296. }
  9297. }
  9298. else {
  9299. destination[prop] = sourceValue;
  9300. }
  9301. }
  9302. catch (e) {
  9303. // Just ignore error (it could be because of a read-only property)
  9304. }
  9305. }
  9306. };
  9307. Tools.IsEmpty = function (obj) {
  9308. for (var i in obj) {
  9309. if (obj.hasOwnProperty(i)) {
  9310. return false;
  9311. }
  9312. }
  9313. return true;
  9314. };
  9315. Tools.RegisterTopRootEvents = function (events) {
  9316. for (var index = 0; index < events.length; index++) {
  9317. var event = events[index];
  9318. window.addEventListener(event.name, event.handler, false);
  9319. try {
  9320. if (window.parent) {
  9321. window.parent.addEventListener(event.name, event.handler, false);
  9322. }
  9323. }
  9324. catch (e) {
  9325. // Silently fails...
  9326. }
  9327. }
  9328. };
  9329. Tools.UnregisterTopRootEvents = function (events) {
  9330. for (var index = 0; index < events.length; index++) {
  9331. var event = events[index];
  9332. window.removeEventListener(event.name, event.handler);
  9333. try {
  9334. if (window.parent) {
  9335. window.parent.removeEventListener(event.name, event.handler);
  9336. }
  9337. }
  9338. catch (e) {
  9339. // Silently fails...
  9340. }
  9341. }
  9342. };
  9343. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9344. if (mimeType === void 0) { mimeType = "image/png"; }
  9345. // Read the contents of the framebuffer
  9346. var numberOfChannelsByLine = width * 4;
  9347. var halfHeight = height / 2;
  9348. //Reading datas from WebGL
  9349. var data = engine.readPixels(0, 0, width, height);
  9350. //To flip image on Y axis.
  9351. for (var i = 0; i < halfHeight; i++) {
  9352. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9353. var currentCell = j + i * numberOfChannelsByLine;
  9354. var targetLine = height - i - 1;
  9355. var targetCell = j + targetLine * numberOfChannelsByLine;
  9356. var temp = data[currentCell];
  9357. data[currentCell] = data[targetCell];
  9358. data[targetCell] = temp;
  9359. }
  9360. }
  9361. // Create a 2D canvas to store the result
  9362. if (!screenshotCanvas) {
  9363. screenshotCanvas = document.createElement('canvas');
  9364. }
  9365. screenshotCanvas.width = width;
  9366. screenshotCanvas.height = height;
  9367. var context = screenshotCanvas.getContext('2d');
  9368. if (context) {
  9369. // Copy the pixels to a 2D canvas
  9370. var imageData = context.createImageData(width, height);
  9371. var castData = (imageData.data);
  9372. castData.set(data);
  9373. context.putImageData(imageData, 0, 0);
  9374. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9375. }
  9376. };
  9377. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9378. if (mimeType === void 0) { mimeType = "image/png"; }
  9379. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9380. if (successCallback) {
  9381. successCallback(base64Image);
  9382. }
  9383. else {
  9384. // We need HTMLCanvasElement.toBlob for HD screenshots
  9385. if (!screenshotCanvas.toBlob) {
  9386. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9387. screenshotCanvas.toBlob = function (callback, type, quality) {
  9388. var _this = this;
  9389. setTimeout(function () {
  9390. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9391. for (var i = 0; i < len; i++) {
  9392. arr[i] = binStr.charCodeAt(i);
  9393. }
  9394. callback(new Blob([arr], { type: type || 'image/png' }));
  9395. });
  9396. };
  9397. }
  9398. screenshotCanvas.toBlob(function (blob) {
  9399. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9400. if (("download" in document.createElement("a"))) {
  9401. if (!fileName) {
  9402. var date = new Date();
  9403. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9404. fileName = "screenshot_" + stringDate + ".png";
  9405. }
  9406. Tools.Download(blob, fileName);
  9407. }
  9408. else {
  9409. var url = URL.createObjectURL(blob);
  9410. var newWindow = window.open("");
  9411. if (!newWindow)
  9412. return;
  9413. var img = newWindow.document.createElement("img");
  9414. img.onload = function () {
  9415. // no longer need to read the blob so it's revoked
  9416. URL.revokeObjectURL(url);
  9417. };
  9418. img.src = url;
  9419. newWindow.document.body.appendChild(img);
  9420. }
  9421. });
  9422. }
  9423. };
  9424. /**
  9425. * Downloads a blob in the browser
  9426. * @param blob defines the blob to download
  9427. * @param fileName defines the name of the downloaded file
  9428. */
  9429. Tools.Download = function (blob, fileName) {
  9430. var url = window.URL.createObjectURL(blob);
  9431. var a = document.createElement("a");
  9432. document.body.appendChild(a);
  9433. a.style.display = "none";
  9434. a.href = url;
  9435. a.download = fileName;
  9436. a.addEventListener("click", function () {
  9437. if (a.parentElement) {
  9438. a.parentElement.removeChild(a);
  9439. }
  9440. });
  9441. a.click();
  9442. window.URL.revokeObjectURL(url);
  9443. };
  9444. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9445. if (mimeType === void 0) { mimeType = "image/png"; }
  9446. var width;
  9447. var height;
  9448. // If a precision value is specified
  9449. if (size.precision) {
  9450. width = Math.round(engine.getRenderWidth() * size.precision);
  9451. height = Math.round(width / engine.getAspectRatio(camera));
  9452. }
  9453. else if (size.width && size.height) {
  9454. width = size.width;
  9455. height = size.height;
  9456. }
  9457. //If passing only width, computing height to keep display canvas ratio.
  9458. else if (size.width && !size.height) {
  9459. width = size.width;
  9460. height = Math.round(width / engine.getAspectRatio(camera));
  9461. }
  9462. //If passing only height, computing width to keep display canvas ratio.
  9463. else if (size.height && !size.width) {
  9464. height = size.height;
  9465. width = Math.round(height * engine.getAspectRatio(camera));
  9466. }
  9467. //Assuming here that "size" parameter is a number
  9468. else if (!isNaN(size)) {
  9469. height = size;
  9470. width = size;
  9471. }
  9472. else {
  9473. Tools.Error("Invalid 'size' parameter !");
  9474. return;
  9475. }
  9476. if (!screenshotCanvas) {
  9477. screenshotCanvas = document.createElement('canvas');
  9478. }
  9479. screenshotCanvas.width = width;
  9480. screenshotCanvas.height = height;
  9481. var renderContext = screenshotCanvas.getContext("2d");
  9482. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9483. var newWidth = width;
  9484. var newHeight = newWidth / ratio;
  9485. if (newHeight > height) {
  9486. newHeight = height;
  9487. newWidth = newHeight * ratio;
  9488. }
  9489. var offsetX = Math.max(0, width - newWidth) / 2;
  9490. var offsetY = Math.max(0, height - newHeight) / 2;
  9491. var renderingCanvas = engine.getRenderingCanvas();
  9492. if (renderContext && renderingCanvas) {
  9493. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9494. }
  9495. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9496. };
  9497. /**
  9498. * Generates an image screenshot from the specified camera.
  9499. *
  9500. * @param engine The engine to use for rendering
  9501. * @param camera The camera to use for rendering
  9502. * @param size This parameter can be set to a single number or to an object with the
  9503. * following (optional) properties: precision, width, height. If a single number is passed,
  9504. * it will be used for both width and height. If an object is passed, the screenshot size
  9505. * will be derived from the parameters. The precision property is a multiplier allowing
  9506. * rendering at a higher or lower resolution.
  9507. * @param successCallback The callback receives a single parameter which contains the
  9508. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9509. * src parameter of an <img> to display it.
  9510. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9511. * Check your browser for supported MIME types.
  9512. * @param samples Texture samples (default: 1)
  9513. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9514. * @param fileName A name for for the downloaded file.
  9515. * @constructor
  9516. */
  9517. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9518. if (mimeType === void 0) { mimeType = "image/png"; }
  9519. if (samples === void 0) { samples = 1; }
  9520. if (antialiasing === void 0) { antialiasing = false; }
  9521. var width;
  9522. var height;
  9523. //If a precision value is specified
  9524. if (size.precision) {
  9525. width = Math.round(engine.getRenderWidth() * size.precision);
  9526. height = Math.round(width / engine.getAspectRatio(camera));
  9527. size = { width: width, height: height };
  9528. }
  9529. else if (size.width && size.height) {
  9530. width = size.width;
  9531. height = size.height;
  9532. }
  9533. //If passing only width, computing height to keep display canvas ratio.
  9534. else if (size.width && !size.height) {
  9535. width = size.width;
  9536. height = Math.round(width / engine.getAspectRatio(camera));
  9537. size = { width: width, height: height };
  9538. }
  9539. //If passing only height, computing width to keep display canvas ratio.
  9540. else if (size.height && !size.width) {
  9541. height = size.height;
  9542. width = Math.round(height * engine.getAspectRatio(camera));
  9543. size = { width: width, height: height };
  9544. }
  9545. //Assuming here that "size" parameter is a number
  9546. else if (!isNaN(size)) {
  9547. height = size;
  9548. width = size;
  9549. }
  9550. else {
  9551. Tools.Error("Invalid 'size' parameter !");
  9552. return;
  9553. }
  9554. var scene = camera.getScene();
  9555. var previousCamera = null;
  9556. if (scene.activeCamera !== camera) {
  9557. previousCamera = scene.activeCamera;
  9558. scene.activeCamera = camera;
  9559. }
  9560. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9561. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9562. texture.renderList = null;
  9563. texture.samples = samples;
  9564. if (antialiasing) {
  9565. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9566. }
  9567. texture.onAfterRenderObservable.add(function () {
  9568. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9569. });
  9570. scene.incrementRenderId();
  9571. scene.resetCachedMaterial();
  9572. texture.render(true);
  9573. texture.dispose();
  9574. if (previousCamera) {
  9575. scene.activeCamera = previousCamera;
  9576. }
  9577. camera.getProjectionMatrix(true); // Force cache refresh;
  9578. };
  9579. // XHR response validator for local file scenario
  9580. Tools.ValidateXHRData = function (xhr, dataType) {
  9581. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9582. if (dataType === void 0) { dataType = 7; }
  9583. try {
  9584. if (dataType & 1) {
  9585. if (xhr.responseText && xhr.responseText.length > 0) {
  9586. return true;
  9587. }
  9588. else if (dataType === 1) {
  9589. return false;
  9590. }
  9591. }
  9592. if (dataType & 2) {
  9593. // Check header width and height since there is no "TGA" magic number
  9594. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9595. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9596. return true;
  9597. }
  9598. else if (dataType === 2) {
  9599. return false;
  9600. }
  9601. }
  9602. if (dataType & 4) {
  9603. // Check for the "DDS" magic number
  9604. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9605. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9606. return true;
  9607. }
  9608. else {
  9609. return false;
  9610. }
  9611. }
  9612. }
  9613. catch (e) {
  9614. // Global protection
  9615. }
  9616. return false;
  9617. };
  9618. /**
  9619. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9620. * Be aware Math.random() could cause collisions, but:
  9621. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9622. */
  9623. Tools.RandomId = function () {
  9624. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9625. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9626. return v.toString(16);
  9627. });
  9628. };
  9629. /**
  9630. * Test if the given uri is a base64 string.
  9631. * @param uri The uri to test
  9632. * @return True if the uri is a base64 string or false otherwise.
  9633. */
  9634. Tools.IsBase64 = function (uri) {
  9635. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9636. };
  9637. /**
  9638. * Decode the given base64 uri.
  9639. * @param uri The uri to decode
  9640. * @return The decoded base64 data.
  9641. */
  9642. Tools.DecodeBase64 = function (uri) {
  9643. var decodedString = atob(uri.split(",")[1]);
  9644. var bufferLength = decodedString.length;
  9645. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9646. for (var i = 0; i < bufferLength; i++) {
  9647. bufferView[i] = decodedString.charCodeAt(i);
  9648. }
  9649. return bufferView.buffer;
  9650. };
  9651. Object.defineProperty(Tools, "NoneLogLevel", {
  9652. get: function () {
  9653. return Tools._NoneLogLevel;
  9654. },
  9655. enumerable: true,
  9656. configurable: true
  9657. });
  9658. Object.defineProperty(Tools, "MessageLogLevel", {
  9659. get: function () {
  9660. return Tools._MessageLogLevel;
  9661. },
  9662. enumerable: true,
  9663. configurable: true
  9664. });
  9665. Object.defineProperty(Tools, "WarningLogLevel", {
  9666. get: function () {
  9667. return Tools._WarningLogLevel;
  9668. },
  9669. enumerable: true,
  9670. configurable: true
  9671. });
  9672. Object.defineProperty(Tools, "ErrorLogLevel", {
  9673. get: function () {
  9674. return Tools._ErrorLogLevel;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Object.defineProperty(Tools, "AllLogLevel", {
  9680. get: function () {
  9681. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9682. },
  9683. enumerable: true,
  9684. configurable: true
  9685. });
  9686. Tools._AddLogEntry = function (entry) {
  9687. Tools._LogCache = entry + Tools._LogCache;
  9688. if (Tools.OnNewCacheEntry) {
  9689. Tools.OnNewCacheEntry(entry);
  9690. }
  9691. };
  9692. Tools._FormatMessage = function (message) {
  9693. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9694. var date = new Date();
  9695. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9696. };
  9697. Tools._LogDisabled = function (message) {
  9698. // nothing to do
  9699. };
  9700. Tools._LogEnabled = function (message) {
  9701. var formattedMessage = Tools._FormatMessage(message);
  9702. console.log("BJS - " + formattedMessage);
  9703. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9704. Tools._AddLogEntry(entry);
  9705. };
  9706. Tools._WarnDisabled = function (message) {
  9707. // nothing to do
  9708. };
  9709. Tools._WarnEnabled = function (message) {
  9710. var formattedMessage = Tools._FormatMessage(message);
  9711. console.warn("BJS - " + formattedMessage);
  9712. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9713. Tools._AddLogEntry(entry);
  9714. };
  9715. Tools._ErrorDisabled = function (message) {
  9716. // nothing to do
  9717. };
  9718. Tools._ErrorEnabled = function (message) {
  9719. Tools.errorsCount++;
  9720. var formattedMessage = Tools._FormatMessage(message);
  9721. console.error("BJS - " + formattedMessage);
  9722. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9723. Tools._AddLogEntry(entry);
  9724. };
  9725. Object.defineProperty(Tools, "LogCache", {
  9726. get: function () {
  9727. return Tools._LogCache;
  9728. },
  9729. enumerable: true,
  9730. configurable: true
  9731. });
  9732. Tools.ClearLogCache = function () {
  9733. Tools._LogCache = "";
  9734. Tools.errorsCount = 0;
  9735. };
  9736. Object.defineProperty(Tools, "LogLevels", {
  9737. set: function (level) {
  9738. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9739. Tools.Log = Tools._LogEnabled;
  9740. }
  9741. else {
  9742. Tools.Log = Tools._LogDisabled;
  9743. }
  9744. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9745. Tools.Warn = Tools._WarnEnabled;
  9746. }
  9747. else {
  9748. Tools.Warn = Tools._WarnDisabled;
  9749. }
  9750. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9751. Tools.Error = Tools._ErrorEnabled;
  9752. }
  9753. else {
  9754. Tools.Error = Tools._ErrorDisabled;
  9755. }
  9756. },
  9757. enumerable: true,
  9758. configurable: true
  9759. });
  9760. Tools.IsWindowObjectExist = function () {
  9761. return (typeof window) !== "undefined";
  9762. };
  9763. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9764. get: function () {
  9765. return Tools._PerformanceNoneLogLevel;
  9766. },
  9767. enumerable: true,
  9768. configurable: true
  9769. });
  9770. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9771. get: function () {
  9772. return Tools._PerformanceUserMarkLogLevel;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9778. get: function () {
  9779. return Tools._PerformanceConsoleLogLevel;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9785. set: function (level) {
  9786. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9787. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9788. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9789. return;
  9790. }
  9791. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9792. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9793. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9794. return;
  9795. }
  9796. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9797. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9798. },
  9799. enumerable: true,
  9800. configurable: true
  9801. });
  9802. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9803. };
  9804. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9805. };
  9806. Tools._StartUserMark = function (counterName, condition) {
  9807. if (condition === void 0) { condition = true; }
  9808. if (!Tools._performance) {
  9809. if (!Tools.IsWindowObjectExist()) {
  9810. return;
  9811. }
  9812. Tools._performance = window.performance;
  9813. }
  9814. if (!condition || !Tools._performance.mark) {
  9815. return;
  9816. }
  9817. Tools._performance.mark(counterName + "-Begin");
  9818. };
  9819. Tools._EndUserMark = function (counterName, condition) {
  9820. if (condition === void 0) { condition = true; }
  9821. if (!condition || !Tools._performance.mark) {
  9822. return;
  9823. }
  9824. Tools._performance.mark(counterName + "-End");
  9825. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9826. };
  9827. Tools._StartPerformanceConsole = function (counterName, condition) {
  9828. if (condition === void 0) { condition = true; }
  9829. if (!condition) {
  9830. return;
  9831. }
  9832. Tools._StartUserMark(counterName, condition);
  9833. if (console.time) {
  9834. console.time(counterName);
  9835. }
  9836. };
  9837. Tools._EndPerformanceConsole = function (counterName, condition) {
  9838. if (condition === void 0) { condition = true; }
  9839. if (!condition) {
  9840. return;
  9841. }
  9842. Tools._EndUserMark(counterName, condition);
  9843. if (console.time) {
  9844. console.timeEnd(counterName);
  9845. }
  9846. };
  9847. Object.defineProperty(Tools, "Now", {
  9848. get: function () {
  9849. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9850. return window.performance.now();
  9851. }
  9852. return Date.now();
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. /**
  9858. * This method will return the name of the class used to create the instance of the given object.
  9859. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9860. * @param object the object to get the class name from
  9861. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9862. */
  9863. Tools.GetClassName = function (object, isType) {
  9864. if (isType === void 0) { isType = false; }
  9865. var name = null;
  9866. if (!isType && object.getClassName) {
  9867. name = object.getClassName();
  9868. }
  9869. else {
  9870. if (object instanceof Object) {
  9871. var classObj = isType ? object : Object.getPrototypeOf(object);
  9872. name = classObj.constructor["__bjsclassName__"];
  9873. }
  9874. if (!name) {
  9875. name = typeof object;
  9876. }
  9877. }
  9878. return name;
  9879. };
  9880. Tools.First = function (array, predicate) {
  9881. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9882. var el = array_1[_i];
  9883. if (predicate(el)) {
  9884. return el;
  9885. }
  9886. }
  9887. return null;
  9888. };
  9889. /**
  9890. * This method will return the name of the full name of the class, including its owning module (if any).
  9891. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9892. * @param object the object to get the class name from
  9893. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9894. */
  9895. Tools.getFullClassName = function (object, isType) {
  9896. if (isType === void 0) { isType = false; }
  9897. var className = null;
  9898. var moduleName = null;
  9899. if (!isType && object.getClassName) {
  9900. className = object.getClassName();
  9901. }
  9902. else {
  9903. if (object instanceof Object) {
  9904. var classObj = isType ? object : Object.getPrototypeOf(object);
  9905. className = classObj.constructor["__bjsclassName__"];
  9906. moduleName = classObj.constructor["__bjsmoduleName__"];
  9907. }
  9908. if (!className) {
  9909. className = typeof object;
  9910. }
  9911. }
  9912. if (!className) {
  9913. return null;
  9914. }
  9915. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9916. };
  9917. /**
  9918. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9919. * @param array
  9920. */
  9921. Tools.arrayOrStringFeeder = function (array) {
  9922. return function (index) {
  9923. if (index >= array.length) {
  9924. return null;
  9925. }
  9926. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9927. if (val && val.getHashCode) {
  9928. val = val.getHashCode();
  9929. }
  9930. if (typeof val === "string") {
  9931. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9932. }
  9933. return val;
  9934. };
  9935. };
  9936. /**
  9937. * Compute the hashCode of a stream of number
  9938. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9939. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9940. * @return the hash code computed
  9941. */
  9942. Tools.hashCodeFromStream = function (feeder) {
  9943. // Based from here: http://stackoverflow.com/a/7616484/802124
  9944. var hash = 0;
  9945. var index = 0;
  9946. var chr = feeder(index++);
  9947. while (chr != null) {
  9948. hash = ((hash << 5) - hash) + chr;
  9949. hash |= 0; // Convert to 32bit integer
  9950. chr = feeder(index++);
  9951. }
  9952. return hash;
  9953. };
  9954. /**
  9955. * Returns a promise that resolves after the given amount of time.
  9956. * @param delay Number of milliseconds to delay
  9957. * @returns Promise that resolves after the given amount of time
  9958. */
  9959. Tools.DelayAsync = function (delay) {
  9960. return new Promise(function (resolve) {
  9961. setTimeout(function () {
  9962. resolve();
  9963. }, delay);
  9964. });
  9965. };
  9966. Tools.BaseUrl = "";
  9967. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9968. /**
  9969. * Default behaviour for cors in the application.
  9970. * It can be a string if the expected behavior is identical in the entire app.
  9971. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9972. */
  9973. Tools.CorsBehavior = "anonymous";
  9974. Tools.UseFallbackTexture = true;
  9975. /**
  9976. * Use this object to register external classes like custom textures or material
  9977. * to allow the laoders to instantiate them
  9978. */
  9979. Tools.RegisteredExternalClasses = {};
  9980. // Used in case of a texture loading problem
  9981. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/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";
  9982. Tools._tmpFloatArray = new Float32Array(1);
  9983. Tools.PreprocessUrl = function (url) {
  9984. return url;
  9985. };
  9986. // Logs
  9987. Tools._NoneLogLevel = 0;
  9988. Tools._MessageLogLevel = 1;
  9989. Tools._WarningLogLevel = 2;
  9990. Tools._ErrorLogLevel = 4;
  9991. Tools._LogCache = "";
  9992. Tools.errorsCount = 0;
  9993. Tools.Log = Tools._LogEnabled;
  9994. Tools.Warn = Tools._WarnEnabled;
  9995. Tools.Error = Tools._ErrorEnabled;
  9996. // Performances
  9997. Tools._PerformanceNoneLogLevel = 0;
  9998. Tools._PerformanceUserMarkLogLevel = 1;
  9999. Tools._PerformanceConsoleLogLevel = 2;
  10000. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10001. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10002. return Tools;
  10003. }());
  10004. BABYLON.Tools = Tools;
  10005. /**
  10006. * This class is used to track a performance counter which is number based.
  10007. * The user has access to many properties which give statistics of different nature
  10008. *
  10009. * The implementer can track two kinds of Performance Counter: time and count
  10010. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  10011. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  10012. */
  10013. var PerfCounter = /** @class */ (function () {
  10014. function PerfCounter() {
  10015. this._startMonitoringTime = 0;
  10016. this._min = 0;
  10017. this._max = 0;
  10018. this._average = 0;
  10019. this._lastSecAverage = 0;
  10020. this._current = 0;
  10021. this._totalValueCount = 0;
  10022. this._totalAccumulated = 0;
  10023. this._lastSecAccumulated = 0;
  10024. this._lastSecTime = 0;
  10025. this._lastSecValueCount = 0;
  10026. }
  10027. Object.defineProperty(PerfCounter.prototype, "min", {
  10028. /**
  10029. * Returns the smallest value ever
  10030. */
  10031. get: function () {
  10032. return this._min;
  10033. },
  10034. enumerable: true,
  10035. configurable: true
  10036. });
  10037. Object.defineProperty(PerfCounter.prototype, "max", {
  10038. /**
  10039. * Returns the biggest value ever
  10040. */
  10041. get: function () {
  10042. return this._max;
  10043. },
  10044. enumerable: true,
  10045. configurable: true
  10046. });
  10047. Object.defineProperty(PerfCounter.prototype, "average", {
  10048. /**
  10049. * Returns the average value since the performance counter is running
  10050. */
  10051. get: function () {
  10052. return this._average;
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10058. /**
  10059. * Returns the average value of the last second the counter was monitored
  10060. */
  10061. get: function () {
  10062. return this._lastSecAverage;
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(PerfCounter.prototype, "current", {
  10068. /**
  10069. * Returns the current value
  10070. */
  10071. get: function () {
  10072. return this._current;
  10073. },
  10074. enumerable: true,
  10075. configurable: true
  10076. });
  10077. Object.defineProperty(PerfCounter.prototype, "total", {
  10078. get: function () {
  10079. return this._totalAccumulated;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. Object.defineProperty(PerfCounter.prototype, "count", {
  10085. get: function () {
  10086. return this._totalValueCount;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. /**
  10092. * Call this method to start monitoring a new frame.
  10093. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  10094. */
  10095. PerfCounter.prototype.fetchNewFrame = function () {
  10096. this._totalValueCount++;
  10097. this._current = 0;
  10098. this._lastSecValueCount++;
  10099. };
  10100. /**
  10101. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10102. * @param newCount the count value to add to the monitored count
  10103. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  10104. */
  10105. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10106. if (!PerfCounter.Enabled) {
  10107. return;
  10108. }
  10109. this._current += newCount;
  10110. if (fetchResult) {
  10111. this._fetchResult();
  10112. }
  10113. };
  10114. /**
  10115. * Start monitoring this performance counter
  10116. */
  10117. PerfCounter.prototype.beginMonitoring = function () {
  10118. if (!PerfCounter.Enabled) {
  10119. return;
  10120. }
  10121. this._startMonitoringTime = Tools.Now;
  10122. };
  10123. /**
  10124. * Compute the time lapsed since the previous beginMonitoring() call.
  10125. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  10126. */
  10127. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10128. if (newFrame === void 0) { newFrame = true; }
  10129. if (!PerfCounter.Enabled) {
  10130. return;
  10131. }
  10132. if (newFrame) {
  10133. this.fetchNewFrame();
  10134. }
  10135. var currentTime = Tools.Now;
  10136. this._current = currentTime - this._startMonitoringTime;
  10137. if (newFrame) {
  10138. this._fetchResult();
  10139. }
  10140. };
  10141. PerfCounter.prototype._fetchResult = function () {
  10142. this._totalAccumulated += this._current;
  10143. this._lastSecAccumulated += this._current;
  10144. // Min/Max update
  10145. this._min = Math.min(this._min, this._current);
  10146. this._max = Math.max(this._max, this._current);
  10147. this._average = this._totalAccumulated / this._totalValueCount;
  10148. // Reset last sec?
  10149. var now = Tools.Now;
  10150. if ((now - this._lastSecTime) > 1000) {
  10151. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10152. this._lastSecTime = now;
  10153. this._lastSecAccumulated = 0;
  10154. this._lastSecValueCount = 0;
  10155. }
  10156. };
  10157. PerfCounter.Enabled = true;
  10158. return PerfCounter;
  10159. }());
  10160. BABYLON.PerfCounter = PerfCounter;
  10161. /**
  10162. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10163. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10164. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10165. * @param name The name of the class, case should be preserved
  10166. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10167. */
  10168. function className(name, module) {
  10169. return function (target) {
  10170. target["__bjsclassName__"] = name;
  10171. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10172. };
  10173. }
  10174. BABYLON.className = className;
  10175. /**
  10176. * An implementation of a loop for asynchronous functions.
  10177. */
  10178. var AsyncLoop = /** @class */ (function () {
  10179. /**
  10180. * Constroctor.
  10181. * @param iterations the number of iterations.
  10182. * @param _fn the function to run each iteration
  10183. * @param _successCallback the callback that will be called upon succesful execution
  10184. * @param offset starting offset.
  10185. */
  10186. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10187. if (offset === void 0) { offset = 0; }
  10188. this.iterations = iterations;
  10189. this._fn = _fn;
  10190. this._successCallback = _successCallback;
  10191. this.index = offset - 1;
  10192. this._done = false;
  10193. }
  10194. /**
  10195. * Execute the next iteration. Must be called after the last iteration was finished.
  10196. */
  10197. AsyncLoop.prototype.executeNext = function () {
  10198. if (!this._done) {
  10199. if (this.index + 1 < this.iterations) {
  10200. ++this.index;
  10201. this._fn(this);
  10202. }
  10203. else {
  10204. this.breakLoop();
  10205. }
  10206. }
  10207. };
  10208. /**
  10209. * Break the loop and run the success callback.
  10210. */
  10211. AsyncLoop.prototype.breakLoop = function () {
  10212. this._done = true;
  10213. this._successCallback();
  10214. };
  10215. /**
  10216. * Helper function
  10217. */
  10218. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10219. if (offset === void 0) { offset = 0; }
  10220. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10221. loop.executeNext();
  10222. return loop;
  10223. };
  10224. /**
  10225. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10226. * @param iterations total number of iterations
  10227. * @param syncedIterations number of synchronous iterations in each async iteration.
  10228. * @param fn the function to call each iteration.
  10229. * @param callback a success call back that will be called when iterating stops.
  10230. * @param breakFunction a break condition (optional)
  10231. * @param timeout timeout settings for the setTimeout function. default - 0.
  10232. * @constructor
  10233. */
  10234. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10235. if (timeout === void 0) { timeout = 0; }
  10236. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10237. if (breakFunction && breakFunction())
  10238. loop.breakLoop();
  10239. else {
  10240. setTimeout(function () {
  10241. for (var i = 0; i < syncedIterations; ++i) {
  10242. var iteration = (loop.index * syncedIterations) + i;
  10243. if (iteration >= iterations)
  10244. break;
  10245. fn(iteration);
  10246. if (breakFunction && breakFunction()) {
  10247. loop.breakLoop();
  10248. break;
  10249. }
  10250. }
  10251. loop.executeNext();
  10252. }, timeout);
  10253. }
  10254. }, callback);
  10255. };
  10256. return AsyncLoop;
  10257. }());
  10258. BABYLON.AsyncLoop = AsyncLoop;
  10259. })(BABYLON || (BABYLON = {}));
  10260. //# sourceMappingURL=babylon.tools.js.map
  10261. var BABYLON;
  10262. (function (BABYLON) {
  10263. var PromiseStates;
  10264. (function (PromiseStates) {
  10265. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10266. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10267. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10268. })(PromiseStates || (PromiseStates = {}));
  10269. var FulFillmentAgregator = /** @class */ (function () {
  10270. function FulFillmentAgregator() {
  10271. this.count = 0;
  10272. this.target = 0;
  10273. this.results = [];
  10274. }
  10275. return FulFillmentAgregator;
  10276. }());
  10277. var InternalPromise = /** @class */ (function () {
  10278. function InternalPromise(resolver) {
  10279. var _this = this;
  10280. this._state = PromiseStates.Pending;
  10281. this._children = new Array();
  10282. this._rejectWasConsumed = false;
  10283. if (!resolver) {
  10284. return;
  10285. }
  10286. try {
  10287. resolver(function (value) {
  10288. _this._resolve(value);
  10289. }, function (reason) {
  10290. _this._reject(reason);
  10291. });
  10292. }
  10293. catch (e) {
  10294. this._reject(e);
  10295. }
  10296. }
  10297. Object.defineProperty(InternalPromise.prototype, "_result", {
  10298. get: function () {
  10299. return this._resultValue;
  10300. },
  10301. set: function (value) {
  10302. this._resultValue = value;
  10303. if (this._parent && this._parent._result === undefined) {
  10304. this._parent._result = value;
  10305. }
  10306. },
  10307. enumerable: true,
  10308. configurable: true
  10309. });
  10310. InternalPromise.prototype.catch = function (onRejected) {
  10311. return this.then(undefined, onRejected);
  10312. };
  10313. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10314. var _this = this;
  10315. var newPromise = new InternalPromise();
  10316. newPromise._onFulfilled = onFulfilled;
  10317. newPromise._onRejected = onRejected;
  10318. // Composition
  10319. this._children.push(newPromise);
  10320. newPromise._parent = this;
  10321. if (this._state !== PromiseStates.Pending) {
  10322. BABYLON.Tools.SetImmediate(function () {
  10323. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10324. var returnedValue = newPromise._resolve(_this._result);
  10325. if (returnedValue !== undefined && returnedValue !== null) {
  10326. if (returnedValue._state !== undefined) {
  10327. var returnedPromise = returnedValue;
  10328. newPromise._children.push(returnedPromise);
  10329. returnedPromise._parent = newPromise;
  10330. newPromise = returnedPromise;
  10331. }
  10332. else {
  10333. newPromise._result = returnedValue;
  10334. }
  10335. }
  10336. }
  10337. else {
  10338. newPromise._reject(_this._reason);
  10339. }
  10340. });
  10341. }
  10342. return newPromise;
  10343. };
  10344. InternalPromise.prototype._moveChildren = function (children) {
  10345. var _this = this;
  10346. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10347. this._children.forEach(function (child) {
  10348. child._parent = _this;
  10349. });
  10350. if (this._state === PromiseStates.Fulfilled) {
  10351. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10352. var child = _b[_i];
  10353. child._resolve(this._result);
  10354. }
  10355. }
  10356. else if (this._state === PromiseStates.Rejected) {
  10357. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10358. var child = _d[_c];
  10359. child._reject(this._reason);
  10360. }
  10361. }
  10362. var _a;
  10363. };
  10364. InternalPromise.prototype._resolve = function (value) {
  10365. try {
  10366. this._state = PromiseStates.Fulfilled;
  10367. var returnedValue = null;
  10368. if (this._onFulfilled) {
  10369. returnedValue = this._onFulfilled(value);
  10370. }
  10371. if (returnedValue !== undefined && returnedValue !== null) {
  10372. if (returnedValue._state !== undefined) {
  10373. // Transmit children
  10374. var returnedPromise = returnedValue;
  10375. returnedPromise._parent = this;
  10376. returnedPromise._moveChildren(this._children);
  10377. value = returnedPromise._result;
  10378. }
  10379. else {
  10380. value = returnedValue;
  10381. }
  10382. }
  10383. this._result = value;
  10384. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10385. var child = _a[_i];
  10386. child._resolve(value);
  10387. }
  10388. this._children.length = 0;
  10389. delete this._onFulfilled;
  10390. delete this._onRejected;
  10391. }
  10392. catch (e) {
  10393. this._reject(e, true);
  10394. }
  10395. };
  10396. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10397. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10398. this._state = PromiseStates.Rejected;
  10399. this._reason = reason;
  10400. if (this._onRejected && !onLocalThrow) {
  10401. try {
  10402. this._onRejected(reason);
  10403. this._rejectWasConsumed = true;
  10404. }
  10405. catch (e) {
  10406. reason = e;
  10407. }
  10408. }
  10409. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10410. var child = _a[_i];
  10411. if (this._rejectWasConsumed) {
  10412. child._resolve(null);
  10413. }
  10414. else {
  10415. child._reject(reason);
  10416. }
  10417. }
  10418. this._children.length = 0;
  10419. delete this._onFulfilled;
  10420. delete this._onRejected;
  10421. };
  10422. InternalPromise.resolve = function (value) {
  10423. var newPromise = new InternalPromise();
  10424. newPromise._resolve(value);
  10425. return newPromise;
  10426. };
  10427. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10428. promise.then(function (value) {
  10429. agregator.results[index] = value;
  10430. agregator.count++;
  10431. if (agregator.count === agregator.target) {
  10432. agregator.rootPromise._resolve(agregator.results);
  10433. }
  10434. return null;
  10435. }, function (reason) {
  10436. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10437. agregator.rootPromise._reject(reason);
  10438. }
  10439. });
  10440. };
  10441. InternalPromise.all = function (promises) {
  10442. var newPromise = new InternalPromise();
  10443. var agregator = new FulFillmentAgregator();
  10444. agregator.target = promises.length;
  10445. agregator.rootPromise = newPromise;
  10446. if (promises.length) {
  10447. for (var index = 0; index < promises.length; index++) {
  10448. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10449. }
  10450. }
  10451. else {
  10452. newPromise._resolve([]);
  10453. }
  10454. return newPromise;
  10455. };
  10456. InternalPromise.race = function (promises) {
  10457. var newPromise = new InternalPromise();
  10458. if (promises.length) {
  10459. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10460. var promise = promises_1[_i];
  10461. promise.then(function (value) {
  10462. if (newPromise) {
  10463. newPromise._resolve(value);
  10464. newPromise = null;
  10465. }
  10466. return null;
  10467. }, function (reason) {
  10468. if (newPromise) {
  10469. newPromise._reject(reason);
  10470. newPromise = null;
  10471. }
  10472. });
  10473. }
  10474. }
  10475. return newPromise;
  10476. };
  10477. return InternalPromise;
  10478. }());
  10479. /**
  10480. * Helper class that provides a small promise polyfill
  10481. */
  10482. var PromisePolyfill = /** @class */ (function () {
  10483. function PromisePolyfill() {
  10484. }
  10485. /**
  10486. * Static function used to check if the polyfill is required
  10487. * If this is the case then the function will inject the polyfill to window.Promise
  10488. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10489. */
  10490. PromisePolyfill.Apply = function (force) {
  10491. if (force === void 0) { force = false; }
  10492. if (force || typeof Promise === 'undefined') {
  10493. var root = window;
  10494. root.Promise = InternalPromise;
  10495. }
  10496. };
  10497. return PromisePolyfill;
  10498. }());
  10499. BABYLON.PromisePolyfill = PromisePolyfill;
  10500. })(BABYLON || (BABYLON = {}));
  10501. //# sourceMappingURL=babylon.promise.js.map
  10502. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10503. var BABYLON;
  10504. (function (BABYLON) {
  10505. /**
  10506. * Helper class to push actions to a pool of workers.
  10507. */
  10508. var WorkerPool = /** @class */ (function () {
  10509. /**
  10510. * Constructor
  10511. * @param workers Array of workers to use for actions
  10512. */
  10513. function WorkerPool(workers) {
  10514. this._pendingActions = new Array();
  10515. this._workerInfos = workers.map(function (worker) { return ({
  10516. worker: worker,
  10517. active: false
  10518. }); });
  10519. }
  10520. /**
  10521. * Terminates all workers and clears any pending actions.
  10522. */
  10523. WorkerPool.prototype.dispose = function () {
  10524. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10525. var workerInfo = _a[_i];
  10526. workerInfo.worker.terminate();
  10527. }
  10528. delete this._workerInfos;
  10529. delete this._pendingActions;
  10530. };
  10531. /**
  10532. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10533. * pended until a worker has completed its action.
  10534. * @param action The action to perform. Call onComplete when the action is complete.
  10535. */
  10536. WorkerPool.prototype.push = function (action) {
  10537. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10538. var workerInfo = _a[_i];
  10539. if (!workerInfo.active) {
  10540. this._execute(workerInfo, action);
  10541. return;
  10542. }
  10543. }
  10544. this._pendingActions.push(action);
  10545. };
  10546. WorkerPool.prototype._execute = function (workerInfo, action) {
  10547. var _this = this;
  10548. workerInfo.active = true;
  10549. action(workerInfo.worker, function () {
  10550. workerInfo.active = false;
  10551. var nextAction = _this._pendingActions.shift();
  10552. if (nextAction) {
  10553. _this._execute(workerInfo, nextAction);
  10554. }
  10555. });
  10556. };
  10557. return WorkerPool;
  10558. }());
  10559. BABYLON.WorkerPool = WorkerPool;
  10560. })(BABYLON || (BABYLON = {}));
  10561. //# sourceMappingURL=babylon.workerPool.js.map
  10562. var BABYLON;
  10563. (function (BABYLON) {
  10564. /**
  10565. * @hidden
  10566. **/
  10567. var _AlphaState = /** @class */ (function () {
  10568. /**
  10569. * Initializes the state.
  10570. */
  10571. function _AlphaState() {
  10572. this._isAlphaBlendDirty = false;
  10573. this._isBlendFunctionParametersDirty = false;
  10574. this._isBlendEquationParametersDirty = false;
  10575. this._isBlendConstantsDirty = false;
  10576. this._alphaBlend = false;
  10577. this._blendFunctionParameters = new Array(4);
  10578. this._blendEquationParameters = new Array(2);
  10579. this._blendConstants = new Array(4);
  10580. this.reset();
  10581. }
  10582. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10583. get: function () {
  10584. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10585. },
  10586. enumerable: true,
  10587. configurable: true
  10588. });
  10589. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10590. get: function () {
  10591. return this._alphaBlend;
  10592. },
  10593. set: function (value) {
  10594. if (this._alphaBlend === value) {
  10595. return;
  10596. }
  10597. this._alphaBlend = value;
  10598. this._isAlphaBlendDirty = true;
  10599. },
  10600. enumerable: true,
  10601. configurable: true
  10602. });
  10603. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10604. if (this._blendConstants[0] === r &&
  10605. this._blendConstants[1] === g &&
  10606. this._blendConstants[2] === b &&
  10607. this._blendConstants[3] === a) {
  10608. return;
  10609. }
  10610. this._blendConstants[0] = r;
  10611. this._blendConstants[1] = g;
  10612. this._blendConstants[2] = b;
  10613. this._blendConstants[3] = a;
  10614. this._isBlendConstantsDirty = true;
  10615. };
  10616. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10617. if (this._blendFunctionParameters[0] === value0 &&
  10618. this._blendFunctionParameters[1] === value1 &&
  10619. this._blendFunctionParameters[2] === value2 &&
  10620. this._blendFunctionParameters[3] === value3) {
  10621. return;
  10622. }
  10623. this._blendFunctionParameters[0] = value0;
  10624. this._blendFunctionParameters[1] = value1;
  10625. this._blendFunctionParameters[2] = value2;
  10626. this._blendFunctionParameters[3] = value3;
  10627. this._isBlendFunctionParametersDirty = true;
  10628. };
  10629. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10630. if (this._blendEquationParameters[0] === rgb &&
  10631. this._blendEquationParameters[1] === alpha) {
  10632. return;
  10633. }
  10634. this._blendEquationParameters[0] = rgb;
  10635. this._blendEquationParameters[1] = alpha;
  10636. this._isBlendEquationParametersDirty = true;
  10637. };
  10638. _AlphaState.prototype.reset = function () {
  10639. this._alphaBlend = false;
  10640. this._blendFunctionParameters[0] = null;
  10641. this._blendFunctionParameters[1] = null;
  10642. this._blendFunctionParameters[2] = null;
  10643. this._blendFunctionParameters[3] = null;
  10644. this._blendEquationParameters[0] = null;
  10645. this._blendEquationParameters[1] = null;
  10646. this._blendConstants[0] = null;
  10647. this._blendConstants[1] = null;
  10648. this._blendConstants[2] = null;
  10649. this._blendConstants[3] = null;
  10650. this._isAlphaBlendDirty = true;
  10651. this._isBlendFunctionParametersDirty = false;
  10652. this._isBlendEquationParametersDirty = false;
  10653. this._isBlendConstantsDirty = false;
  10654. };
  10655. _AlphaState.prototype.apply = function (gl) {
  10656. if (!this.isDirty) {
  10657. return;
  10658. }
  10659. // Alpha blend
  10660. if (this._isAlphaBlendDirty) {
  10661. if (this._alphaBlend) {
  10662. gl.enable(gl.BLEND);
  10663. }
  10664. else {
  10665. gl.disable(gl.BLEND);
  10666. }
  10667. this._isAlphaBlendDirty = false;
  10668. }
  10669. // Alpha function
  10670. if (this._isBlendFunctionParametersDirty) {
  10671. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10672. this._isBlendFunctionParametersDirty = false;
  10673. }
  10674. // Alpha equation
  10675. if (this._isBlendEquationParametersDirty) {
  10676. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10677. this._isBlendEquationParametersDirty = false;
  10678. }
  10679. // Constants
  10680. if (this._isBlendConstantsDirty) {
  10681. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10682. this._isBlendConstantsDirty = false;
  10683. }
  10684. };
  10685. return _AlphaState;
  10686. }());
  10687. BABYLON._AlphaState = _AlphaState;
  10688. })(BABYLON || (BABYLON = {}));
  10689. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10690. var BABYLON;
  10691. (function (BABYLON) {
  10692. /**
  10693. * @hidden
  10694. **/
  10695. var _DepthCullingState = /** @class */ (function () {
  10696. /**
  10697. * Initializes the state.
  10698. */
  10699. function _DepthCullingState() {
  10700. this._isDepthTestDirty = false;
  10701. this._isDepthMaskDirty = false;
  10702. this._isDepthFuncDirty = false;
  10703. this._isCullFaceDirty = false;
  10704. this._isCullDirty = false;
  10705. this._isZOffsetDirty = false;
  10706. this._isFrontFaceDirty = false;
  10707. this.reset();
  10708. }
  10709. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10710. get: function () {
  10711. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10712. },
  10713. enumerable: true,
  10714. configurable: true
  10715. });
  10716. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10717. get: function () {
  10718. return this._zOffset;
  10719. },
  10720. set: function (value) {
  10721. if (this._zOffset === value) {
  10722. return;
  10723. }
  10724. this._zOffset = value;
  10725. this._isZOffsetDirty = true;
  10726. },
  10727. enumerable: true,
  10728. configurable: true
  10729. });
  10730. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10731. get: function () {
  10732. return this._cullFace;
  10733. },
  10734. set: function (value) {
  10735. if (this._cullFace === value) {
  10736. return;
  10737. }
  10738. this._cullFace = value;
  10739. this._isCullFaceDirty = true;
  10740. },
  10741. enumerable: true,
  10742. configurable: true
  10743. });
  10744. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10745. get: function () {
  10746. return this._cull;
  10747. },
  10748. set: function (value) {
  10749. if (this._cull === value) {
  10750. return;
  10751. }
  10752. this._cull = value;
  10753. this._isCullDirty = true;
  10754. },
  10755. enumerable: true,
  10756. configurable: true
  10757. });
  10758. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10759. get: function () {
  10760. return this._depthFunc;
  10761. },
  10762. set: function (value) {
  10763. if (this._depthFunc === value) {
  10764. return;
  10765. }
  10766. this._depthFunc = value;
  10767. this._isDepthFuncDirty = true;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10773. get: function () {
  10774. return this._depthMask;
  10775. },
  10776. set: function (value) {
  10777. if (this._depthMask === value) {
  10778. return;
  10779. }
  10780. this._depthMask = value;
  10781. this._isDepthMaskDirty = true;
  10782. },
  10783. enumerable: true,
  10784. configurable: true
  10785. });
  10786. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10787. get: function () {
  10788. return this._depthTest;
  10789. },
  10790. set: function (value) {
  10791. if (this._depthTest === value) {
  10792. return;
  10793. }
  10794. this._depthTest = value;
  10795. this._isDepthTestDirty = true;
  10796. },
  10797. enumerable: true,
  10798. configurable: true
  10799. });
  10800. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10801. get: function () {
  10802. return this._frontFace;
  10803. },
  10804. set: function (value) {
  10805. if (this._frontFace === value) {
  10806. return;
  10807. }
  10808. this._frontFace = value;
  10809. this._isFrontFaceDirty = true;
  10810. },
  10811. enumerable: true,
  10812. configurable: true
  10813. });
  10814. _DepthCullingState.prototype.reset = function () {
  10815. this._depthMask = true;
  10816. this._depthTest = true;
  10817. this._depthFunc = null;
  10818. this._cullFace = null;
  10819. this._cull = null;
  10820. this._zOffset = 0;
  10821. this._frontFace = null;
  10822. this._isDepthTestDirty = true;
  10823. this._isDepthMaskDirty = true;
  10824. this._isDepthFuncDirty = false;
  10825. this._isCullFaceDirty = false;
  10826. this._isCullDirty = false;
  10827. this._isZOffsetDirty = false;
  10828. this._isFrontFaceDirty = false;
  10829. };
  10830. _DepthCullingState.prototype.apply = function (gl) {
  10831. if (!this.isDirty) {
  10832. return;
  10833. }
  10834. // Cull
  10835. if (this._isCullDirty) {
  10836. if (this.cull) {
  10837. gl.enable(gl.CULL_FACE);
  10838. }
  10839. else {
  10840. gl.disable(gl.CULL_FACE);
  10841. }
  10842. this._isCullDirty = false;
  10843. }
  10844. // Cull face
  10845. if (this._isCullFaceDirty) {
  10846. gl.cullFace(this.cullFace);
  10847. this._isCullFaceDirty = false;
  10848. }
  10849. // Depth mask
  10850. if (this._isDepthMaskDirty) {
  10851. gl.depthMask(this.depthMask);
  10852. this._isDepthMaskDirty = false;
  10853. }
  10854. // Depth test
  10855. if (this._isDepthTestDirty) {
  10856. if (this.depthTest) {
  10857. gl.enable(gl.DEPTH_TEST);
  10858. }
  10859. else {
  10860. gl.disable(gl.DEPTH_TEST);
  10861. }
  10862. this._isDepthTestDirty = false;
  10863. }
  10864. // Depth func
  10865. if (this._isDepthFuncDirty) {
  10866. gl.depthFunc(this.depthFunc);
  10867. this._isDepthFuncDirty = false;
  10868. }
  10869. // zOffset
  10870. if (this._isZOffsetDirty) {
  10871. if (this.zOffset) {
  10872. gl.enable(gl.POLYGON_OFFSET_FILL);
  10873. gl.polygonOffset(this.zOffset, 0);
  10874. }
  10875. else {
  10876. gl.disable(gl.POLYGON_OFFSET_FILL);
  10877. }
  10878. this._isZOffsetDirty = false;
  10879. }
  10880. // Front face
  10881. if (this._isFrontFaceDirty) {
  10882. gl.frontFace(this.frontFace);
  10883. this._isFrontFaceDirty = false;
  10884. }
  10885. };
  10886. return _DepthCullingState;
  10887. }());
  10888. BABYLON._DepthCullingState = _DepthCullingState;
  10889. })(BABYLON || (BABYLON = {}));
  10890. //# sourceMappingURL=babylon.depthCullingState.js.map
  10891. var BABYLON;
  10892. (function (BABYLON) {
  10893. /**
  10894. * @hidden
  10895. **/
  10896. var _StencilState = /** @class */ (function () {
  10897. function _StencilState() {
  10898. this._isStencilTestDirty = false;
  10899. this._isStencilMaskDirty = false;
  10900. this._isStencilFuncDirty = false;
  10901. this._isStencilOpDirty = false;
  10902. this.reset();
  10903. }
  10904. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10905. get: function () {
  10906. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10912. get: function () {
  10913. return this._stencilFunc;
  10914. },
  10915. set: function (value) {
  10916. if (this._stencilFunc === value) {
  10917. return;
  10918. }
  10919. this._stencilFunc = value;
  10920. this._isStencilFuncDirty = true;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10926. get: function () {
  10927. return this._stencilFuncRef;
  10928. },
  10929. set: function (value) {
  10930. if (this._stencilFuncRef === value) {
  10931. return;
  10932. }
  10933. this._stencilFuncRef = value;
  10934. this._isStencilFuncDirty = true;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10940. get: function () {
  10941. return this._stencilFuncMask;
  10942. },
  10943. set: function (value) {
  10944. if (this._stencilFuncMask === value) {
  10945. return;
  10946. }
  10947. this._stencilFuncMask = value;
  10948. this._isStencilFuncDirty = true;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10954. get: function () {
  10955. return this._stencilOpStencilFail;
  10956. },
  10957. set: function (value) {
  10958. if (this._stencilOpStencilFail === value) {
  10959. return;
  10960. }
  10961. this._stencilOpStencilFail = value;
  10962. this._isStencilOpDirty = true;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10968. get: function () {
  10969. return this._stencilOpDepthFail;
  10970. },
  10971. set: function (value) {
  10972. if (this._stencilOpDepthFail === value) {
  10973. return;
  10974. }
  10975. this._stencilOpDepthFail = value;
  10976. this._isStencilOpDirty = true;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10982. get: function () {
  10983. return this._stencilOpStencilDepthPass;
  10984. },
  10985. set: function (value) {
  10986. if (this._stencilOpStencilDepthPass === value) {
  10987. return;
  10988. }
  10989. this._stencilOpStencilDepthPass = value;
  10990. this._isStencilOpDirty = true;
  10991. },
  10992. enumerable: true,
  10993. configurable: true
  10994. });
  10995. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10996. get: function () {
  10997. return this._stencilMask;
  10998. },
  10999. set: function (value) {
  11000. if (this._stencilMask === value) {
  11001. return;
  11002. }
  11003. this._stencilMask = value;
  11004. this._isStencilMaskDirty = true;
  11005. },
  11006. enumerable: true,
  11007. configurable: true
  11008. });
  11009. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11010. get: function () {
  11011. return this._stencilTest;
  11012. },
  11013. set: function (value) {
  11014. if (this._stencilTest === value) {
  11015. return;
  11016. }
  11017. this._stencilTest = value;
  11018. this._isStencilTestDirty = true;
  11019. },
  11020. enumerable: true,
  11021. configurable: true
  11022. });
  11023. _StencilState.prototype.reset = function () {
  11024. this._stencilTest = false;
  11025. this._stencilMask = 0xFF;
  11026. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11027. this._stencilFuncRef = 1;
  11028. this._stencilFuncMask = 0xFF;
  11029. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11030. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11031. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11032. this._isStencilTestDirty = true;
  11033. this._isStencilMaskDirty = true;
  11034. this._isStencilFuncDirty = true;
  11035. this._isStencilOpDirty = true;
  11036. };
  11037. _StencilState.prototype.apply = function (gl) {
  11038. if (!this.isDirty) {
  11039. return;
  11040. }
  11041. // Stencil test
  11042. if (this._isStencilTestDirty) {
  11043. if (this.stencilTest) {
  11044. gl.enable(gl.STENCIL_TEST);
  11045. }
  11046. else {
  11047. gl.disable(gl.STENCIL_TEST);
  11048. }
  11049. this._isStencilTestDirty = false;
  11050. }
  11051. // Stencil mask
  11052. if (this._isStencilMaskDirty) {
  11053. gl.stencilMask(this.stencilMask);
  11054. this._isStencilMaskDirty = false;
  11055. }
  11056. // Stencil func
  11057. if (this._isStencilFuncDirty) {
  11058. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11059. this._isStencilFuncDirty = false;
  11060. }
  11061. // Stencil op
  11062. if (this._isStencilOpDirty) {
  11063. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11064. this._isStencilOpDirty = false;
  11065. }
  11066. };
  11067. return _StencilState;
  11068. }());
  11069. BABYLON._StencilState = _StencilState;
  11070. })(BABYLON || (BABYLON = {}));
  11071. //# sourceMappingURL=babylon.stencilState.js.map
  11072. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11073. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11074. s = arguments[i];
  11075. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11076. t[p] = s[p];
  11077. }
  11078. return t;
  11079. };
  11080. var BABYLON;
  11081. (function (BABYLON) {
  11082. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11083. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11084. };
  11085. var compileRawShader = function (gl, source, type) {
  11086. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11087. gl.shaderSource(shader, source);
  11088. gl.compileShader(shader);
  11089. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11090. var log = gl.getShaderInfoLog(shader);
  11091. if (log) {
  11092. throw new Error(log);
  11093. }
  11094. }
  11095. if (!shader) {
  11096. throw new Error("Something went wrong while compile the shader.");
  11097. }
  11098. return shader;
  11099. };
  11100. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11101. var magFilter = gl.NEAREST;
  11102. var minFilter = gl.NEAREST;
  11103. switch (samplingMode) {
  11104. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11105. magFilter = gl.LINEAR;
  11106. if (generateMipMaps) {
  11107. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11108. }
  11109. else {
  11110. minFilter = gl.LINEAR;
  11111. }
  11112. break;
  11113. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11114. magFilter = gl.LINEAR;
  11115. if (generateMipMaps) {
  11116. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11117. }
  11118. else {
  11119. minFilter = gl.LINEAR;
  11120. }
  11121. break;
  11122. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11123. magFilter = gl.NEAREST;
  11124. if (generateMipMaps) {
  11125. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11126. }
  11127. else {
  11128. minFilter = gl.NEAREST;
  11129. }
  11130. break;
  11131. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11132. magFilter = gl.NEAREST;
  11133. if (generateMipMaps) {
  11134. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11135. }
  11136. else {
  11137. minFilter = gl.NEAREST;
  11138. }
  11139. break;
  11140. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11141. magFilter = gl.NEAREST;
  11142. if (generateMipMaps) {
  11143. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11144. }
  11145. else {
  11146. minFilter = gl.LINEAR;
  11147. }
  11148. break;
  11149. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11150. magFilter = gl.NEAREST;
  11151. if (generateMipMaps) {
  11152. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11153. }
  11154. else {
  11155. minFilter = gl.LINEAR;
  11156. }
  11157. break;
  11158. case BABYLON.Texture.NEAREST_LINEAR:
  11159. magFilter = gl.NEAREST;
  11160. minFilter = gl.LINEAR;
  11161. break;
  11162. case BABYLON.Texture.NEAREST_NEAREST:
  11163. magFilter = gl.NEAREST;
  11164. minFilter = gl.NEAREST;
  11165. break;
  11166. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11167. magFilter = gl.LINEAR;
  11168. if (generateMipMaps) {
  11169. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11170. }
  11171. else {
  11172. minFilter = gl.NEAREST;
  11173. }
  11174. break;
  11175. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11176. magFilter = gl.LINEAR;
  11177. if (generateMipMaps) {
  11178. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11179. }
  11180. else {
  11181. minFilter = gl.NEAREST;
  11182. }
  11183. break;
  11184. case BABYLON.Texture.LINEAR_LINEAR:
  11185. magFilter = gl.LINEAR;
  11186. minFilter = gl.LINEAR;
  11187. break;
  11188. case BABYLON.Texture.LINEAR_NEAREST:
  11189. magFilter = gl.LINEAR;
  11190. minFilter = gl.NEAREST;
  11191. break;
  11192. }
  11193. return {
  11194. min: minFilter,
  11195. mag: magFilter
  11196. };
  11197. };
  11198. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11199. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11200. var img;
  11201. var onload = function () {
  11202. loadedImages[index] = img;
  11203. loadedImages._internalCount++;
  11204. if (scene) {
  11205. scene._removePendingData(img);
  11206. }
  11207. if (loadedImages._internalCount === 6) {
  11208. onfinish(loadedImages);
  11209. }
  11210. };
  11211. var onerror = function (message, exception) {
  11212. if (scene) {
  11213. scene._removePendingData(img);
  11214. }
  11215. if (onErrorCallBack) {
  11216. onErrorCallBack(message, exception);
  11217. }
  11218. };
  11219. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11220. if (scene) {
  11221. scene._addPendingData(img);
  11222. }
  11223. };
  11224. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11225. if (onError === void 0) { onError = null; }
  11226. var loadedImages = [];
  11227. loadedImages._internalCount = 0;
  11228. for (var index = 0; index < 6; index++) {
  11229. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11230. }
  11231. };
  11232. var BufferPointer = /** @class */ (function () {
  11233. function BufferPointer() {
  11234. }
  11235. return BufferPointer;
  11236. }());
  11237. /**
  11238. * Interface for attribute information associated with buffer instanciation
  11239. */
  11240. var InstancingAttributeInfo = /** @class */ (function () {
  11241. function InstancingAttributeInfo() {
  11242. }
  11243. return InstancingAttributeInfo;
  11244. }());
  11245. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11246. /**
  11247. * Define options used to create a render target texture
  11248. */
  11249. var RenderTargetCreationOptions = /** @class */ (function () {
  11250. function RenderTargetCreationOptions() {
  11251. }
  11252. return RenderTargetCreationOptions;
  11253. }());
  11254. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11255. /**
  11256. * Define options used to create a depth texture
  11257. */
  11258. var DepthTextureCreationOptions = /** @class */ (function () {
  11259. function DepthTextureCreationOptions() {
  11260. }
  11261. return DepthTextureCreationOptions;
  11262. }());
  11263. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11264. /**
  11265. * Class used to describe the capabilities of the engine relatively to the current browser
  11266. */
  11267. var EngineCapabilities = /** @class */ (function () {
  11268. function EngineCapabilities() {
  11269. }
  11270. return EngineCapabilities;
  11271. }());
  11272. BABYLON.EngineCapabilities = EngineCapabilities;
  11273. /**
  11274. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11275. */
  11276. var Engine = /** @class */ (function () {
  11277. /**
  11278. * Creates a new engine
  11279. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11280. * @param antialias defines enable antialiasing (default: false)
  11281. * @param options defines further options to be sent to the getContext() function
  11282. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11283. */
  11284. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11285. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11286. var _this = this;
  11287. // Public members
  11288. /**
  11289. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11290. */
  11291. this.forcePOTTextures = false;
  11292. /**
  11293. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11294. */
  11295. this.isFullscreen = false;
  11296. /**
  11297. * Gets a boolean indicating if the pointer is currently locked
  11298. */
  11299. this.isPointerLock = false;
  11300. /**
  11301. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11302. */
  11303. this.cullBackFaces = true;
  11304. /**
  11305. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11306. */
  11307. this.renderEvenInBackground = true;
  11308. /**
  11309. * Gets or sets a boolean indicating that cache can be kept between frames
  11310. */
  11311. this.preventCacheWipeBetweenFrames = false;
  11312. /**
  11313. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11314. **/
  11315. this.enableOfflineSupport = false;
  11316. /**
  11317. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11318. **/
  11319. this.disableManifestCheck = false;
  11320. /**
  11321. * Gets the list of created scenes
  11322. */
  11323. this.scenes = new Array();
  11324. /**
  11325. * Gets the list of created postprocesses
  11326. */
  11327. this.postProcesses = new Array();
  11328. // Observables
  11329. /**
  11330. * Observable event triggered each time the rendering canvas is resized
  11331. */
  11332. this.onResizeObservable = new BABYLON.Observable();
  11333. /**
  11334. * Observable event triggered each time the canvas loses focus
  11335. */
  11336. this.onCanvasBlurObservable = new BABYLON.Observable();
  11337. /**
  11338. * Observable event triggered each time the canvas gains focus
  11339. */
  11340. this.onCanvasFocusObservable = new BABYLON.Observable();
  11341. /**
  11342. * Observable event triggered each time the canvas receives pointerout event
  11343. */
  11344. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11345. /**
  11346. * Observable event triggered before each texture is initialized
  11347. */
  11348. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11349. //WebVR
  11350. this._vrDisplay = undefined;
  11351. this._vrSupported = false;
  11352. this._vrExclusivePointerMode = false;
  11353. // Uniform buffers list
  11354. /**
  11355. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11356. */
  11357. this.disableUniformBuffers = false;
  11358. /** @hidden */
  11359. this._uniformBuffers = new Array();
  11360. // Observables
  11361. /**
  11362. * Observable raised when the engine begins a new frame
  11363. */
  11364. this.onBeginFrameObservable = new BABYLON.Observable();
  11365. /**
  11366. * Observable raised when the engine ends the current frame
  11367. */
  11368. this.onEndFrameObservable = new BABYLON.Observable();
  11369. /**
  11370. * Observable raised when the engine is about to compile a shader
  11371. */
  11372. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11373. /**
  11374. * Observable raised when the engine has jsut compiled a shader
  11375. */
  11376. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11377. this._windowIsBackground = false;
  11378. this._webGLVersion = 1.0;
  11379. /** @hidden */
  11380. this._badOS = false;
  11381. /** @hidden */
  11382. this._badDesktopOS = false;
  11383. /**
  11384. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11385. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11386. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11387. */
  11388. this.disableTextureBindingOptimization = false;
  11389. /**
  11390. * Observable signaled when VR display mode changes
  11391. */
  11392. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11393. /**
  11394. * Observable signaled when VR request present is complete
  11395. */
  11396. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11397. /**
  11398. * Observable signaled when VR request present starts
  11399. */
  11400. this.onVRRequestPresentStart = new BABYLON.Observable();
  11401. this._colorWrite = true;
  11402. /** @hidden */
  11403. this._drawCalls = new BABYLON.PerfCounter();
  11404. /** @hidden */
  11405. this._textureCollisions = new BABYLON.PerfCounter();
  11406. this._renderingQueueLaunched = false;
  11407. this._activeRenderLoops = new Array();
  11408. // Deterministic lockstepMaxSteps
  11409. this._deterministicLockstep = false;
  11410. this._lockstepMaxSteps = 4;
  11411. // Lost context
  11412. /**
  11413. * Observable signaled when a context lost event is raised
  11414. */
  11415. this.onContextLostObservable = new BABYLON.Observable();
  11416. /**
  11417. * Observable signaled when a context restored event is raised
  11418. */
  11419. this.onContextRestoredObservable = new BABYLON.Observable();
  11420. this._contextWasLost = false;
  11421. this._doNotHandleContextLost = false;
  11422. // FPS
  11423. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11424. this._fps = 60;
  11425. this._deltaTime = 0;
  11426. /**
  11427. * Turn this value on if you want to pause FPS computation when in background
  11428. */
  11429. this.disablePerformanceMonitorInBackground = false;
  11430. // States
  11431. /** @hidden */
  11432. this._depthCullingState = new BABYLON._DepthCullingState();
  11433. /** @hidden */
  11434. this._stencilState = new BABYLON._StencilState();
  11435. /** @hidden */
  11436. this._alphaState = new BABYLON._AlphaState();
  11437. /** @hidden */
  11438. this._alphaMode = Engine.ALPHA_DISABLE;
  11439. // Cache
  11440. this._internalTexturesCache = new Array();
  11441. /** @hidden */
  11442. this._activeChannel = 0;
  11443. this._currentTextureChannel = -1;
  11444. /** @hidden */
  11445. this._boundTexturesCache = {};
  11446. this._compiledEffects = {};
  11447. this._vertexAttribArraysEnabled = [];
  11448. this._uintIndicesCurrentlySet = false;
  11449. this._currentBoundBuffer = new Array();
  11450. this._currentBufferPointers = new Array();
  11451. this._currentInstanceLocations = new Array();
  11452. this._currentInstanceBuffers = new Array();
  11453. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11454. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11455. this._vaoRecordInProgress = false;
  11456. this._mustWipeVertexAttributes = false;
  11457. this._nextFreeTextureSlots = new Array();
  11458. this._maxSimultaneousTextures = 0;
  11459. this._activeRequests = new Array();
  11460. // Hardware supported Compressed Textures
  11461. this._texturesSupported = new Array();
  11462. /**
  11463. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11464. */
  11465. this.premultipliedAlpha = true;
  11466. this._onVRFullScreenTriggered = function () {
  11467. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11468. //get the old size before we change
  11469. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11470. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11471. //get the width and height, change the render size
  11472. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11473. _this.setHardwareScalingLevel(1);
  11474. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11475. }
  11476. else {
  11477. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11478. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11479. }
  11480. };
  11481. this._boundUniforms = {};
  11482. // Register promises
  11483. BABYLON.PromisePolyfill.Apply();
  11484. var canvas = null;
  11485. Engine.Instances.push(this);
  11486. if (!canvasOrContext) {
  11487. return;
  11488. }
  11489. options = options || {};
  11490. if (canvasOrContext.getContext) {
  11491. canvas = canvasOrContext;
  11492. this._renderingCanvas = canvas;
  11493. if (antialias != null) {
  11494. options.antialias = antialias;
  11495. }
  11496. if (options.deterministicLockstep === undefined) {
  11497. options.deterministicLockstep = false;
  11498. }
  11499. if (options.lockstepMaxSteps === undefined) {
  11500. options.lockstepMaxSteps = 4;
  11501. }
  11502. if (options.preserveDrawingBuffer === undefined) {
  11503. options.preserveDrawingBuffer = false;
  11504. }
  11505. if (options.audioEngine === undefined) {
  11506. options.audioEngine = true;
  11507. }
  11508. if (options.stencil === undefined) {
  11509. options.stencil = true;
  11510. }
  11511. if (options.premultipliedAlpha === false) {
  11512. this.premultipliedAlpha = false;
  11513. }
  11514. this._deterministicLockstep = options.deterministicLockstep;
  11515. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11516. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11517. // Exceptions
  11518. if (navigator && navigator.userAgent) {
  11519. var ua = navigator.userAgent;
  11520. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11521. var exception = _a[_i];
  11522. var key = exception.key;
  11523. var targets = exception.targets;
  11524. if (ua.indexOf(key) > -1) {
  11525. if (exception.capture && exception.captureConstraint) {
  11526. var capture = exception.capture;
  11527. var constraint = exception.captureConstraint;
  11528. var regex = new RegExp(capture);
  11529. var matches = regex.exec(ua);
  11530. if (matches && matches.length > 0) {
  11531. var capturedValue = parseInt(matches[matches.length - 1]);
  11532. if (capturedValue >= constraint) {
  11533. continue;
  11534. }
  11535. }
  11536. }
  11537. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11538. var target = targets_1[_b];
  11539. switch (target) {
  11540. case "uniformBuffer":
  11541. this.disableUniformBuffers = true;
  11542. break;
  11543. case "textureBindingOptimization":
  11544. this.disableTextureBindingOptimization = true;
  11545. break;
  11546. }
  11547. }
  11548. }
  11549. }
  11550. }
  11551. // GL
  11552. if (!options.disableWebGL2Support) {
  11553. try {
  11554. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11555. if (this._gl) {
  11556. this._webGLVersion = 2.0;
  11557. }
  11558. }
  11559. catch (e) {
  11560. // Do nothing
  11561. }
  11562. }
  11563. if (!this._gl) {
  11564. if (!canvas) {
  11565. throw new Error("The provided canvas is null or undefined.");
  11566. }
  11567. try {
  11568. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11569. }
  11570. catch (e) {
  11571. throw new Error("WebGL not supported");
  11572. }
  11573. }
  11574. if (!this._gl) {
  11575. throw new Error("WebGL not supported");
  11576. }
  11577. this._onCanvasFocus = function () {
  11578. _this.onCanvasFocusObservable.notifyObservers(_this);
  11579. };
  11580. this._onCanvasBlur = function () {
  11581. _this.onCanvasBlurObservable.notifyObservers(_this);
  11582. };
  11583. canvas.addEventListener("focus", this._onCanvasFocus);
  11584. canvas.addEventListener("blur", this._onCanvasBlur);
  11585. this._onBlur = function () {
  11586. if (_this.disablePerformanceMonitorInBackground) {
  11587. _this._performanceMonitor.disable();
  11588. }
  11589. _this._windowIsBackground = true;
  11590. };
  11591. this._onFocus = function () {
  11592. if (_this.disablePerformanceMonitorInBackground) {
  11593. _this._performanceMonitor.enable();
  11594. }
  11595. _this._windowIsBackground = false;
  11596. };
  11597. this._onCanvasPointerOut = function (ev) {
  11598. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11599. };
  11600. window.addEventListener("blur", this._onBlur);
  11601. window.addEventListener("focus", this._onFocus);
  11602. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11603. // Context lost
  11604. if (!this._doNotHandleContextLost) {
  11605. this._onContextLost = function (evt) {
  11606. evt.preventDefault();
  11607. _this._contextWasLost = true;
  11608. BABYLON.Tools.Warn("WebGL context lost.");
  11609. _this.onContextLostObservable.notifyObservers(_this);
  11610. };
  11611. this._onContextRestored = function (evt) {
  11612. // Adding a timeout to avoid race condition at browser level
  11613. setTimeout(function () {
  11614. // Rebuild gl context
  11615. _this._initGLContext();
  11616. // Rebuild effects
  11617. _this._rebuildEffects();
  11618. // Rebuild textures
  11619. _this._rebuildInternalTextures();
  11620. // Rebuild buffers
  11621. _this._rebuildBuffers();
  11622. // Cache
  11623. _this.wipeCaches(true);
  11624. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11625. _this.onContextRestoredObservable.notifyObservers(_this);
  11626. _this._contextWasLost = false;
  11627. }, 0);
  11628. };
  11629. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11630. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11631. }
  11632. }
  11633. else {
  11634. this._gl = canvasOrContext;
  11635. this._renderingCanvas = this._gl.canvas;
  11636. if (this._gl.renderbufferStorageMultisample) {
  11637. this._webGLVersion = 2.0;
  11638. }
  11639. options.stencil = this._gl.getContextAttributes().stencil;
  11640. }
  11641. // Viewport
  11642. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11643. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11644. this.resize();
  11645. this._isStencilEnable = options.stencil ? true : false;
  11646. this._initGLContext();
  11647. if (canvas) {
  11648. // Fullscreen
  11649. this._onFullscreenChange = function () {
  11650. if (document.fullscreen !== undefined) {
  11651. _this.isFullscreen = document.fullscreen;
  11652. }
  11653. else if (document.mozFullScreen !== undefined) {
  11654. _this.isFullscreen = document.mozFullScreen;
  11655. }
  11656. else if (document.webkitIsFullScreen !== undefined) {
  11657. _this.isFullscreen = document.webkitIsFullScreen;
  11658. }
  11659. else if (document.msIsFullScreen !== undefined) {
  11660. _this.isFullscreen = document.msIsFullScreen;
  11661. }
  11662. // Pointer lock
  11663. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11664. canvas.requestPointerLock = canvas.requestPointerLock ||
  11665. canvas.msRequestPointerLock ||
  11666. canvas.mozRequestPointerLock ||
  11667. canvas.webkitRequestPointerLock;
  11668. if (canvas.requestPointerLock) {
  11669. canvas.requestPointerLock();
  11670. }
  11671. }
  11672. };
  11673. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11674. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11675. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11676. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11677. // Pointer lock
  11678. this._onPointerLockChange = function () {
  11679. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11680. document.webkitPointerLockElement === canvas ||
  11681. document.msPointerLockElement === canvas ||
  11682. document.pointerLockElement === canvas);
  11683. };
  11684. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11685. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11686. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11687. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11688. this._onVRDisplayPointerRestricted = function () {
  11689. if (canvas) {
  11690. canvas.requestPointerLock();
  11691. }
  11692. };
  11693. this._onVRDisplayPointerUnrestricted = function () {
  11694. document.exitPointerLock();
  11695. };
  11696. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11697. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11698. }
  11699. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11700. Engine.audioEngine = new BABYLON.AudioEngine();
  11701. }
  11702. // Prepare buffer pointers
  11703. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11704. this._currentBufferPointers[i] = new BufferPointer();
  11705. }
  11706. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11707. // Load WebVR Devices
  11708. if (options.autoEnableWebVR) {
  11709. this.initWebVR();
  11710. }
  11711. // Detect if we are running on a faulty buggy OS.
  11712. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11713. // Detect if we are running on a faulty buggy desktop OS.
  11714. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11715. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11716. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11717. }
  11718. Object.defineProperty(Engine, "LastCreatedEngine", {
  11719. /**
  11720. * Gets the latest created engine
  11721. */
  11722. get: function () {
  11723. if (Engine.Instances.length === 0) {
  11724. return null;
  11725. }
  11726. return Engine.Instances[Engine.Instances.length - 1];
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "LastCreatedScene", {
  11732. /**
  11733. * Gets the latest created scene
  11734. */
  11735. get: function () {
  11736. var lastCreatedEngine = Engine.LastCreatedEngine;
  11737. if (!lastCreatedEngine) {
  11738. return null;
  11739. }
  11740. if (lastCreatedEngine.scenes.length === 0) {
  11741. return null;
  11742. }
  11743. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. /**
  11749. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11750. * @param flag defines which part of the materials must be marked as dirty
  11751. * @param predicate defines a predicate used to filter which materials should be affected
  11752. */
  11753. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11754. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11755. var engine = Engine.Instances[engineIndex];
  11756. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11757. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11758. }
  11759. }
  11760. };
  11761. Object.defineProperty(Engine, "NEVER", {
  11762. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11763. get: function () {
  11764. return Engine._NEVER;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "ALWAYS", {
  11770. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  11771. get: function () {
  11772. return Engine._ALWAYS;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "LESS", {
  11778. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11779. get: function () {
  11780. return Engine._LESS;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "EQUAL", {
  11786. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11787. get: function () {
  11788. return Engine._EQUAL;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "LEQUAL", {
  11794. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  11795. get: function () {
  11796. return Engine._LEQUAL;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "GREATER", {
  11802. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11803. get: function () {
  11804. return Engine._GREATER;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine, "GEQUAL", {
  11810. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  11811. get: function () {
  11812. return Engine._GEQUAL;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine, "NOTEQUAL", {
  11818. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  11819. get: function () {
  11820. return Engine._NOTEQUAL;
  11821. },
  11822. enumerable: true,
  11823. configurable: true
  11824. });
  11825. Object.defineProperty(Engine, "KEEP", {
  11826. /** Passed to stencilOperation to specify that stencil value must be kept */
  11827. get: function () {
  11828. return Engine._KEEP;
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(Engine, "REPLACE", {
  11834. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11835. get: function () {
  11836. return Engine._REPLACE;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine, "INCR", {
  11842. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11843. get: function () {
  11844. return Engine._INCR;
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(Engine, "DECR", {
  11850. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11851. get: function () {
  11852. return Engine._DECR;
  11853. },
  11854. enumerable: true,
  11855. configurable: true
  11856. });
  11857. Object.defineProperty(Engine, "INVERT", {
  11858. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11859. get: function () {
  11860. return Engine._INVERT;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. Object.defineProperty(Engine, "INCR_WRAP", {
  11866. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11867. get: function () {
  11868. return Engine._INCR_WRAP;
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Object.defineProperty(Engine, "DECR_WRAP", {
  11874. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11875. get: function () {
  11876. return Engine._DECR_WRAP;
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11882. // Alpha
  11883. /** Defines that alpha blending is disabled */
  11884. get: function () {
  11885. return Engine._ALPHA_DISABLE;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11891. /** Defines that alpha blending to SRC + DEST */
  11892. get: function () {
  11893. return Engine._ALPHA_ONEONE;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine, "ALPHA_ADD", {
  11899. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11900. get: function () {
  11901. return Engine._ALPHA_ADD;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11907. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11908. get: function () {
  11909. return Engine._ALPHA_COMBINE;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11915. /** Defines that alpha blending to DEST - SRC * DEST */
  11916. get: function () {
  11917. return Engine._ALPHA_SUBTRACT;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11923. /** Defines that alpha blending to SRC * DEST */
  11924. get: function () {
  11925. return Engine._ALPHA_MULTIPLY;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11931. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11932. get: function () {
  11933. return Engine._ALPHA_MAXIMIZED;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11939. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11940. get: function () {
  11941. return Engine._ALPHA_PREMULTIPLIED;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11947. /**
  11948. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11949. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11950. */
  11951. get: function () {
  11952. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11958. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11959. get: function () {
  11960. return Engine._ALPHA_INTERPOLATE;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11966. /**
  11967. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11968. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11969. */
  11970. get: function () {
  11971. return Engine._ALPHA_SCREENMODE;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11977. // Delays
  11978. /** Defines that the ressource is not delayed*/
  11979. get: function () {
  11980. return Engine._DELAYLOADSTATE_NONE;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11986. /** Defines that the ressource was successfully delay loaded */
  11987. get: function () {
  11988. return Engine._DELAYLOADSTATE_LOADED;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11994. /** Defines that the ressource is currently delay loading */
  11995. get: function () {
  11996. return Engine._DELAYLOADSTATE_LOADING;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12002. /** Defines that the ressource is delayed and has not started loading */
  12003. get: function () {
  12004. return Engine._DELAYLOADSTATE_NOTLOADED;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12010. /** ALPHA */
  12011. get: function () {
  12012. return Engine._TEXTUREFORMAT_ALPHA;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12018. /** LUMINANCE */
  12019. get: function () {
  12020. return Engine._TEXTUREFORMAT_LUMINANCE;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12026. /**
  12027. * R
  12028. */
  12029. get: function () {
  12030. return Engine._TEXTUREFORMAT_R;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12036. /**
  12037. * RG
  12038. */
  12039. get: function () {
  12040. return Engine._TEXTUREFORMAT_RG;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12046. /** LUMINANCE_ALPHA */
  12047. get: function () {
  12048. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12049. },
  12050. enumerable: true,
  12051. configurable: true
  12052. });
  12053. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12054. /** RGB */
  12055. get: function () {
  12056. return Engine._TEXTUREFORMAT_RGB;
  12057. },
  12058. enumerable: true,
  12059. configurable: true
  12060. });
  12061. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12062. /** RGBA */
  12063. get: function () {
  12064. return Engine._TEXTUREFORMAT_RGBA;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12070. /** UNSIGNED_INT */
  12071. get: function () {
  12072. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12078. /** FLOAT */
  12079. get: function () {
  12080. return Engine._TEXTURETYPE_FLOAT;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12086. /** HALF_FLOAT */
  12087. get: function () {
  12088. return Engine._TEXTURETYPE_HALF_FLOAT;
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12094. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12095. get: function () {
  12096. return Engine._SCALEMODE_FLOOR;
  12097. },
  12098. enumerable: true,
  12099. configurable: true
  12100. });
  12101. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12102. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12103. get: function () {
  12104. return Engine._SCALEMODE_NEAREST;
  12105. },
  12106. enumerable: true,
  12107. configurable: true
  12108. });
  12109. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12110. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12111. get: function () {
  12112. return Engine._SCALEMODE_CEILING;
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. Object.defineProperty(Engine, "Version", {
  12118. /**
  12119. * Returns the current version of the framework
  12120. */
  12121. get: function () {
  12122. return "3.3.0-alpha.6";
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12128. /**
  12129. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12130. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12131. */
  12132. get: function () {
  12133. return this._vrExclusivePointerMode;
  12134. },
  12135. enumerable: true,
  12136. configurable: true
  12137. });
  12138. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12139. /**
  12140. * Gets a boolean indicating that the engine supports uniform buffers
  12141. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12142. */
  12143. get: function () {
  12144. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12145. },
  12146. enumerable: true,
  12147. configurable: true
  12148. });
  12149. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12150. /**
  12151. * Gets a boolean indicating that only power of 2 textures are supported
  12152. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12153. */
  12154. get: function () {
  12155. return this._webGLVersion < 2 || this.forcePOTTextures;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12161. /**
  12162. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12163. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12164. */
  12165. get: function () {
  12166. return this._doNotHandleContextLost;
  12167. },
  12168. set: function (value) {
  12169. this._doNotHandleContextLost = value;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12175. /**
  12176. * Gets the performance monitor attached to this engine
  12177. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12178. */
  12179. get: function () {
  12180. return this._performanceMonitor;
  12181. },
  12182. enumerable: true,
  12183. configurable: true
  12184. });
  12185. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12186. /**
  12187. * Gets the list of texture formats supported
  12188. */
  12189. get: function () {
  12190. return this._texturesSupported;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12196. /**
  12197. * Gets the list of texture formats in use
  12198. */
  12199. get: function () {
  12200. return this._textureFormatInUse;
  12201. },
  12202. enumerable: true,
  12203. configurable: true
  12204. });
  12205. Object.defineProperty(Engine.prototype, "currentViewport", {
  12206. /**
  12207. * Gets the current viewport
  12208. */
  12209. get: function () {
  12210. return this._cachedViewport;
  12211. },
  12212. enumerable: true,
  12213. configurable: true
  12214. });
  12215. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12216. /**
  12217. * Gets the default empty texture
  12218. */
  12219. get: function () {
  12220. if (!this._emptyTexture) {
  12221. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12222. }
  12223. return this._emptyTexture;
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12229. /**
  12230. * Gets the default empty 3D texture
  12231. */
  12232. get: function () {
  12233. if (!this._emptyTexture3D) {
  12234. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12235. }
  12236. return this._emptyTexture3D;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12242. /**
  12243. * Gets the default empty cube texture
  12244. */
  12245. get: function () {
  12246. if (!this._emptyCubeTexture) {
  12247. var faceData = new Uint8Array(4);
  12248. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12249. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12250. }
  12251. return this._emptyCubeTexture;
  12252. },
  12253. enumerable: true,
  12254. configurable: true
  12255. });
  12256. Engine.prototype._rebuildInternalTextures = function () {
  12257. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12258. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12259. var internalTexture = currentState_1[_i];
  12260. internalTexture._rebuild();
  12261. }
  12262. };
  12263. Engine.prototype._rebuildEffects = function () {
  12264. for (var key in this._compiledEffects) {
  12265. var effect = this._compiledEffects[key];
  12266. effect._prepareEffect();
  12267. }
  12268. BABYLON.Effect.ResetCache();
  12269. };
  12270. Engine.prototype._rebuildBuffers = function () {
  12271. // Index / Vertex
  12272. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12273. var scene = _a[_i];
  12274. scene.resetCachedMaterial();
  12275. scene._rebuildGeometries();
  12276. scene._rebuildTextures();
  12277. }
  12278. // Uniforms
  12279. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12280. var uniformBuffer = _c[_b];
  12281. uniformBuffer._rebuild();
  12282. }
  12283. };
  12284. Engine.prototype._initGLContext = function () {
  12285. // Caps
  12286. this._caps = new EngineCapabilities();
  12287. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12288. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12289. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12290. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12291. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12292. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12293. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12294. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12295. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12296. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12297. // Infos
  12298. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12299. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12300. if (rendererInfo != null) {
  12301. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12302. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12303. }
  12304. if (!this._glVendor) {
  12305. this._glVendor = "Unknown vendor";
  12306. }
  12307. if (!this._glRenderer) {
  12308. this._glRenderer = "Unknown renderer";
  12309. }
  12310. // Constants
  12311. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12312. if (this._gl.RGBA16F !== 0x881A) {
  12313. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12314. }
  12315. if (this._gl.RGBA32F !== 0x8814) {
  12316. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12317. }
  12318. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12319. this._gl.DEPTH24_STENCIL8 = 35056;
  12320. }
  12321. // Extensions
  12322. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12323. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12324. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12325. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12326. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12327. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12328. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12329. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  12330. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12331. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12332. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12333. this._caps.highPrecisionShaderSupported = true;
  12334. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12335. if (this._caps.timerQuery) {
  12336. if (this._webGLVersion === 1) {
  12337. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12338. }
  12339. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12340. }
  12341. // Checks if some of the format renders first to allow the use of webgl inspector.
  12342. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12343. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12344. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12345. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12346. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12347. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12348. if (this._webGLVersion > 1) {
  12349. this._gl.HALF_FLOAT_OES = 0x140B;
  12350. }
  12351. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12352. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12353. // Draw buffers
  12354. if (this._webGLVersion > 1) {
  12355. this._caps.drawBuffersExtension = true;
  12356. }
  12357. else {
  12358. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12359. if (drawBuffersExtension !== null) {
  12360. this._caps.drawBuffersExtension = true;
  12361. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12362. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12363. for (var i = 0; i < 16; i++) {
  12364. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12365. }
  12366. }
  12367. else {
  12368. this._caps.drawBuffersExtension = false;
  12369. }
  12370. }
  12371. // Depth Texture
  12372. if (this._webGLVersion > 1) {
  12373. this._caps.depthTextureExtension = true;
  12374. }
  12375. else {
  12376. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12377. if (depthTextureExtension != null) {
  12378. this._caps.depthTextureExtension = true;
  12379. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12380. }
  12381. }
  12382. // Vertex array object
  12383. if (this._webGLVersion > 1) {
  12384. this._caps.vertexArrayObject = true;
  12385. }
  12386. else {
  12387. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12388. if (vertexArrayObjectExtension != null) {
  12389. this._caps.vertexArrayObject = true;
  12390. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12391. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12392. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12393. }
  12394. else {
  12395. this._caps.vertexArrayObject = false;
  12396. }
  12397. }
  12398. // Instances count
  12399. if (this._webGLVersion > 1) {
  12400. this._caps.instancedArrays = true;
  12401. }
  12402. else {
  12403. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12404. if (instanceExtension != null) {
  12405. this._caps.instancedArrays = true;
  12406. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12407. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12408. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12409. }
  12410. else {
  12411. this._caps.instancedArrays = false;
  12412. }
  12413. }
  12414. // Intelligently add supported compressed formats in order to check for.
  12415. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12416. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12417. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12418. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12419. if (this._caps.astc)
  12420. this.texturesSupported.push('-astc.ktx');
  12421. if (this._caps.s3tc)
  12422. this.texturesSupported.push('-dxt.ktx');
  12423. if (this._caps.pvrtc)
  12424. this.texturesSupported.push('-pvrtc.ktx');
  12425. if (this._caps.etc2)
  12426. this.texturesSupported.push('-etc2.ktx');
  12427. if (this._caps.etc1)
  12428. this.texturesSupported.push('-etc1.ktx');
  12429. if (this._gl.getShaderPrecisionFormat) {
  12430. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12431. if (highp) {
  12432. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12433. }
  12434. }
  12435. // Depth buffer
  12436. this.setDepthBuffer(true);
  12437. this.setDepthFunctionToLessOrEqual();
  12438. this.setDepthWrite(true);
  12439. // Texture maps
  12440. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12441. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12442. this._nextFreeTextureSlots.push(slot);
  12443. }
  12444. };
  12445. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12446. /**
  12447. * Gets version of the current webGL context
  12448. */
  12449. get: function () {
  12450. return this._webGLVersion;
  12451. },
  12452. enumerable: true,
  12453. configurable: true
  12454. });
  12455. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12456. /**
  12457. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12458. */
  12459. get: function () {
  12460. return this._isStencilEnable;
  12461. },
  12462. enumerable: true,
  12463. configurable: true
  12464. });
  12465. Engine.prototype._prepareWorkingCanvas = function () {
  12466. if (this._workingCanvas) {
  12467. return;
  12468. }
  12469. this._workingCanvas = document.createElement("canvas");
  12470. var context = this._workingCanvas.getContext("2d");
  12471. if (context) {
  12472. this._workingContext = context;
  12473. }
  12474. };
  12475. /**
  12476. * Reset the texture cache to empty state
  12477. */
  12478. Engine.prototype.resetTextureCache = function () {
  12479. for (var key in this._boundTexturesCache) {
  12480. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12481. continue;
  12482. }
  12483. var boundTexture = this._boundTexturesCache[key];
  12484. if (boundTexture) {
  12485. this._removeDesignatedSlot(boundTexture);
  12486. }
  12487. this._boundTexturesCache[key] = null;
  12488. }
  12489. if (!this.disableTextureBindingOptimization) {
  12490. this._nextFreeTextureSlots = [];
  12491. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12492. this._nextFreeTextureSlots.push(slot);
  12493. }
  12494. }
  12495. this._currentTextureChannel = -1;
  12496. };
  12497. /**
  12498. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12499. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12500. * @returns true if engine is in deterministic lock step mode
  12501. */
  12502. Engine.prototype.isDeterministicLockStep = function () {
  12503. return this._deterministicLockstep;
  12504. };
  12505. /**
  12506. * Gets the max steps when engine is running in deterministic lock step
  12507. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12508. * @returns the max steps
  12509. */
  12510. Engine.prototype.getLockstepMaxSteps = function () {
  12511. return this._lockstepMaxSteps;
  12512. };
  12513. /**
  12514. * Gets an object containing information about the current webGL context
  12515. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12516. */
  12517. Engine.prototype.getGlInfo = function () {
  12518. return {
  12519. vendor: this._glVendor,
  12520. renderer: this._glRenderer,
  12521. version: this._glVersion
  12522. };
  12523. };
  12524. /**
  12525. * Gets current aspect ratio
  12526. * @param camera defines the camera to use to get the aspect ratio
  12527. * @param useScreen defines if screen size must be used (or the current render target if any)
  12528. * @returns a number defining the aspect ratio
  12529. */
  12530. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12531. if (useScreen === void 0) { useScreen = false; }
  12532. var viewport = camera.viewport;
  12533. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12534. };
  12535. /**
  12536. * Gets current screen aspect ratio
  12537. * @returns a number defining the aspect ratio
  12538. */
  12539. Engine.prototype.getScreenAspectRatio = function () {
  12540. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12541. };
  12542. /**
  12543. * Gets the current render width
  12544. * @param useScreen defines if screen size must be used (or the current render target if any)
  12545. * @returns a number defining the current render width
  12546. */
  12547. Engine.prototype.getRenderWidth = function (useScreen) {
  12548. if (useScreen === void 0) { useScreen = false; }
  12549. if (!useScreen && this._currentRenderTarget) {
  12550. return this._currentRenderTarget.width;
  12551. }
  12552. return this._gl.drawingBufferWidth;
  12553. };
  12554. /**
  12555. * Gets the current render height
  12556. * @param useScreen defines if screen size must be used (or the current render target if any)
  12557. * @returns a number defining the current render height
  12558. */
  12559. Engine.prototype.getRenderHeight = function (useScreen) {
  12560. if (useScreen === void 0) { useScreen = false; }
  12561. if (!useScreen && this._currentRenderTarget) {
  12562. return this._currentRenderTarget.height;
  12563. }
  12564. return this._gl.drawingBufferHeight;
  12565. };
  12566. /**
  12567. * Gets the HTML canvas attached with the current webGL context
  12568. * @returns a HTML canvas
  12569. */
  12570. Engine.prototype.getRenderingCanvas = function () {
  12571. return this._renderingCanvas;
  12572. };
  12573. /**
  12574. * Gets the client rect of the HTML canvas attached with the current webGL context
  12575. * @returns a client rectanglee
  12576. */
  12577. Engine.prototype.getRenderingCanvasClientRect = function () {
  12578. if (!this._renderingCanvas) {
  12579. return null;
  12580. }
  12581. return this._renderingCanvas.getBoundingClientRect();
  12582. };
  12583. /**
  12584. * Defines the hardware scaling level.
  12585. * By default the hardware scaling level is computed from the window device ratio.
  12586. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12587. * @param level defines the level to use
  12588. */
  12589. Engine.prototype.setHardwareScalingLevel = function (level) {
  12590. this._hardwareScalingLevel = level;
  12591. this.resize();
  12592. };
  12593. /**
  12594. * Gets the current hardware scaling level.
  12595. * By default the hardware scaling level is computed from the window device ratio.
  12596. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12597. * @returns a number indicating the current hardware scaling level
  12598. */
  12599. Engine.prototype.getHardwareScalingLevel = function () {
  12600. return this._hardwareScalingLevel;
  12601. };
  12602. /**
  12603. * Gets the list of loaded textures
  12604. * @returns an array containing all loaded textures
  12605. */
  12606. Engine.prototype.getLoadedTexturesCache = function () {
  12607. return this._internalTexturesCache;
  12608. };
  12609. /**
  12610. * Gets the object containing all engine capabilities
  12611. * @returns the EngineCapabilities object
  12612. */
  12613. Engine.prototype.getCaps = function () {
  12614. return this._caps;
  12615. };
  12616. Object.defineProperty(Engine.prototype, "drawCalls", {
  12617. /** @hidden */
  12618. get: function () {
  12619. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12620. return 0;
  12621. },
  12622. enumerable: true,
  12623. configurable: true
  12624. });
  12625. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12626. /** @hidden */
  12627. get: function () {
  12628. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12629. return null;
  12630. },
  12631. enumerable: true,
  12632. configurable: true
  12633. });
  12634. /**
  12635. * Gets the current depth function
  12636. * @returns a number defining the depth function
  12637. */
  12638. Engine.prototype.getDepthFunction = function () {
  12639. return this._depthCullingState.depthFunc;
  12640. };
  12641. /**
  12642. * Sets the current depth function
  12643. * @param depthFunc defines the function to use
  12644. */
  12645. Engine.prototype.setDepthFunction = function (depthFunc) {
  12646. this._depthCullingState.depthFunc = depthFunc;
  12647. };
  12648. /**
  12649. * Sets the current depth function to GREATER
  12650. */
  12651. Engine.prototype.setDepthFunctionToGreater = function () {
  12652. this._depthCullingState.depthFunc = this._gl.GREATER;
  12653. };
  12654. /**
  12655. * Sets the current depth function to GEQUAL
  12656. */
  12657. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12658. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12659. };
  12660. /**
  12661. * Sets the current depth function to LESS
  12662. */
  12663. Engine.prototype.setDepthFunctionToLess = function () {
  12664. this._depthCullingState.depthFunc = this._gl.LESS;
  12665. };
  12666. /**
  12667. * Sets the current depth function to LEQUAL
  12668. */
  12669. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12670. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12671. };
  12672. /**
  12673. * Gets a boolean indicating if stencil buffer is enabled
  12674. * @returns the current stencil buffer state
  12675. */
  12676. Engine.prototype.getStencilBuffer = function () {
  12677. return this._stencilState.stencilTest;
  12678. };
  12679. /**
  12680. * Enable or disable the stencil buffer
  12681. * @param enable defines if the stencil buffer must be enabled or disabled
  12682. */
  12683. Engine.prototype.setStencilBuffer = function (enable) {
  12684. this._stencilState.stencilTest = enable;
  12685. };
  12686. /**
  12687. * Gets the current stencil mask
  12688. * @returns a number defining the new stencil mask to use
  12689. */
  12690. Engine.prototype.getStencilMask = function () {
  12691. return this._stencilState.stencilMask;
  12692. };
  12693. /**
  12694. * Sets the current stencil mask
  12695. * @param mask defines the new stencil mask to use
  12696. */
  12697. Engine.prototype.setStencilMask = function (mask) {
  12698. this._stencilState.stencilMask = mask;
  12699. };
  12700. /**
  12701. * Gets the current stencil function
  12702. * @returns a number defining the stencil function to use
  12703. */
  12704. Engine.prototype.getStencilFunction = function () {
  12705. return this._stencilState.stencilFunc;
  12706. };
  12707. /**
  12708. * Gets the current stencil reference value
  12709. * @returns a number defining the stencil reference value to use
  12710. */
  12711. Engine.prototype.getStencilFunctionReference = function () {
  12712. return this._stencilState.stencilFuncRef;
  12713. };
  12714. /**
  12715. * Gets the current stencil mask
  12716. * @returns a number defining the stencil mask to use
  12717. */
  12718. Engine.prototype.getStencilFunctionMask = function () {
  12719. return this._stencilState.stencilFuncMask;
  12720. };
  12721. /**
  12722. * Sets the current stencil function
  12723. * @param stencilFunc defines the new stencil function to use
  12724. */
  12725. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12726. this._stencilState.stencilFunc = stencilFunc;
  12727. };
  12728. /**
  12729. * Sets the current stencil reference
  12730. * @param reference defines the new stencil reference to use
  12731. */
  12732. Engine.prototype.setStencilFunctionReference = function (reference) {
  12733. this._stencilState.stencilFuncRef = reference;
  12734. };
  12735. /**
  12736. * Sets the current stencil mask
  12737. * @param mask defines the new stencil mask to use
  12738. */
  12739. Engine.prototype.setStencilFunctionMask = function (mask) {
  12740. this._stencilState.stencilFuncMask = mask;
  12741. };
  12742. /**
  12743. * Gets the current stencil operation when stencil fails
  12744. * @returns a number defining stencil operation to use when stencil fails
  12745. */
  12746. Engine.prototype.getStencilOperationFail = function () {
  12747. return this._stencilState.stencilOpStencilFail;
  12748. };
  12749. /**
  12750. * Gets the current stencil operation when depth fails
  12751. * @returns a number defining stencil operation to use when depth fails
  12752. */
  12753. Engine.prototype.getStencilOperationDepthFail = function () {
  12754. return this._stencilState.stencilOpDepthFail;
  12755. };
  12756. /**
  12757. * Gets the current stencil operation when stencil passes
  12758. * @returns a number defining stencil operation to use when stencil passes
  12759. */
  12760. Engine.prototype.getStencilOperationPass = function () {
  12761. return this._stencilState.stencilOpStencilDepthPass;
  12762. };
  12763. /**
  12764. * Sets the stencil operation to use when stencil fails
  12765. * @param operation defines the stencil operation to use when stencil fails
  12766. */
  12767. Engine.prototype.setStencilOperationFail = function (operation) {
  12768. this._stencilState.stencilOpStencilFail = operation;
  12769. };
  12770. /**
  12771. * Sets the stencil operation to use when depth fails
  12772. * @param operation defines the stencil operation to use when depth fails
  12773. */
  12774. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12775. this._stencilState.stencilOpDepthFail = operation;
  12776. };
  12777. /**
  12778. * Sets the stencil operation to use when stencil passes
  12779. * @param operation defines the stencil operation to use when stencil passes
  12780. */
  12781. Engine.prototype.setStencilOperationPass = function (operation) {
  12782. this._stencilState.stencilOpStencilDepthPass = operation;
  12783. };
  12784. /**
  12785. * Sets a boolean indicating if the dithering state is enabled or disabled
  12786. * @param value defines the dithering state
  12787. */
  12788. Engine.prototype.setDitheringState = function (value) {
  12789. if (value) {
  12790. this._gl.enable(this._gl.DITHER);
  12791. }
  12792. else {
  12793. this._gl.disable(this._gl.DITHER);
  12794. }
  12795. };
  12796. /**
  12797. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12798. * @param value defines the rasterizer state
  12799. */
  12800. Engine.prototype.setRasterizerState = function (value) {
  12801. if (value) {
  12802. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12803. }
  12804. else {
  12805. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12806. }
  12807. };
  12808. /**
  12809. * stop executing a render loop function and remove it from the execution array
  12810. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12811. */
  12812. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12813. if (!renderFunction) {
  12814. this._activeRenderLoops = [];
  12815. return;
  12816. }
  12817. var index = this._activeRenderLoops.indexOf(renderFunction);
  12818. if (index >= 0) {
  12819. this._activeRenderLoops.splice(index, 1);
  12820. }
  12821. };
  12822. /** @hidden */
  12823. Engine.prototype._renderLoop = function () {
  12824. if (!this._contextWasLost) {
  12825. var shouldRender = true;
  12826. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12827. shouldRender = false;
  12828. }
  12829. if (shouldRender) {
  12830. // Start new frame
  12831. this.beginFrame();
  12832. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12833. var renderFunction = this._activeRenderLoops[index];
  12834. renderFunction();
  12835. }
  12836. // Present
  12837. this.endFrame();
  12838. }
  12839. }
  12840. if (this._activeRenderLoops.length > 0) {
  12841. // Register new frame
  12842. var requester = null;
  12843. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12844. requester = this._vrDisplay;
  12845. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12846. }
  12847. else {
  12848. this._renderingQueueLaunched = false;
  12849. }
  12850. };
  12851. /**
  12852. * Register and execute a render loop. The engine can have more than one render function
  12853. * @param renderFunction defines the function to continuously execute
  12854. */
  12855. Engine.prototype.runRenderLoop = function (renderFunction) {
  12856. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12857. return;
  12858. }
  12859. this._activeRenderLoops.push(renderFunction);
  12860. if (!this._renderingQueueLaunched) {
  12861. this._renderingQueueLaunched = true;
  12862. this._bindedRenderFunction = this._renderLoop.bind(this);
  12863. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12864. }
  12865. };
  12866. /**
  12867. * Toggle full screen mode
  12868. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12869. * @param options defines an option object to be sent to the requestFullscreen function
  12870. */
  12871. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12872. if (this.isFullscreen) {
  12873. BABYLON.Tools.ExitFullscreen();
  12874. }
  12875. else {
  12876. this._pointerLockRequested = requestPointerLock;
  12877. if (this._renderingCanvas) {
  12878. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12879. }
  12880. }
  12881. };
  12882. /**
  12883. * Clear the current render buffer or the current render target (if any is set up)
  12884. * @param color defines the color to use
  12885. * @param backBuffer defines if the back buffer must be cleared
  12886. * @param depth defines if the depth buffer must be cleared
  12887. * @param stencil defines if the stencil buffer must be cleared
  12888. */
  12889. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12890. if (stencil === void 0) { stencil = false; }
  12891. this.applyStates();
  12892. var mode = 0;
  12893. if (backBuffer && color) {
  12894. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12895. mode |= this._gl.COLOR_BUFFER_BIT;
  12896. }
  12897. if (depth) {
  12898. this._gl.clearDepth(1.0);
  12899. mode |= this._gl.DEPTH_BUFFER_BIT;
  12900. }
  12901. if (stencil) {
  12902. this._gl.clearStencil(0);
  12903. mode |= this._gl.STENCIL_BUFFER_BIT;
  12904. }
  12905. this._gl.clear(mode);
  12906. };
  12907. /**
  12908. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12909. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12910. * @param y defines the y-coordinate of the corner of the clear rectangle
  12911. * @param width defines the width of the clear rectangle
  12912. * @param height defines the height of the clear rectangle
  12913. * @param clearColor defines the clear color
  12914. */
  12915. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12916. var gl = this._gl;
  12917. // Save state
  12918. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12919. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12920. // Change state
  12921. gl.enable(gl.SCISSOR_TEST);
  12922. gl.scissor(x, y, width, height);
  12923. // Clear
  12924. this.clear(clearColor, true, true, true);
  12925. // Restore state
  12926. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12927. if (curScissor === true) {
  12928. gl.enable(gl.SCISSOR_TEST);
  12929. }
  12930. else {
  12931. gl.disable(gl.SCISSOR_TEST);
  12932. }
  12933. };
  12934. /**
  12935. * Set the WebGL's viewport
  12936. * @param viewport defines the viewport element to be used
  12937. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12938. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12939. */
  12940. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12941. var width = requiredWidth || this.getRenderWidth();
  12942. var height = requiredHeight || this.getRenderHeight();
  12943. var x = viewport.x || 0;
  12944. var y = viewport.y || 0;
  12945. this._cachedViewport = viewport;
  12946. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12947. };
  12948. /**
  12949. * Directly set the WebGL Viewport
  12950. * @param x defines the x coordinate of the viewport (in screen space)
  12951. * @param y defines the y coordinate of the viewport (in screen space)
  12952. * @param width defines the width of the viewport (in screen space)
  12953. * @param height defines the height of the viewport (in screen space)
  12954. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  12955. */
  12956. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12957. var currentViewport = this._cachedViewport;
  12958. this._cachedViewport = null;
  12959. this._gl.viewport(x, y, width, height);
  12960. return currentViewport;
  12961. };
  12962. /**
  12963. * Begin a new frame
  12964. */
  12965. Engine.prototype.beginFrame = function () {
  12966. this.onBeginFrameObservable.notifyObservers(this);
  12967. this._measureFps();
  12968. };
  12969. /**
  12970. * Enf the current frame
  12971. */
  12972. Engine.prototype.endFrame = function () {
  12973. // Force a flush in case we are using a bad OS.
  12974. if (this._badOS) {
  12975. this.flushFramebuffer();
  12976. }
  12977. // Submit frame to the vr device, if enabled
  12978. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12979. // TODO: We should only submit the frame if we read frameData successfully.
  12980. this._vrDisplay.submitFrame();
  12981. }
  12982. this.onEndFrameObservable.notifyObservers(this);
  12983. };
  12984. /**
  12985. * Resize the view according to the canvas' size
  12986. */
  12987. Engine.prototype.resize = function () {
  12988. // We're not resizing the size of the canvas while in VR mode & presenting
  12989. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12990. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12991. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12992. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12993. }
  12994. };
  12995. /**
  12996. * Force a specific size of the canvas
  12997. * @param width defines the new canvas' width
  12998. * @param height defines the new canvas' height
  12999. */
  13000. Engine.prototype.setSize = function (width, height) {
  13001. if (!this._renderingCanvas) {
  13002. return;
  13003. }
  13004. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13005. return;
  13006. }
  13007. this._renderingCanvas.width = width;
  13008. this._renderingCanvas.height = height;
  13009. for (var index = 0; index < this.scenes.length; index++) {
  13010. var scene = this.scenes[index];
  13011. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13012. var cam = scene.cameras[camIndex];
  13013. cam._currentRenderId = 0;
  13014. }
  13015. }
  13016. if (this.onResizeObservable.hasObservers) {
  13017. this.onResizeObservable.notifyObservers(this);
  13018. }
  13019. };
  13020. // WebVR functions
  13021. /**
  13022. * Gets a boolean indicating if a webVR device was detected
  13023. * @returns true if a webVR device was detected
  13024. */
  13025. Engine.prototype.isVRDevicePresent = function () {
  13026. return !!this._vrDisplay;
  13027. };
  13028. /**
  13029. * Gets the current webVR device
  13030. * @returns the current webVR device (or null)
  13031. */
  13032. Engine.prototype.getVRDevice = function () {
  13033. return this._vrDisplay;
  13034. };
  13035. /**
  13036. * Initializes a webVR display and starts listening to display change events
  13037. * The onVRDisplayChangedObservable will be notified upon these changes
  13038. * @returns The onVRDisplayChangedObservable
  13039. */
  13040. Engine.prototype.initWebVR = function () {
  13041. this.initWebVRAsync();
  13042. return this.onVRDisplayChangedObservable;
  13043. };
  13044. /**
  13045. * Initializes a webVR display and starts listening to display change events
  13046. * The onVRDisplayChangedObservable will be notified upon these changes
  13047. * @returns A promise containing a VRDisplay and if vr is supported
  13048. */
  13049. Engine.prototype.initWebVRAsync = function () {
  13050. var _this = this;
  13051. var notifyObservers = function () {
  13052. var eventArgs = {
  13053. vrDisplay: _this._vrDisplay,
  13054. vrSupported: _this._vrSupported
  13055. };
  13056. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13057. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13058. };
  13059. if (!this._onVrDisplayConnect) {
  13060. this._onVrDisplayConnect = function (event) {
  13061. _this._vrDisplay = event.display;
  13062. notifyObservers();
  13063. };
  13064. this._onVrDisplayDisconnect = function () {
  13065. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13066. _this._vrDisplay = undefined;
  13067. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13068. notifyObservers();
  13069. };
  13070. this._onVrDisplayPresentChange = function () {
  13071. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13072. };
  13073. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13074. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13075. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13076. }
  13077. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13078. this._webVRInitPromise.then(notifyObservers);
  13079. return this._webVRInitPromise;
  13080. };
  13081. /**
  13082. * Call this function to switch to webVR mode
  13083. * Will do nothing if webVR is not supported or if there is no webVR device
  13084. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13085. */
  13086. Engine.prototype.enableVR = function () {
  13087. var _this = this;
  13088. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13089. var onResolved = function () {
  13090. _this.onVRRequestPresentComplete.notifyObservers(true);
  13091. _this._onVRFullScreenTriggered();
  13092. };
  13093. var onRejected = function () {
  13094. _this.onVRRequestPresentComplete.notifyObservers(false);
  13095. };
  13096. this.onVRRequestPresentStart.notifyObservers(this);
  13097. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13098. }
  13099. };
  13100. /**
  13101. * Call this function to leave webVR mode
  13102. * Will do nothing if webVR is not supported or if there is no webVR device
  13103. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13104. */
  13105. Engine.prototype.disableVR = function () {
  13106. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13107. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13108. }
  13109. };
  13110. Engine.prototype._getVRDisplaysAsync = function () {
  13111. var _this = this;
  13112. return new Promise(function (res, rej) {
  13113. if (navigator.getVRDisplays) {
  13114. navigator.getVRDisplays().then(function (devices) {
  13115. _this._vrSupported = true;
  13116. // note that devices may actually be an empty array. This is fine;
  13117. // we expect this._vrDisplay to be undefined in this case.
  13118. _this._vrDisplay = devices[0];
  13119. res({
  13120. vrDisplay: _this._vrDisplay,
  13121. vrSupported: _this._vrSupported
  13122. });
  13123. });
  13124. }
  13125. else {
  13126. _this._vrDisplay = undefined;
  13127. _this._vrSupported = false;
  13128. res({
  13129. vrDisplay: _this._vrDisplay,
  13130. vrSupported: _this._vrSupported
  13131. });
  13132. }
  13133. });
  13134. };
  13135. /**
  13136. * Binds the frame buffer to the specified texture.
  13137. * @param texture The texture to render to or null for the default canvas
  13138. * @param faceIndex The face of the texture to render to in case of cube texture
  13139. * @param requiredWidth The width of the target to render to
  13140. * @param requiredHeight The height of the target to render to
  13141. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13142. * @param depthStencilTexture The depth stencil texture to use to render
  13143. * @param lodLevel defines le lod level to bind to the frame buffer
  13144. */
  13145. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13146. if (lodLevel === void 0) { lodLevel = 0; }
  13147. if (this._currentRenderTarget) {
  13148. this.unBindFramebuffer(this._currentRenderTarget);
  13149. }
  13150. this._currentRenderTarget = texture;
  13151. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13152. var gl = this._gl;
  13153. if (texture.isCube) {
  13154. if (faceIndex === undefined) {
  13155. faceIndex = 0;
  13156. }
  13157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13158. if (depthStencilTexture) {
  13159. if (depthStencilTexture._generateStencilBuffer) {
  13160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13161. }
  13162. else {
  13163. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13164. }
  13165. }
  13166. }
  13167. if (this._cachedViewport && !forceFullscreenViewport) {
  13168. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13169. }
  13170. else {
  13171. if (!requiredWidth) {
  13172. requiredWidth = texture.width;
  13173. if (lodLevel) {
  13174. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13175. }
  13176. }
  13177. if (!requiredHeight) {
  13178. requiredHeight = texture.height;
  13179. if (lodLevel) {
  13180. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13181. }
  13182. }
  13183. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13184. }
  13185. this.wipeCaches();
  13186. };
  13187. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13188. if (this._currentFramebuffer !== framebuffer) {
  13189. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13190. this._currentFramebuffer = framebuffer;
  13191. }
  13192. };
  13193. /**
  13194. * Unbind the current render target texture from the webGL context
  13195. * @param texture defines the render target texture to unbind
  13196. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13197. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13198. */
  13199. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13200. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13201. this._currentRenderTarget = null;
  13202. // If MSAA, we need to bitblt back to main texture
  13203. var gl = this._gl;
  13204. if (texture._MSAAFramebuffer) {
  13205. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13206. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13207. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13208. }
  13209. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13210. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13211. gl.generateMipmap(gl.TEXTURE_2D);
  13212. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13213. }
  13214. if (onBeforeUnbind) {
  13215. if (texture._MSAAFramebuffer) {
  13216. // Bind the correct framebuffer
  13217. this.bindUnboundFramebuffer(texture._framebuffer);
  13218. }
  13219. onBeforeUnbind();
  13220. }
  13221. this.bindUnboundFramebuffer(null);
  13222. };
  13223. /**
  13224. * Unbind a list of render target textures from the webGL context
  13225. * This is used only when drawBuffer extension or webGL2 are active
  13226. * @param textures defines the render target textures to unbind
  13227. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13228. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13229. */
  13230. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13231. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13232. this._currentRenderTarget = null;
  13233. // If MSAA, we need to bitblt back to main texture
  13234. var gl = this._gl;
  13235. if (textures[0]._MSAAFramebuffer) {
  13236. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13237. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13238. var attachments = textures[0]._attachments;
  13239. if (!attachments) {
  13240. attachments = new Array(textures.length);
  13241. textures[0]._attachments = attachments;
  13242. }
  13243. for (var i = 0; i < textures.length; i++) {
  13244. var texture = textures[i];
  13245. for (var j = 0; j < attachments.length; j++) {
  13246. attachments[j] = gl.NONE;
  13247. }
  13248. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13249. gl.readBuffer(attachments[i]);
  13250. gl.drawBuffers(attachments);
  13251. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13252. }
  13253. for (var i = 0; i < attachments.length; i++) {
  13254. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13255. }
  13256. gl.drawBuffers(attachments);
  13257. }
  13258. for (var i = 0; i < textures.length; i++) {
  13259. var texture = textures[i];
  13260. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13261. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13262. gl.generateMipmap(gl.TEXTURE_2D);
  13263. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13264. }
  13265. }
  13266. if (onBeforeUnbind) {
  13267. if (textures[0]._MSAAFramebuffer) {
  13268. // Bind the correct framebuffer
  13269. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13270. }
  13271. onBeforeUnbind();
  13272. }
  13273. this.bindUnboundFramebuffer(null);
  13274. };
  13275. /**
  13276. * Force the mipmap generation for the given render target texture
  13277. * @param texture defines the render target texture to use
  13278. */
  13279. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13280. if (texture.generateMipMaps) {
  13281. var gl = this._gl;
  13282. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13283. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13284. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13285. }
  13286. };
  13287. /**
  13288. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13289. */
  13290. Engine.prototype.flushFramebuffer = function () {
  13291. this._gl.flush();
  13292. };
  13293. /**
  13294. * Unbind the current render target and bind the default framebuffer
  13295. */
  13296. Engine.prototype.restoreDefaultFramebuffer = function () {
  13297. if (this._currentRenderTarget) {
  13298. this.unBindFramebuffer(this._currentRenderTarget);
  13299. }
  13300. else {
  13301. this.bindUnboundFramebuffer(null);
  13302. }
  13303. if (this._cachedViewport) {
  13304. this.setViewport(this._cachedViewport);
  13305. }
  13306. this.wipeCaches();
  13307. };
  13308. // UBOs
  13309. /**
  13310. * Create an uniform buffer
  13311. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13312. * @param elements defines the content of the uniform buffer
  13313. * @returns the webGL uniform buffer
  13314. */
  13315. Engine.prototype.createUniformBuffer = function (elements) {
  13316. var ubo = this._gl.createBuffer();
  13317. if (!ubo) {
  13318. throw new Error("Unable to create uniform buffer");
  13319. }
  13320. this.bindUniformBuffer(ubo);
  13321. if (elements instanceof Float32Array) {
  13322. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13323. }
  13324. else {
  13325. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13326. }
  13327. this.bindUniformBuffer(null);
  13328. ubo.references = 1;
  13329. return ubo;
  13330. };
  13331. /**
  13332. * Create a dynamic uniform buffer
  13333. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13334. * @param elements defines the content of the uniform buffer
  13335. * @returns the webGL uniform buffer
  13336. */
  13337. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13338. var ubo = this._gl.createBuffer();
  13339. if (!ubo) {
  13340. throw new Error("Unable to create dynamic uniform buffer");
  13341. }
  13342. this.bindUniformBuffer(ubo);
  13343. if (elements instanceof Float32Array) {
  13344. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13345. }
  13346. else {
  13347. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13348. }
  13349. this.bindUniformBuffer(null);
  13350. ubo.references = 1;
  13351. return ubo;
  13352. };
  13353. /**
  13354. * Update an existing uniform buffer
  13355. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13356. * @param uniformBuffer defines the target uniform buffer
  13357. * @param elements defines the content to update
  13358. * @param offset defines the offset in the uniform buffer where update should start
  13359. * @param count defines the size of the data to update
  13360. */
  13361. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13362. this.bindUniformBuffer(uniformBuffer);
  13363. if (offset === undefined) {
  13364. offset = 0;
  13365. }
  13366. if (count === undefined) {
  13367. if (elements instanceof Float32Array) {
  13368. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13369. }
  13370. else {
  13371. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13372. }
  13373. }
  13374. else {
  13375. if (elements instanceof Float32Array) {
  13376. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13377. }
  13378. else {
  13379. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13380. }
  13381. }
  13382. this.bindUniformBuffer(null);
  13383. };
  13384. // VBOs
  13385. Engine.prototype._resetVertexBufferBinding = function () {
  13386. this.bindArrayBuffer(null);
  13387. this._cachedVertexBuffers = null;
  13388. };
  13389. /**
  13390. * Creates a vertex buffer
  13391. * @param data the data for the vertex buffer
  13392. * @returns the new WebGL static buffer
  13393. */
  13394. Engine.prototype.createVertexBuffer = function (data) {
  13395. var vbo = this._gl.createBuffer();
  13396. if (!vbo) {
  13397. throw new Error("Unable to create vertex buffer");
  13398. }
  13399. this.bindArrayBuffer(vbo);
  13400. if (data instanceof Array) {
  13401. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13402. }
  13403. else {
  13404. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13405. }
  13406. this._resetVertexBufferBinding();
  13407. vbo.references = 1;
  13408. return vbo;
  13409. };
  13410. /**
  13411. * Creates a dynamic vertex buffer
  13412. * @param data the data for the dynamic vertex buffer
  13413. * @returns the new WebGL dynamic buffer
  13414. */
  13415. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13416. var vbo = this._gl.createBuffer();
  13417. if (!vbo) {
  13418. throw new Error("Unable to create dynamic vertex buffer");
  13419. }
  13420. this.bindArrayBuffer(vbo);
  13421. if (data instanceof Array) {
  13422. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13423. }
  13424. else {
  13425. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13426. }
  13427. this._resetVertexBufferBinding();
  13428. vbo.references = 1;
  13429. return vbo;
  13430. };
  13431. /**
  13432. * Update a dynamic index buffer
  13433. * @param indexBuffer defines the target index buffer
  13434. * @param indices defines the data to update
  13435. * @param offset defines the offset in the target index buffer where update should start
  13436. */
  13437. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13438. if (offset === void 0) { offset = 0; }
  13439. // Force cache update
  13440. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13441. this.bindIndexBuffer(indexBuffer);
  13442. var arrayBuffer;
  13443. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13444. arrayBuffer = indices;
  13445. }
  13446. else {
  13447. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13448. }
  13449. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13450. this._resetIndexBufferBinding();
  13451. };
  13452. /**
  13453. * Updates a dynamic vertex buffer.
  13454. * @param vertexBuffer the vertex buffer to update
  13455. * @param data the data used to update the vertex buffer
  13456. * @param byteOffset the byte offset of the data
  13457. * @param byteLength the byte length of the data
  13458. */
  13459. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13460. this.bindArrayBuffer(vertexBuffer);
  13461. if (byteOffset === undefined) {
  13462. byteOffset = 0;
  13463. }
  13464. if (byteLength === undefined) {
  13465. if (data instanceof Array) {
  13466. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13467. }
  13468. else {
  13469. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13470. }
  13471. }
  13472. else {
  13473. if (data instanceof Array) {
  13474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13475. }
  13476. else {
  13477. if (data instanceof ArrayBuffer) {
  13478. data = new Uint8Array(data, byteOffset, byteLength);
  13479. }
  13480. else {
  13481. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13482. }
  13483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13484. }
  13485. }
  13486. this._resetVertexBufferBinding();
  13487. };
  13488. Engine.prototype._resetIndexBufferBinding = function () {
  13489. this.bindIndexBuffer(null);
  13490. this._cachedIndexBuffer = null;
  13491. };
  13492. /**
  13493. * Creates a new index buffer
  13494. * @param indices defines the content of the index buffer
  13495. * @param updatable defines if the index buffer must be updatable
  13496. * @returns a new webGL buffer
  13497. */
  13498. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13499. var vbo = this._gl.createBuffer();
  13500. if (!vbo) {
  13501. throw new Error("Unable to create index buffer");
  13502. }
  13503. this.bindIndexBuffer(vbo);
  13504. // Check for 32 bits indices
  13505. var arrayBuffer;
  13506. var need32Bits = false;
  13507. if (indices instanceof Uint16Array) {
  13508. arrayBuffer = indices;
  13509. }
  13510. else {
  13511. //check 32 bit support
  13512. if (this._caps.uintIndices) {
  13513. if (indices instanceof Uint32Array) {
  13514. arrayBuffer = indices;
  13515. need32Bits = true;
  13516. }
  13517. else {
  13518. //number[] or Int32Array, check if 32 bit is necessary
  13519. for (var index = 0; index < indices.length; index++) {
  13520. if (indices[index] > 65535) {
  13521. need32Bits = true;
  13522. break;
  13523. }
  13524. }
  13525. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13526. }
  13527. }
  13528. else {
  13529. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13530. arrayBuffer = new Uint16Array(indices);
  13531. }
  13532. }
  13533. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13534. this._resetIndexBufferBinding();
  13535. vbo.references = 1;
  13536. vbo.is32Bits = need32Bits;
  13537. return vbo;
  13538. };
  13539. /**
  13540. * Bind a webGL buffer to the webGL context
  13541. * @param buffer defines the buffer to bind
  13542. */
  13543. Engine.prototype.bindArrayBuffer = function (buffer) {
  13544. if (!this._vaoRecordInProgress) {
  13545. this._unbindVertexArrayObject();
  13546. }
  13547. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13548. };
  13549. /**
  13550. * Bind an uniform buffer to the current webGL context
  13551. * @param buffer defines the buffer to bind
  13552. */
  13553. Engine.prototype.bindUniformBuffer = function (buffer) {
  13554. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13555. };
  13556. /**
  13557. * Bind a buffer to the current webGL context at a given location
  13558. * @param buffer defines the buffer to bind
  13559. * @param location defines the index where to bind the buffer
  13560. */
  13561. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13562. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13563. };
  13564. /**
  13565. * Bind a specific block at a given index in a specific shader program
  13566. * @param shaderProgram defines the shader program
  13567. * @param blockName defines the block name
  13568. * @param index defines the index where to bind the block
  13569. */
  13570. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13571. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13572. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13573. };
  13574. ;
  13575. Engine.prototype.bindIndexBuffer = function (buffer) {
  13576. if (!this._vaoRecordInProgress) {
  13577. this._unbindVertexArrayObject();
  13578. }
  13579. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13580. };
  13581. Engine.prototype.bindBuffer = function (buffer, target) {
  13582. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13583. this._gl.bindBuffer(target, buffer);
  13584. this._currentBoundBuffer[target] = buffer;
  13585. }
  13586. };
  13587. /**
  13588. * update the bound buffer with the given data
  13589. * @param data defines the data to update
  13590. */
  13591. Engine.prototype.updateArrayBuffer = function (data) {
  13592. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13593. };
  13594. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13595. var pointer = this._currentBufferPointers[indx];
  13596. var changed = false;
  13597. if (!pointer.active) {
  13598. changed = true;
  13599. pointer.active = true;
  13600. pointer.index = indx;
  13601. pointer.size = size;
  13602. pointer.type = type;
  13603. pointer.normalized = normalized;
  13604. pointer.stride = stride;
  13605. pointer.offset = offset;
  13606. pointer.buffer = buffer;
  13607. }
  13608. else {
  13609. if (pointer.buffer !== buffer) {
  13610. pointer.buffer = buffer;
  13611. changed = true;
  13612. }
  13613. if (pointer.size !== size) {
  13614. pointer.size = size;
  13615. changed = true;
  13616. }
  13617. if (pointer.type !== type) {
  13618. pointer.type = type;
  13619. changed = true;
  13620. }
  13621. if (pointer.normalized !== normalized) {
  13622. pointer.normalized = normalized;
  13623. changed = true;
  13624. }
  13625. if (pointer.stride !== stride) {
  13626. pointer.stride = stride;
  13627. changed = true;
  13628. }
  13629. if (pointer.offset !== offset) {
  13630. pointer.offset = offset;
  13631. changed = true;
  13632. }
  13633. }
  13634. if (changed || this._vaoRecordInProgress) {
  13635. this.bindArrayBuffer(buffer);
  13636. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13637. }
  13638. };
  13639. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13640. if (indexBuffer == null) {
  13641. return;
  13642. }
  13643. if (this._cachedIndexBuffer !== indexBuffer) {
  13644. this._cachedIndexBuffer = indexBuffer;
  13645. this.bindIndexBuffer(indexBuffer);
  13646. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13647. }
  13648. };
  13649. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13650. var attributes = effect.getAttributesNames();
  13651. if (!this._vaoRecordInProgress) {
  13652. this._unbindVertexArrayObject();
  13653. }
  13654. this.unbindAllAttributes();
  13655. for (var index = 0; index < attributes.length; index++) {
  13656. var order = effect.getAttributeLocation(index);
  13657. if (order >= 0) {
  13658. var vertexBuffer = vertexBuffers[attributes[index]];
  13659. if (!vertexBuffer) {
  13660. continue;
  13661. }
  13662. this._gl.enableVertexAttribArray(order);
  13663. if (!this._vaoRecordInProgress) {
  13664. this._vertexAttribArraysEnabled[order] = true;
  13665. }
  13666. var buffer = vertexBuffer.getBuffer();
  13667. if (buffer) {
  13668. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13669. if (vertexBuffer.getIsInstanced()) {
  13670. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13671. if (!this._vaoRecordInProgress) {
  13672. this._currentInstanceLocations.push(order);
  13673. this._currentInstanceBuffers.push(buffer);
  13674. }
  13675. }
  13676. }
  13677. }
  13678. }
  13679. };
  13680. /**
  13681. * Records a vertex array object
  13682. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13683. * @param vertexBuffers defines the list of vertex buffers to store
  13684. * @param indexBuffer defines the index buffer to store
  13685. * @param effect defines the effect to store
  13686. * @returns the new vertex array object
  13687. */
  13688. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13689. var vao = this._gl.createVertexArray();
  13690. this._vaoRecordInProgress = true;
  13691. this._gl.bindVertexArray(vao);
  13692. this._mustWipeVertexAttributes = true;
  13693. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13694. this.bindIndexBuffer(indexBuffer);
  13695. this._vaoRecordInProgress = false;
  13696. this._gl.bindVertexArray(null);
  13697. return vao;
  13698. };
  13699. /**
  13700. * Bind a specific vertex array object
  13701. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13702. * @param vertexArrayObject defines the vertex array object to bind
  13703. * @param indexBuffer defines the index buffer to bind
  13704. */
  13705. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13706. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13707. this._cachedVertexArrayObject = vertexArrayObject;
  13708. this._gl.bindVertexArray(vertexArrayObject);
  13709. this._cachedVertexBuffers = null;
  13710. this._cachedIndexBuffer = null;
  13711. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13712. this._mustWipeVertexAttributes = true;
  13713. }
  13714. };
  13715. /**
  13716. * Bind webGl buffers directly to the webGL context
  13717. * @param vertexBuffer defines the vertex buffer to bind
  13718. * @param indexBuffer defines the index buffer to bind
  13719. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13720. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13721. * @param effect defines the effect associated with the vertex buffer
  13722. */
  13723. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13724. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13725. this._cachedVertexBuffers = vertexBuffer;
  13726. this._cachedEffectForVertexBuffers = effect;
  13727. var attributesCount = effect.getAttributesCount();
  13728. this._unbindVertexArrayObject();
  13729. this.unbindAllAttributes();
  13730. var offset = 0;
  13731. for (var index = 0; index < attributesCount; index++) {
  13732. if (index < vertexDeclaration.length) {
  13733. var order = effect.getAttributeLocation(index);
  13734. if (order >= 0) {
  13735. this._gl.enableVertexAttribArray(order);
  13736. this._vertexAttribArraysEnabled[order] = true;
  13737. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13738. }
  13739. offset += vertexDeclaration[index] * 4;
  13740. }
  13741. }
  13742. }
  13743. this._bindIndexBufferWithCache(indexBuffer);
  13744. };
  13745. Engine.prototype._unbindVertexArrayObject = function () {
  13746. if (!this._cachedVertexArrayObject) {
  13747. return;
  13748. }
  13749. this._cachedVertexArrayObject = null;
  13750. this._gl.bindVertexArray(null);
  13751. };
  13752. /**
  13753. * Bind a list of vertex buffers to the webGL context
  13754. * @param vertexBuffers defines the list of vertex buffers to bind
  13755. * @param indexBuffer defines the index buffer to bind
  13756. * @param effect defines the effect associated with the vertex buffers
  13757. */
  13758. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13759. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13760. this._cachedVertexBuffers = vertexBuffers;
  13761. this._cachedEffectForVertexBuffers = effect;
  13762. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13763. }
  13764. this._bindIndexBufferWithCache(indexBuffer);
  13765. };
  13766. /**
  13767. * Unbind all instance attributes
  13768. */
  13769. Engine.prototype.unbindInstanceAttributes = function () {
  13770. var boundBuffer;
  13771. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13772. var instancesBuffer = this._currentInstanceBuffers[i];
  13773. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13774. boundBuffer = instancesBuffer;
  13775. this.bindArrayBuffer(instancesBuffer);
  13776. }
  13777. var offsetLocation = this._currentInstanceLocations[i];
  13778. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13779. }
  13780. this._currentInstanceBuffers.length = 0;
  13781. this._currentInstanceLocations.length = 0;
  13782. };
  13783. /**
  13784. * Release and free the memory of a vertex array object
  13785. * @param vao defines the vertex array object to delete
  13786. */
  13787. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13788. this._gl.deleteVertexArray(vao);
  13789. };
  13790. /** @hidden */
  13791. Engine.prototype._releaseBuffer = function (buffer) {
  13792. buffer.references--;
  13793. if (buffer.references === 0) {
  13794. this._gl.deleteBuffer(buffer);
  13795. return true;
  13796. }
  13797. return false;
  13798. };
  13799. /**
  13800. * Creates a webGL buffer to use with instanciation
  13801. * @param capacity defines the size of the buffer
  13802. * @returns the webGL buffer
  13803. */
  13804. Engine.prototype.createInstancesBuffer = function (capacity) {
  13805. var buffer = this._gl.createBuffer();
  13806. if (!buffer) {
  13807. throw new Error("Unable to create instance buffer");
  13808. }
  13809. buffer.capacity = capacity;
  13810. this.bindArrayBuffer(buffer);
  13811. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13812. return buffer;
  13813. };
  13814. /**
  13815. * Delete a webGL buffer used with instanciation
  13816. * @param buffer defines the webGL buffer to delete
  13817. */
  13818. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13819. this._gl.deleteBuffer(buffer);
  13820. };
  13821. /**
  13822. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13823. * @param instancesBuffer defines the webGL buffer to update and bind
  13824. * @param data defines the data to store in the buffer
  13825. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13826. */
  13827. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13828. this.bindArrayBuffer(instancesBuffer);
  13829. if (data) {
  13830. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13831. }
  13832. if (offsetLocations[0].index !== undefined) {
  13833. var stride = 0;
  13834. for (var i = 0; i < offsetLocations.length; i++) {
  13835. var ai = offsetLocations[i];
  13836. stride += ai.attributeSize * 4;
  13837. }
  13838. for (var i = 0; i < offsetLocations.length; i++) {
  13839. var ai = offsetLocations[i];
  13840. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13841. this._gl.enableVertexAttribArray(ai.index);
  13842. this._vertexAttribArraysEnabled[ai.index] = true;
  13843. }
  13844. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13845. this._gl.vertexAttribDivisor(ai.index, 1);
  13846. this._currentInstanceLocations.push(ai.index);
  13847. this._currentInstanceBuffers.push(instancesBuffer);
  13848. }
  13849. }
  13850. else {
  13851. for (var index = 0; index < 4; index++) {
  13852. var offsetLocation = offsetLocations[index];
  13853. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13854. this._gl.enableVertexAttribArray(offsetLocation);
  13855. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13856. }
  13857. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13858. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13859. this._currentInstanceLocations.push(offsetLocation);
  13860. this._currentInstanceBuffers.push(instancesBuffer);
  13861. }
  13862. }
  13863. };
  13864. /**
  13865. * Apply all cached states (depth, culling, stencil and alpha)
  13866. */
  13867. Engine.prototype.applyStates = function () {
  13868. this._depthCullingState.apply(this._gl);
  13869. this._stencilState.apply(this._gl);
  13870. this._alphaState.apply(this._gl);
  13871. };
  13872. /**
  13873. * Send a draw order
  13874. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13875. * @param indexStart defines the starting index
  13876. * @param indexCount defines the number of index to draw
  13877. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13878. */
  13879. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13880. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13881. };
  13882. /**
  13883. * Draw a list of points
  13884. * @param verticesStart defines the index of first vertex to draw
  13885. * @param verticesCount defines the count of vertices to draw
  13886. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13887. */
  13888. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13889. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13890. };
  13891. /**
  13892. * Draw a list of unindexed primitives
  13893. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13894. * @param verticesStart defines the index of first vertex to draw
  13895. * @param verticesCount defines the count of vertices to draw
  13896. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13897. */
  13898. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13899. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13900. };
  13901. /**
  13902. * Draw a list of indexed primitives
  13903. * @param fillMode defines the primitive to use
  13904. * @param indexStart defines the starting index
  13905. * @param indexCount defines the number of index to draw
  13906. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13907. */
  13908. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13909. // Apply states
  13910. this.applyStates();
  13911. this._drawCalls.addCount(1, false);
  13912. // Render
  13913. var drawMode = this._drawMode(fillMode);
  13914. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13915. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13916. if (instancesCount) {
  13917. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13918. }
  13919. else {
  13920. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13921. }
  13922. };
  13923. /**
  13924. * Draw a list of unindexed primitives
  13925. * @param fillMode defines the primitive to use
  13926. * @param verticesStart defines the index of first vertex to draw
  13927. * @param verticesCount defines the count of vertices to draw
  13928. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13929. */
  13930. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13931. // Apply states
  13932. this.applyStates();
  13933. this._drawCalls.addCount(1, false);
  13934. var drawMode = this._drawMode(fillMode);
  13935. if (instancesCount) {
  13936. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13937. }
  13938. else {
  13939. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13940. }
  13941. };
  13942. Engine.prototype._drawMode = function (fillMode) {
  13943. switch (fillMode) {
  13944. // Triangle views
  13945. case BABYLON.Material.TriangleFillMode:
  13946. return this._gl.TRIANGLES;
  13947. case BABYLON.Material.PointFillMode:
  13948. return this._gl.POINTS;
  13949. case BABYLON.Material.WireFrameFillMode:
  13950. return this._gl.LINES;
  13951. // Draw modes
  13952. case BABYLON.Material.PointListDrawMode:
  13953. return this._gl.POINTS;
  13954. case BABYLON.Material.LineListDrawMode:
  13955. return this._gl.LINES;
  13956. case BABYLON.Material.LineLoopDrawMode:
  13957. return this._gl.LINE_LOOP;
  13958. case BABYLON.Material.LineStripDrawMode:
  13959. return this._gl.LINE_STRIP;
  13960. case BABYLON.Material.TriangleStripDrawMode:
  13961. return this._gl.TRIANGLE_STRIP;
  13962. case BABYLON.Material.TriangleFanDrawMode:
  13963. return this._gl.TRIANGLE_FAN;
  13964. default:
  13965. return this._gl.TRIANGLES;
  13966. }
  13967. };
  13968. // Shaders
  13969. /** @hidden */
  13970. Engine.prototype._releaseEffect = function (effect) {
  13971. if (this._compiledEffects[effect._key]) {
  13972. delete this._compiledEffects[effect._key];
  13973. this._deleteProgram(effect.getProgram());
  13974. }
  13975. };
  13976. /** @hidden */
  13977. Engine.prototype._deleteProgram = function (program) {
  13978. if (program) {
  13979. program.__SPECTOR_rebuildProgram = null;
  13980. if (program.transformFeedback) {
  13981. this.deleteTransformFeedback(program.transformFeedback);
  13982. program.transformFeedback = null;
  13983. }
  13984. this._gl.deleteProgram(program);
  13985. }
  13986. };
  13987. /**
  13988. * Create a new effect (used to store vertex/fragment shaders)
  13989. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13990. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13991. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13992. * @param samplers defines an array of string used to represent textures
  13993. * @param defines defines the string containing the defines to use to compile the shaders
  13994. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13995. * @param onCompiled defines a function to call when the effect creation is successful
  13996. * @param onError defines a function to call when the effect creation has failed
  13997. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13998. * @returns the new Effect
  13999. */
  14000. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14001. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14002. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14003. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14004. if (this._compiledEffects[name]) {
  14005. var compiledEffect = this._compiledEffects[name];
  14006. if (onCompiled && compiledEffect.isReady()) {
  14007. onCompiled(compiledEffect);
  14008. }
  14009. return compiledEffect;
  14010. }
  14011. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14012. effect._key = name;
  14013. this._compiledEffects[name] = effect;
  14014. return effect;
  14015. };
  14016. /**
  14017. * Create an effect to use with particle systems
  14018. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14019. * @param uniformsNames defines a list of attribute names
  14020. * @param samplers defines an array of string used to represent textures
  14021. * @param defines defines the string containing the defines to use to compile the shaders
  14022. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14023. * @param onCompiled defines a function to call when the effect creation is successful
  14024. * @param onError defines a function to call when the effect creation has failed
  14025. * @returns the new Effect
  14026. */
  14027. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14028. if (uniformsNames === void 0) { uniformsNames = []; }
  14029. if (samplers === void 0) { samplers = []; }
  14030. if (defines === void 0) { defines = ""; }
  14031. return this.createEffect({
  14032. vertex: "particles",
  14033. fragmentElement: fragmentName
  14034. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14035. };
  14036. /**
  14037. * Directly creates a webGL program
  14038. * @param vertexCode defines the vertex shader code to use
  14039. * @param fragmentCode defines the fragment shader code to use
  14040. * @param context defines the webGL context to use (if not set, the current one will be used)
  14041. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14042. * @returns the new webGL program
  14043. */
  14044. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14045. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14046. context = context || this._gl;
  14047. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14048. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14049. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14050. };
  14051. /**
  14052. * Creates a webGL program
  14053. * @param vertexCode defines the vertex shader code to use
  14054. * @param fragmentCode defines the fragment shader code to use
  14055. * @param defines defines the string containing the defines to use to compile the shaders
  14056. * @param context defines the webGL context to use (if not set, the current one will be used)
  14057. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14058. * @returns the new webGL program
  14059. */
  14060. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14061. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14062. context = context || this._gl;
  14063. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14064. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14065. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14066. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14067. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14068. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14069. return program;
  14070. };
  14071. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14072. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14073. var shaderProgram = context.createProgram();
  14074. if (!shaderProgram) {
  14075. throw new Error("Unable to create program");
  14076. }
  14077. context.attachShader(shaderProgram, vertexShader);
  14078. context.attachShader(shaderProgram, fragmentShader);
  14079. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14080. var transformFeedback = this.createTransformFeedback();
  14081. this.bindTransformFeedback(transformFeedback);
  14082. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14083. shaderProgram.transformFeedback = transformFeedback;
  14084. }
  14085. context.linkProgram(shaderProgram);
  14086. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14087. this.bindTransformFeedback(null);
  14088. }
  14089. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14090. if (!linked) {
  14091. context.validateProgram(shaderProgram);
  14092. var error = context.getProgramInfoLog(shaderProgram);
  14093. if (error) {
  14094. throw new Error(error);
  14095. }
  14096. }
  14097. context.deleteShader(vertexShader);
  14098. context.deleteShader(fragmentShader);
  14099. return shaderProgram;
  14100. };
  14101. /**
  14102. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14103. * @param shaderProgram defines the webGL program to use
  14104. * @param uniformsNames defines the list of uniform names
  14105. * @returns an array of webGL uniform locations
  14106. */
  14107. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14108. var results = new Array();
  14109. for (var index = 0; index < uniformsNames.length; index++) {
  14110. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14111. }
  14112. return results;
  14113. };
  14114. /**
  14115. * Gets the lsit of active attributes for a given webGL program
  14116. * @param shaderProgram defines the webGL program to use
  14117. * @param attributesNames defines the list of attribute names to get
  14118. * @returns an array of indices indicating the offset of each attribute
  14119. */
  14120. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14121. var results = [];
  14122. for (var index = 0; index < attributesNames.length; index++) {
  14123. try {
  14124. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14125. }
  14126. catch (e) {
  14127. results.push(-1);
  14128. }
  14129. }
  14130. return results;
  14131. };
  14132. /**
  14133. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14134. * @param effect defines the effect to activate
  14135. */
  14136. Engine.prototype.enableEffect = function (effect) {
  14137. if (!effect) {
  14138. return;
  14139. }
  14140. // Use program
  14141. this.bindSamplers(effect);
  14142. this._currentEffect = effect;
  14143. if (effect.onBind) {
  14144. effect.onBind(effect);
  14145. }
  14146. effect.onBindObservable.notifyObservers(effect);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to an array of int32
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param array defines the array of int32 to store
  14152. */
  14153. Engine.prototype.setIntArray = function (uniform, array) {
  14154. if (!uniform)
  14155. return;
  14156. this._gl.uniform1iv(uniform, array);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to an array of int32 (stored as vec2)
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param array defines the array of int32 to store
  14162. */
  14163. Engine.prototype.setIntArray2 = function (uniform, array) {
  14164. if (!uniform || array.length % 2 !== 0)
  14165. return;
  14166. this._gl.uniform2iv(uniform, array);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to an array of int32 (stored as vec3)
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param array defines the array of int32 to store
  14172. */
  14173. Engine.prototype.setIntArray3 = function (uniform, array) {
  14174. if (!uniform || array.length % 3 !== 0)
  14175. return;
  14176. this._gl.uniform3iv(uniform, array);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to an array of int32 (stored as vec4)
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param array defines the array of int32 to store
  14182. */
  14183. Engine.prototype.setIntArray4 = function (uniform, array) {
  14184. if (!uniform || array.length % 4 !== 0)
  14185. return;
  14186. this._gl.uniform4iv(uniform, array);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to an array of float32
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param array defines the array of float32 to store
  14192. */
  14193. Engine.prototype.setFloatArray = function (uniform, array) {
  14194. if (!uniform)
  14195. return;
  14196. this._gl.uniform1fv(uniform, array);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to an array of float32 (stored as vec2)
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param array defines the array of float32 to store
  14202. */
  14203. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14204. if (!uniform || array.length % 2 !== 0)
  14205. return;
  14206. this._gl.uniform2fv(uniform, array);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to an array of float32 (stored as vec3)
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param array defines the array of float32 to store
  14212. */
  14213. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14214. if (!uniform || array.length % 3 !== 0)
  14215. return;
  14216. this._gl.uniform3fv(uniform, array);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to an array of float32 (stored as vec4)
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param array defines the array of float32 to store
  14222. */
  14223. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14224. if (!uniform || array.length % 4 !== 0)
  14225. return;
  14226. this._gl.uniform4fv(uniform, array);
  14227. };
  14228. /**
  14229. * Set the value of an uniform to an array of number
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param array defines the array of number to store
  14232. */
  14233. Engine.prototype.setArray = function (uniform, array) {
  14234. if (!uniform)
  14235. return;
  14236. this._gl.uniform1fv(uniform, array);
  14237. };
  14238. /**
  14239. * Set the value of an uniform to an array of number (stored as vec2)
  14240. * @param uniform defines the webGL uniform location where to store the value
  14241. * @param array defines the array of number to store
  14242. */
  14243. Engine.prototype.setArray2 = function (uniform, array) {
  14244. if (!uniform || array.length % 2 !== 0)
  14245. return;
  14246. this._gl.uniform2fv(uniform, array);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to an array of number (stored as vec3)
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param array defines the array of number to store
  14252. */
  14253. Engine.prototype.setArray3 = function (uniform, array) {
  14254. if (!uniform || array.length % 3 !== 0)
  14255. return;
  14256. this._gl.uniform3fv(uniform, array);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to an array of number (stored as vec4)
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param array defines the array of number to store
  14262. */
  14263. Engine.prototype.setArray4 = function (uniform, array) {
  14264. if (!uniform || array.length % 4 !== 0)
  14265. return;
  14266. this._gl.uniform4fv(uniform, array);
  14267. };
  14268. /**
  14269. * Set the value of an uniform to an array of float32 (stored as matrices)
  14270. * @param uniform defines the webGL uniform location where to store the value
  14271. * @param matrices defines the array of float32 to store
  14272. */
  14273. Engine.prototype.setMatrices = function (uniform, matrices) {
  14274. if (!uniform)
  14275. return;
  14276. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14277. };
  14278. /**
  14279. * Set the value of an uniform to a matrix
  14280. * @param uniform defines the webGL uniform location where to store the value
  14281. * @param matrix defines the matrix to store
  14282. */
  14283. Engine.prototype.setMatrix = function (uniform, matrix) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a matrix (3x3)
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14292. */
  14293. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14294. if (!uniform)
  14295. return;
  14296. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14297. };
  14298. /**
  14299. * Set the value of an uniform to a matrix (2x2)
  14300. * @param uniform defines the webGL uniform location where to store the value
  14301. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14302. */
  14303. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14304. if (!uniform)
  14305. return;
  14306. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14307. };
  14308. /**
  14309. * Set the value of an uniform to a number (int)
  14310. * @param uniform defines the webGL uniform location where to store the value
  14311. * @param value defines the int number to store
  14312. */
  14313. Engine.prototype.setInt = function (uniform, value) {
  14314. if (!uniform)
  14315. return;
  14316. this._gl.uniform1i(uniform, value);
  14317. };
  14318. /**
  14319. * Set the value of an uniform to a number (float)
  14320. * @param uniform defines the webGL uniform location where to store the value
  14321. * @param value defines the float number to store
  14322. */
  14323. Engine.prototype.setFloat = function (uniform, value) {
  14324. if (!uniform)
  14325. return;
  14326. this._gl.uniform1f(uniform, value);
  14327. };
  14328. /**
  14329. * Set the value of an uniform to a vec2
  14330. * @param uniform defines the webGL uniform location where to store the value
  14331. * @param x defines the 1st component of the value
  14332. * @param y defines the 2nd component of the value
  14333. */
  14334. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14335. if (!uniform)
  14336. return;
  14337. this._gl.uniform2f(uniform, x, y);
  14338. };
  14339. /**
  14340. * Set the value of an uniform to a vec3
  14341. * @param uniform defines the webGL uniform location where to store the value
  14342. * @param x defines the 1st component of the value
  14343. * @param y defines the 2nd component of the value
  14344. * @param z defines the 3rd component of the value
  14345. */
  14346. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14347. if (!uniform)
  14348. return;
  14349. this._gl.uniform3f(uniform, x, y, z);
  14350. };
  14351. /**
  14352. * Set the value of an uniform to a boolean
  14353. * @param uniform defines the webGL uniform location where to store the value
  14354. * @param bool defines the boolean to store
  14355. */
  14356. Engine.prototype.setBool = function (uniform, bool) {
  14357. if (!uniform)
  14358. return;
  14359. this._gl.uniform1i(uniform, bool);
  14360. };
  14361. /**
  14362. * Set the value of an uniform to a vec4
  14363. * @param uniform defines the webGL uniform location where to store the value
  14364. * @param x defines the 1st component of the value
  14365. * @param y defines the 2nd component of the value
  14366. * @param z defines the 3rd component of the value
  14367. * @param w defines the 4th component of the value
  14368. */
  14369. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14370. if (!uniform)
  14371. return;
  14372. this._gl.uniform4f(uniform, x, y, z, w);
  14373. };
  14374. /**
  14375. * Set the value of an uniform to a Color3
  14376. * @param uniform defines the webGL uniform location where to store the value
  14377. * @param color3 defines the color to store
  14378. */
  14379. Engine.prototype.setColor3 = function (uniform, color3) {
  14380. if (!uniform)
  14381. return;
  14382. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14383. };
  14384. /**
  14385. * Set the value of an uniform to a Color3 and an alpha value
  14386. * @param uniform defines the webGL uniform location where to store the value
  14387. * @param color3 defines the color to store
  14388. * @param alpha defines the alpha component to store
  14389. */
  14390. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14391. if (!uniform)
  14392. return;
  14393. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14394. };
  14395. /**
  14396. * Sets a Color4 on a uniform variable
  14397. * @param uniform defines the uniform location
  14398. * @param color4 defines the value to be set
  14399. */
  14400. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14401. if (!uniform)
  14402. return;
  14403. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14404. };
  14405. // States
  14406. /**
  14407. * Set various states to the webGL context
  14408. * @param culling defines backface culling state
  14409. * @param zOffset defines the value to apply to zOffset (0 by default)
  14410. * @param force defines if states must be applied even if cache is up to date
  14411. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14412. */
  14413. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14414. if (zOffset === void 0) { zOffset = 0; }
  14415. if (reverseSide === void 0) { reverseSide = false; }
  14416. // Culling
  14417. if (this._depthCullingState.cull !== culling || force) {
  14418. this._depthCullingState.cull = culling;
  14419. }
  14420. // Cull face
  14421. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14422. if (this._depthCullingState.cullFace !== cullFace || force) {
  14423. this._depthCullingState.cullFace = cullFace;
  14424. }
  14425. // Z offset
  14426. this.setZOffset(zOffset);
  14427. // Front face
  14428. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14429. if (this._depthCullingState.frontFace !== frontFace || force) {
  14430. this._depthCullingState.frontFace = frontFace;
  14431. }
  14432. };
  14433. /**
  14434. * Set the z offset to apply to current rendering
  14435. * @param value defines the offset to apply
  14436. */
  14437. Engine.prototype.setZOffset = function (value) {
  14438. this._depthCullingState.zOffset = value;
  14439. };
  14440. /**
  14441. * Gets the current value of the zOffset
  14442. * @returns the current zOffset state
  14443. */
  14444. Engine.prototype.getZOffset = function () {
  14445. return this._depthCullingState.zOffset;
  14446. };
  14447. /**
  14448. * Enable or disable depth buffering
  14449. * @param enable defines the state to set
  14450. */
  14451. Engine.prototype.setDepthBuffer = function (enable) {
  14452. this._depthCullingState.depthTest = enable;
  14453. };
  14454. /**
  14455. * Gets a boolean indicating if depth writing is enabled
  14456. * @returns the current depth writing state
  14457. */
  14458. Engine.prototype.getDepthWrite = function () {
  14459. return this._depthCullingState.depthMask;
  14460. };
  14461. /**
  14462. * Enable or disable depth writing
  14463. * @param enable defines the state to set
  14464. */
  14465. Engine.prototype.setDepthWrite = function (enable) {
  14466. this._depthCullingState.depthMask = enable;
  14467. };
  14468. /**
  14469. * Enable or disable color writing
  14470. * @param enable defines the state to set
  14471. */
  14472. Engine.prototype.setColorWrite = function (enable) {
  14473. this._gl.colorMask(enable, enable, enable, enable);
  14474. this._colorWrite = enable;
  14475. };
  14476. /**
  14477. * Gets a boolean indicating if color writing is enabled
  14478. * @returns the current color writing state
  14479. */
  14480. Engine.prototype.getColorWrite = function () {
  14481. return this._colorWrite;
  14482. };
  14483. /**
  14484. * Sets alpha constants used by some alpha blending modes
  14485. * @param r defines the red component
  14486. * @param g defines the green component
  14487. * @param b defines the blue component
  14488. * @param a defines the alpha component
  14489. */
  14490. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14491. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14492. };
  14493. /**
  14494. * Sets the current alpha mode
  14495. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14496. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14497. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14498. */
  14499. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14500. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14501. if (this._alphaMode === mode) {
  14502. return;
  14503. }
  14504. switch (mode) {
  14505. case Engine.ALPHA_DISABLE:
  14506. this._alphaState.alphaBlend = false;
  14507. break;
  14508. case Engine.ALPHA_PREMULTIPLIED:
  14509. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14510. this._alphaState.alphaBlend = true;
  14511. break;
  14512. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14513. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14514. this._alphaState.alphaBlend = true;
  14515. break;
  14516. case Engine.ALPHA_COMBINE:
  14517. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14518. this._alphaState.alphaBlend = true;
  14519. break;
  14520. case Engine.ALPHA_ONEONE:
  14521. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14522. this._alphaState.alphaBlend = true;
  14523. break;
  14524. case Engine.ALPHA_ADD:
  14525. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14526. this._alphaState.alphaBlend = true;
  14527. break;
  14528. case Engine.ALPHA_SUBTRACT:
  14529. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14530. this._alphaState.alphaBlend = true;
  14531. break;
  14532. case Engine.ALPHA_MULTIPLY:
  14533. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14534. this._alphaState.alphaBlend = true;
  14535. break;
  14536. case Engine.ALPHA_MAXIMIZED:
  14537. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14538. this._alphaState.alphaBlend = true;
  14539. break;
  14540. case Engine.ALPHA_INTERPOLATE:
  14541. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14542. this._alphaState.alphaBlend = true;
  14543. break;
  14544. case Engine.ALPHA_SCREENMODE:
  14545. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14546. this._alphaState.alphaBlend = true;
  14547. break;
  14548. }
  14549. if (!noDepthWriteChange) {
  14550. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14551. }
  14552. this._alphaMode = mode;
  14553. };
  14554. /**
  14555. * Gets the current alpha mode
  14556. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14557. * @returns the current alpha mode
  14558. */
  14559. Engine.prototype.getAlphaMode = function () {
  14560. return this._alphaMode;
  14561. };
  14562. // Textures
  14563. /**
  14564. * Clears the list of texture accessible through engine.
  14565. * This can help preventing texture load conflict due to name collision.
  14566. */
  14567. Engine.prototype.clearInternalTexturesCache = function () {
  14568. this._internalTexturesCache = [];
  14569. };
  14570. /**
  14571. * Force the entire cache to be cleared
  14572. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14573. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14574. */
  14575. Engine.prototype.wipeCaches = function (bruteForce) {
  14576. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14577. return;
  14578. }
  14579. this._currentEffect = null;
  14580. if (bruteForce) {
  14581. this.resetTextureCache();
  14582. this._currentProgram = null;
  14583. this._stencilState.reset();
  14584. this._depthCullingState.reset();
  14585. this.setDepthFunctionToLessOrEqual();
  14586. this._alphaState.reset();
  14587. }
  14588. this._resetVertexBufferBinding();
  14589. this._cachedIndexBuffer = null;
  14590. this._cachedEffectForVertexBuffers = null;
  14591. this._unbindVertexArrayObject();
  14592. this.bindIndexBuffer(null);
  14593. };
  14594. /**
  14595. * Set the compressed texture format to use, based on the formats you have, and the formats
  14596. * supported by the hardware / browser.
  14597. *
  14598. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14599. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14600. * to API arguments needed to compressed textures. This puts the burden on the container
  14601. * generator to house the arcane code for determining these for current & future formats.
  14602. *
  14603. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14604. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14605. *
  14606. * Note: The result of this call is not taken into account when a texture is base64.
  14607. *
  14608. * @param formatsAvailable defines the list of those format families you have created
  14609. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14610. *
  14611. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14612. * @returns The extension selected.
  14613. */
  14614. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14615. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14616. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14617. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14618. return this._textureFormatInUse = this._texturesSupported[i];
  14619. }
  14620. }
  14621. }
  14622. // actively set format to nothing, to allow this to be called more than once
  14623. // and possibly fail the 2nd time
  14624. this._textureFormatInUse = null;
  14625. return null;
  14626. };
  14627. /** @hidden */
  14628. Engine.prototype._createTexture = function () {
  14629. var texture = this._gl.createTexture();
  14630. if (!texture) {
  14631. throw new Error("Unable to create texture");
  14632. }
  14633. return texture;
  14634. };
  14635. /**
  14636. * Usually called from BABYLON.Texture.ts.
  14637. * Passed information to create a WebGLTexture
  14638. * @param urlArg defines a value which contains one of the following:
  14639. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14640. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14641. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14642. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14643. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14644. * @param scene needed for loading to the correct scene
  14645. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14646. * @param onLoad optional callback to be called upon successful completion
  14647. * @param onError optional callback to be called upon failure
  14648. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14649. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14650. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14651. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14652. */
  14653. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14654. var _this = this;
  14655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14656. if (onLoad === void 0) { onLoad = null; }
  14657. if (onError === void 0) { onError = null; }
  14658. if (buffer === void 0) { buffer = null; }
  14659. if (fallback === void 0) { fallback = null; }
  14660. if (format === void 0) { format = null; }
  14661. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14662. var fromData = url.substr(0, 5) === "data:";
  14663. var fromBlob = url.substr(0, 5) === "blob:";
  14664. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14665. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14666. // establish the file extension, if possible
  14667. var lastDot = url.lastIndexOf('.');
  14668. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14669. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14670. var isTGA = (extension.indexOf(".tga") === 0);
  14671. // determine if a ktx file should be substituted
  14672. var isKTX = false;
  14673. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14674. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14675. isKTX = true;
  14676. }
  14677. if (scene) {
  14678. scene._addPendingData(texture);
  14679. }
  14680. texture.url = url;
  14681. texture.generateMipMaps = !noMipmap;
  14682. texture.samplingMode = samplingMode;
  14683. texture.invertY = invertY;
  14684. if (!this._doNotHandleContextLost) {
  14685. // Keep a link to the buffer only if we plan to handle context lost
  14686. texture._buffer = buffer;
  14687. }
  14688. var onLoadObserver = null;
  14689. if (onLoad && !fallback) {
  14690. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14691. }
  14692. if (!fallback)
  14693. this._internalTexturesCache.push(texture);
  14694. var onerror = function (message, exception) {
  14695. if (scene) {
  14696. scene._removePendingData(texture);
  14697. }
  14698. if (onLoadObserver) {
  14699. texture.onLoadedObservable.remove(onLoadObserver);
  14700. }
  14701. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14702. if (isKTX) {
  14703. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14704. }
  14705. else if (BABYLON.Tools.UseFallbackTexture) {
  14706. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14707. }
  14708. if (onError) {
  14709. onError(message || "Unknown error", exception);
  14710. }
  14711. };
  14712. var callback = null;
  14713. // processing for non-image formats
  14714. if (isKTX || isTGA || isDDS) {
  14715. if (isKTX) {
  14716. callback = function (data) {
  14717. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14718. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14719. ktx.uploadLevels(_this._gl, !noMipmap);
  14720. return false;
  14721. }, samplingMode);
  14722. };
  14723. }
  14724. else if (isTGA) {
  14725. callback = function (arrayBuffer) {
  14726. var data = new Uint8Array(arrayBuffer);
  14727. var header = BABYLON.TGATools.GetTGAHeader(data);
  14728. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14729. BABYLON.TGATools.UploadContent(_this._gl, data);
  14730. return false;
  14731. }, samplingMode);
  14732. };
  14733. }
  14734. else if (isDDS) {
  14735. callback = function (data) {
  14736. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14737. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14738. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14739. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14740. return false;
  14741. }, samplingMode);
  14742. };
  14743. }
  14744. if (!buffer) {
  14745. this._loadFile(url, function (data) {
  14746. if (callback) {
  14747. callback(data);
  14748. }
  14749. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14750. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14751. });
  14752. }
  14753. else {
  14754. if (callback) {
  14755. callback(buffer);
  14756. }
  14757. }
  14758. // image format processing
  14759. }
  14760. else {
  14761. var onload = function (img) {
  14762. if (fromBlob && !_this._doNotHandleContextLost) {
  14763. // We need to store the image if we need to rebuild the texture
  14764. // in case of a webgl context lost
  14765. texture._buffer = img;
  14766. }
  14767. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14768. var gl = _this._gl;
  14769. var isPot = (img.width === potWidth && img.height === potHeight);
  14770. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14771. if (isPot) {
  14772. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14773. return false;
  14774. }
  14775. // Using shaders to rescale because canvas.drawImage is lossy
  14776. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14777. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14778. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14783. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14784. _this._releaseTexture(source);
  14785. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14786. continuationCallback();
  14787. });
  14788. return true;
  14789. }, samplingMode);
  14790. };
  14791. if (!fromData || isBase64) {
  14792. if (buffer instanceof HTMLImageElement) {
  14793. onload(buffer);
  14794. }
  14795. else {
  14796. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14797. }
  14798. }
  14799. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14800. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14801. }
  14802. else {
  14803. onload(buffer);
  14804. }
  14805. }
  14806. return texture;
  14807. };
  14808. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14809. var _this = this;
  14810. var rtt = this.createRenderTargetTexture({
  14811. width: destination.width,
  14812. height: destination.height,
  14813. }, {
  14814. generateMipMaps: false,
  14815. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14816. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14817. generateDepthBuffer: false,
  14818. generateStencilBuffer: false
  14819. });
  14820. if (!this._rescalePostProcess) {
  14821. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14822. }
  14823. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14824. _this._rescalePostProcess.onApply = function (effect) {
  14825. effect._bindTexture("textureSampler", source);
  14826. };
  14827. var hostingScene = scene;
  14828. if (!hostingScene) {
  14829. hostingScene = _this.scenes[_this.scenes.length - 1];
  14830. }
  14831. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14832. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14833. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14834. _this.unBindFramebuffer(rtt);
  14835. _this._releaseTexture(rtt);
  14836. if (onComplete) {
  14837. onComplete();
  14838. }
  14839. });
  14840. };
  14841. /**
  14842. * Update a raw texture
  14843. * @param texture defines the texture to update
  14844. * @param data defines the data to store in the texture
  14845. * @param format defines the format of the data
  14846. * @param invertY defines if data must be stored with Y axis inverted
  14847. * @param compression defines the compression used (null by default)
  14848. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14849. */
  14850. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14851. if (compression === void 0) { compression = null; }
  14852. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14853. if (!texture) {
  14854. return;
  14855. }
  14856. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14857. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14858. // babylon's internalFormat but gl's texImage2D format
  14859. var internalFormat = this._getInternalFormat(format);
  14860. var textureType = this._getWebGLTextureType(type);
  14861. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14862. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14863. if (!this._doNotHandleContextLost) {
  14864. texture._bufferView = data;
  14865. texture.format = format;
  14866. texture.type = type;
  14867. texture.invertY = invertY;
  14868. texture._compression = compression;
  14869. }
  14870. if (texture.width % 4 !== 0) {
  14871. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14872. }
  14873. if (compression && data) {
  14874. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14875. }
  14876. else {
  14877. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14878. }
  14879. if (texture.generateMipMaps) {
  14880. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14881. }
  14882. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14883. // this.resetTextureCache();
  14884. texture.isReady = true;
  14885. };
  14886. /**
  14887. * Creates a raw texture
  14888. * @param data defines the data to store in the texture
  14889. * @param width defines the width of the texture
  14890. * @param height defines the height of the texture
  14891. * @param format defines the format of the data
  14892. * @param generateMipMaps defines if the engine should generate the mip levels
  14893. * @param invertY defines if data must be stored with Y axis inverted
  14894. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14895. * @param compression defines the compression used (null by default)
  14896. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14897. * @returns the raw texture inside an InternalTexture
  14898. */
  14899. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14900. if (compression === void 0) { compression = null; }
  14901. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14902. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14903. texture.baseWidth = width;
  14904. texture.baseHeight = height;
  14905. texture.width = width;
  14906. texture.height = height;
  14907. texture.format = format;
  14908. texture.generateMipMaps = generateMipMaps;
  14909. texture.samplingMode = samplingMode;
  14910. texture.invertY = invertY;
  14911. texture._compression = compression;
  14912. texture.type = type;
  14913. if (!this._doNotHandleContextLost) {
  14914. texture._bufferView = data;
  14915. }
  14916. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14917. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14918. // Filters
  14919. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14920. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14921. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14922. if (generateMipMaps) {
  14923. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14924. }
  14925. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14926. this._internalTexturesCache.push(texture);
  14927. return texture;
  14928. };
  14929. /**
  14930. * Creates a dynamic texture
  14931. * @param width defines the width of the texture
  14932. * @param height defines the height of the texture
  14933. * @param generateMipMaps defines if the engine should generate the mip levels
  14934. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14935. * @returns the dynamic texture inside an InternalTexture
  14936. */
  14937. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14938. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14939. texture.baseWidth = width;
  14940. texture.baseHeight = height;
  14941. if (generateMipMaps) {
  14942. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14943. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14944. }
  14945. // this.resetTextureCache();
  14946. texture.width = width;
  14947. texture.height = height;
  14948. texture.isReady = false;
  14949. texture.generateMipMaps = generateMipMaps;
  14950. texture.samplingMode = samplingMode;
  14951. this.updateTextureSamplingMode(samplingMode, texture);
  14952. this._internalTexturesCache.push(texture);
  14953. return texture;
  14954. };
  14955. /**
  14956. * Update the sampling mode of a given texture
  14957. * @param samplingMode defines the required sampling mode
  14958. * @param texture defines the texture to update
  14959. */
  14960. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14961. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14962. if (texture.isCube) {
  14963. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14964. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14965. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14966. }
  14967. else if (texture.is3D) {
  14968. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14969. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14970. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14971. }
  14972. else {
  14973. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14974. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14975. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14976. }
  14977. texture.samplingMode = samplingMode;
  14978. };
  14979. /**
  14980. * Update the content of a dynamic texture
  14981. * @param texture defines the texture to update
  14982. * @param canvas defines the canvas containing the source
  14983. * @param invertY defines if data must be stored with Y axis inverted
  14984. * @param premulAlpha defines if alpha is stored as premultiplied
  14985. * @param format defines the format of the data
  14986. */
  14987. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14988. if (premulAlpha === void 0) { premulAlpha = false; }
  14989. if (!texture) {
  14990. return;
  14991. }
  14992. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14993. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14994. if (premulAlpha) {
  14995. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14996. }
  14997. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14998. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14999. if (texture.generateMipMaps) {
  15000. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15001. }
  15002. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15003. if (premulAlpha) {
  15004. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15005. }
  15006. texture.isReady = true;
  15007. };
  15008. /**
  15009. * Update a video texture
  15010. * @param texture defines the texture to update
  15011. * @param video defines the video element to use
  15012. * @param invertY defines if data must be stored with Y axis inverted
  15013. */
  15014. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15015. if (!texture || texture._isDisabled) {
  15016. return;
  15017. }
  15018. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15019. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  15020. try {
  15021. // Testing video texture support
  15022. if (this._videoTextureSupported === undefined) {
  15023. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15024. if (this._gl.getError() !== 0) {
  15025. this._videoTextureSupported = false;
  15026. }
  15027. else {
  15028. this._videoTextureSupported = true;
  15029. }
  15030. }
  15031. // Copy video through the current working canvas if video texture is not supported
  15032. if (!this._videoTextureSupported) {
  15033. if (!texture._workingCanvas) {
  15034. texture._workingCanvas = document.createElement("canvas");
  15035. var context = texture._workingCanvas.getContext("2d");
  15036. if (!context) {
  15037. throw new Error("Unable to get 2d context");
  15038. }
  15039. texture._workingContext = context;
  15040. texture._workingCanvas.width = texture.width;
  15041. texture._workingCanvas.height = texture.height;
  15042. }
  15043. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15044. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15045. }
  15046. else {
  15047. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15048. }
  15049. if (texture.generateMipMaps) {
  15050. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15051. }
  15052. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15053. // this.resetTextureCache();
  15054. texture.isReady = true;
  15055. }
  15056. catch (ex) {
  15057. // Something unexpected
  15058. // Let's disable the texture
  15059. texture._isDisabled = true;
  15060. }
  15061. };
  15062. /**
  15063. * Updates a depth texture Comparison Mode and Function.
  15064. * If the comparison Function is equal to 0, the mode will be set to none.
  15065. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15066. * @param texture The texture to set the comparison function for
  15067. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15068. */
  15069. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15070. if (this.webGLVersion === 1) {
  15071. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15072. return;
  15073. }
  15074. var gl = this._gl;
  15075. if (texture.isCube) {
  15076. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15077. if (comparisonFunction === 0) {
  15078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15080. }
  15081. else {
  15082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15084. }
  15085. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15086. }
  15087. else {
  15088. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15089. if (comparisonFunction === 0) {
  15090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15092. }
  15093. else {
  15094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15095. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15096. }
  15097. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15098. }
  15099. texture._comparisonFunction = comparisonFunction;
  15100. };
  15101. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15102. var width = size.width || size;
  15103. var height = size.height || size;
  15104. internalTexture.baseWidth = width;
  15105. internalTexture.baseHeight = height;
  15106. internalTexture.width = width;
  15107. internalTexture.height = height;
  15108. internalTexture.isReady = true;
  15109. internalTexture.samples = 1;
  15110. internalTexture.generateMipMaps = false;
  15111. internalTexture._generateDepthBuffer = true;
  15112. internalTexture._generateStencilBuffer = generateStencil;
  15113. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15114. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15115. internalTexture._comparisonFunction = comparisonFunction;
  15116. var gl = this._gl;
  15117. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15118. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15119. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15120. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15121. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15122. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15123. if (comparisonFunction === 0) {
  15124. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15125. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15126. }
  15127. else {
  15128. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15129. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15130. }
  15131. };
  15132. /**
  15133. * Creates a depth stencil texture.
  15134. * This is only available in WebGL 2 or with the depth texture extension available.
  15135. * @param size The size of face edge in the texture.
  15136. * @param options The options defining the texture.
  15137. * @returns The texture
  15138. */
  15139. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15140. if (options.isCube) {
  15141. var width = size.width || size;
  15142. return this._createDepthStencilCubeTexture(width, options);
  15143. }
  15144. else {
  15145. return this._createDepthStencilTexture(size, options);
  15146. }
  15147. };
  15148. /**
  15149. * Creates a depth stencil texture.
  15150. * This is only available in WebGL 2 or with the depth texture extension available.
  15151. * @param size The size of face edge in the texture.
  15152. * @param options The options defining the texture.
  15153. * @returns The texture
  15154. */
  15155. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15156. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15157. if (!this._caps.depthTextureExtension) {
  15158. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15159. return internalTexture;
  15160. }
  15161. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15162. var gl = this._gl;
  15163. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15164. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15165. if (this.webGLVersion > 1) {
  15166. if (internalOptions.generateStencil) {
  15167. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15168. }
  15169. else {
  15170. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15171. }
  15172. }
  15173. else {
  15174. if (internalOptions.generateStencil) {
  15175. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15176. }
  15177. else {
  15178. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15179. }
  15180. }
  15181. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15182. return internalTexture;
  15183. };
  15184. /**
  15185. * Creates a depth stencil cube texture.
  15186. * This is only available in WebGL 2.
  15187. * @param size The size of face edge in the cube texture.
  15188. * @param options The options defining the cube texture.
  15189. * @returns The cube texture
  15190. */
  15191. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15192. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15193. internalTexture.isCube = true;
  15194. if (this.webGLVersion === 1) {
  15195. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15196. return internalTexture;
  15197. }
  15198. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15199. var gl = this._gl;
  15200. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15201. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15202. // Create the depth/stencil buffer
  15203. for (var face = 0; face < 6; face++) {
  15204. if (internalOptions.generateStencil) {
  15205. 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);
  15206. }
  15207. else {
  15208. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15209. }
  15210. }
  15211. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15212. return internalTexture;
  15213. };
  15214. /**
  15215. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15216. * @param renderTarget The render target to set the frame buffer for
  15217. */
  15218. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15219. // Create the framebuffer
  15220. var internalTexture = renderTarget.getInternalTexture();
  15221. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15222. return;
  15223. }
  15224. var gl = this._gl;
  15225. var depthStencilTexture = renderTarget.depthStencilTexture;
  15226. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15227. if (depthStencilTexture.isCube) {
  15228. if (depthStencilTexture._generateStencilBuffer) {
  15229. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15230. }
  15231. else {
  15232. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15233. }
  15234. }
  15235. else {
  15236. if (depthStencilTexture._generateStencilBuffer) {
  15237. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15238. }
  15239. else {
  15240. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15241. }
  15242. }
  15243. this.bindUnboundFramebuffer(null);
  15244. };
  15245. /**
  15246. * Creates a new render target texture
  15247. * @param size defines the size of the texture
  15248. * @param options defines the options used to create the texture
  15249. * @returns a new render target texture stored in an InternalTexture
  15250. */
  15251. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15252. var fullOptions = new RenderTargetCreationOptions();
  15253. if (options !== undefined && typeof options === "object") {
  15254. fullOptions.generateMipMaps = options.generateMipMaps;
  15255. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15256. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15257. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15258. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15259. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15260. }
  15261. else {
  15262. fullOptions.generateMipMaps = options;
  15263. fullOptions.generateDepthBuffer = true;
  15264. fullOptions.generateStencilBuffer = false;
  15265. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15266. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15267. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15268. }
  15269. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15270. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15271. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15272. }
  15273. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15274. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15275. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15276. }
  15277. var gl = this._gl;
  15278. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15279. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15280. var width = size.width || size;
  15281. var height = size.height || size;
  15282. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15283. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15284. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15285. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15286. }
  15287. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15291. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15292. // Create the framebuffer
  15293. var currentFrameBuffer = this._currentFramebuffer;
  15294. var framebuffer = gl.createFramebuffer();
  15295. this.bindUnboundFramebuffer(framebuffer);
  15296. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15297. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15298. if (fullOptions.generateMipMaps) {
  15299. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15300. }
  15301. // Unbind
  15302. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15303. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15304. this.bindUnboundFramebuffer(currentFrameBuffer);
  15305. texture._framebuffer = framebuffer;
  15306. texture.baseWidth = width;
  15307. texture.baseHeight = height;
  15308. texture.width = width;
  15309. texture.height = height;
  15310. texture.isReady = true;
  15311. texture.samples = 1;
  15312. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15313. texture.samplingMode = fullOptions.samplingMode;
  15314. texture.type = fullOptions.type;
  15315. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15316. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15317. // this.resetTextureCache();
  15318. this._internalTexturesCache.push(texture);
  15319. return texture;
  15320. };
  15321. /**
  15322. * Create a multi render target texture
  15323. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15324. * @param size defines the size of the texture
  15325. * @param options defines the creation options
  15326. * @returns the cube texture as an InternalTexture
  15327. */
  15328. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15329. var generateMipMaps = false;
  15330. var generateDepthBuffer = true;
  15331. var generateStencilBuffer = false;
  15332. var generateDepthTexture = false;
  15333. var textureCount = 1;
  15334. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15335. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15336. var types = new Array();
  15337. var samplingModes = new Array();
  15338. if (options !== undefined) {
  15339. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15340. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15341. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15342. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15343. textureCount = options.textureCount || 1;
  15344. if (options.types) {
  15345. types = options.types;
  15346. }
  15347. if (options.samplingModes) {
  15348. samplingModes = options.samplingModes;
  15349. }
  15350. }
  15351. var gl = this._gl;
  15352. // Create the framebuffer
  15353. var framebuffer = gl.createFramebuffer();
  15354. this.bindUnboundFramebuffer(framebuffer);
  15355. var width = size.width || size;
  15356. var height = size.height || size;
  15357. var textures = [];
  15358. var attachments = [];
  15359. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15360. for (var i = 0; i < textureCount; i++) {
  15361. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15362. var type = types[i] || defaultType;
  15363. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15364. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15365. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15366. }
  15367. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15368. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15369. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15370. }
  15371. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15372. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15373. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15374. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15375. }
  15376. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15377. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15378. textures.push(texture);
  15379. attachments.push(attachment);
  15380. gl.activeTexture(gl["TEXTURE" + i]);
  15381. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15382. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15383. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15384. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15385. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15386. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15387. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15388. if (generateMipMaps) {
  15389. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15390. }
  15391. // Unbind
  15392. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15393. texture._framebuffer = framebuffer;
  15394. texture._depthStencilBuffer = depthStencilBuffer;
  15395. texture.baseWidth = width;
  15396. texture.baseHeight = height;
  15397. texture.width = width;
  15398. texture.height = height;
  15399. texture.isReady = true;
  15400. texture.samples = 1;
  15401. texture.generateMipMaps = generateMipMaps;
  15402. texture.samplingMode = samplingMode;
  15403. texture.type = type;
  15404. texture._generateDepthBuffer = generateDepthBuffer;
  15405. texture._generateStencilBuffer = generateStencilBuffer;
  15406. texture._attachments = attachments;
  15407. this._internalTexturesCache.push(texture);
  15408. }
  15409. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15410. // Depth texture
  15411. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15412. gl.activeTexture(gl.TEXTURE0);
  15413. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15414. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15418. 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);
  15419. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15420. depthTexture._framebuffer = framebuffer;
  15421. depthTexture.baseWidth = width;
  15422. depthTexture.baseHeight = height;
  15423. depthTexture.width = width;
  15424. depthTexture.height = height;
  15425. depthTexture.isReady = true;
  15426. depthTexture.samples = 1;
  15427. depthTexture.generateMipMaps = generateMipMaps;
  15428. depthTexture.samplingMode = gl.NEAREST;
  15429. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15430. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15431. textures.push(depthTexture);
  15432. this._internalTexturesCache.push(depthTexture);
  15433. }
  15434. gl.drawBuffers(attachments);
  15435. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15436. this.bindUnboundFramebuffer(null);
  15437. this.resetTextureCache();
  15438. return textures;
  15439. };
  15440. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15441. if (samples === void 0) { samples = 1; }
  15442. var depthStencilBuffer = null;
  15443. var gl = this._gl;
  15444. // Create the depth/stencil buffer
  15445. if (generateStencilBuffer) {
  15446. depthStencilBuffer = gl.createRenderbuffer();
  15447. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15448. if (samples > 1) {
  15449. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15450. }
  15451. else {
  15452. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15453. }
  15454. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15455. }
  15456. else if (generateDepthBuffer) {
  15457. depthStencilBuffer = gl.createRenderbuffer();
  15458. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15459. if (samples > 1) {
  15460. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15461. }
  15462. else {
  15463. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15464. }
  15465. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15466. }
  15467. return depthStencilBuffer;
  15468. };
  15469. /**
  15470. * Updates the sample count of a render target texture
  15471. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15472. * @param texture defines the texture to update
  15473. * @param samples defines the sample count to set
  15474. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15475. */
  15476. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15477. if (this.webGLVersion < 2 || !texture) {
  15478. return 1;
  15479. }
  15480. if (texture.samples === samples) {
  15481. return samples;
  15482. }
  15483. var gl = this._gl;
  15484. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15485. // Dispose previous render buffers
  15486. if (texture._depthStencilBuffer) {
  15487. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15488. texture._depthStencilBuffer = null;
  15489. }
  15490. if (texture._MSAAFramebuffer) {
  15491. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15492. texture._MSAAFramebuffer = null;
  15493. }
  15494. if (texture._MSAARenderBuffer) {
  15495. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15496. texture._MSAARenderBuffer = null;
  15497. }
  15498. if (samples > 1) {
  15499. var framebuffer = gl.createFramebuffer();
  15500. if (!framebuffer) {
  15501. throw new Error("Unable to create multi sampled framebuffer");
  15502. }
  15503. texture._MSAAFramebuffer = framebuffer;
  15504. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15505. var colorRenderbuffer = gl.createRenderbuffer();
  15506. if (!colorRenderbuffer) {
  15507. throw new Error("Unable to create multi sampled framebuffer");
  15508. }
  15509. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15510. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15511. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15512. texture._MSAARenderBuffer = colorRenderbuffer;
  15513. }
  15514. else {
  15515. this.bindUnboundFramebuffer(texture._framebuffer);
  15516. }
  15517. texture.samples = samples;
  15518. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15519. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15520. this.bindUnboundFramebuffer(null);
  15521. return samples;
  15522. };
  15523. /**
  15524. * Update the sample count for a given multiple render target texture
  15525. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15526. * @param textures defines the textures to update
  15527. * @param samples defines the sample count to set
  15528. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15529. */
  15530. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15531. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15532. return 1;
  15533. }
  15534. if (textures[0].samples === samples) {
  15535. return samples;
  15536. }
  15537. var gl = this._gl;
  15538. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15539. // Dispose previous render buffers
  15540. if (textures[0]._depthStencilBuffer) {
  15541. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15542. textures[0]._depthStencilBuffer = null;
  15543. }
  15544. if (textures[0]._MSAAFramebuffer) {
  15545. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15546. textures[0]._MSAAFramebuffer = null;
  15547. }
  15548. for (var i = 0; i < textures.length; i++) {
  15549. if (textures[i]._MSAARenderBuffer) {
  15550. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15551. textures[i]._MSAARenderBuffer = null;
  15552. }
  15553. }
  15554. if (samples > 1) {
  15555. var framebuffer = gl.createFramebuffer();
  15556. if (!framebuffer) {
  15557. throw new Error("Unable to create multi sampled framebuffer");
  15558. }
  15559. this.bindUnboundFramebuffer(framebuffer);
  15560. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15561. var attachments = [];
  15562. for (var i = 0; i < textures.length; i++) {
  15563. var texture = textures[i];
  15564. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15565. var colorRenderbuffer = gl.createRenderbuffer();
  15566. if (!colorRenderbuffer) {
  15567. throw new Error("Unable to create multi sampled framebuffer");
  15568. }
  15569. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15570. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15571. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15572. texture._MSAAFramebuffer = framebuffer;
  15573. texture._MSAARenderBuffer = colorRenderbuffer;
  15574. texture.samples = samples;
  15575. texture._depthStencilBuffer = depthStencilBuffer;
  15576. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15577. attachments.push(attachment);
  15578. }
  15579. gl.drawBuffers(attachments);
  15580. }
  15581. else {
  15582. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15583. }
  15584. this.bindUnboundFramebuffer(null);
  15585. return samples;
  15586. };
  15587. /** @hidden */
  15588. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15589. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15590. };
  15591. /** @hidden */
  15592. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15593. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15594. };
  15595. /** @hidden */
  15596. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15597. var gl = this._gl;
  15598. var textureType = this._getWebGLTextureType(texture.type);
  15599. var format = this._getInternalFormat(texture.format);
  15600. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15601. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15602. this._bindTextureDirectly(bindTarget, texture, true);
  15603. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15604. var target = gl.TEXTURE_2D;
  15605. if (texture.isCube) {
  15606. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15607. }
  15608. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15609. this._bindTextureDirectly(bindTarget, null, true);
  15610. };
  15611. /**
  15612. * Creates a new render target cube texture
  15613. * @param size defines the size of the texture
  15614. * @param options defines the options used to create the texture
  15615. * @returns a new render target cube texture stored in an InternalTexture
  15616. */
  15617. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15618. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15619. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15620. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15621. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15622. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15623. }
  15624. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15625. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15626. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15627. }
  15628. var gl = this._gl;
  15629. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15630. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15631. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15632. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15633. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15634. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15635. }
  15636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15640. for (var face = 0; face < 6; face++) {
  15641. 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);
  15642. }
  15643. // Create the framebuffer
  15644. var framebuffer = gl.createFramebuffer();
  15645. this.bindUnboundFramebuffer(framebuffer);
  15646. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15647. // MipMaps
  15648. if (fullOptions.generateMipMaps) {
  15649. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15650. }
  15651. // Unbind
  15652. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15653. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15654. this.bindUnboundFramebuffer(null);
  15655. texture._framebuffer = framebuffer;
  15656. texture.width = size;
  15657. texture.height = size;
  15658. texture.isReady = true;
  15659. texture.isCube = true;
  15660. texture.samples = 1;
  15661. texture.generateMipMaps = fullOptions.generateMipMaps;
  15662. texture.samplingMode = fullOptions.samplingMode;
  15663. texture.type = fullOptions.type;
  15664. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15665. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15666. this._internalTexturesCache.push(texture);
  15667. return texture;
  15668. };
  15669. /**
  15670. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15671. * @param rootUrl defines the url where the file to load is located
  15672. * @param scene defines the current scene
  15673. * @param lodScale defines scale to apply to the mip map selection
  15674. * @param lodOffset defines offset to apply to the mip map selection
  15675. * @param onLoad defines an optional callback raised when the texture is loaded
  15676. * @param onError defines an optional callback raised if there is an issue to load the texture
  15677. * @param format defines the format of the data
  15678. * @param forcedExtension defines the extension to use to pick the right loader
  15679. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15680. * @returns the cube texture as an InternalTexture
  15681. */
  15682. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15683. var _this = this;
  15684. if (onLoad === void 0) { onLoad = null; }
  15685. if (onError === void 0) { onError = null; }
  15686. if (forcedExtension === void 0) { forcedExtension = null; }
  15687. if (createPolynomials === void 0) { createPolynomials = true; }
  15688. var callback = function (loadData) {
  15689. if (!loadData) {
  15690. if (onLoad) {
  15691. onLoad(null);
  15692. }
  15693. return;
  15694. }
  15695. var texture = loadData.texture;
  15696. if (!createPolynomials) {
  15697. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15698. }
  15699. else if (loadData.info.sphericalPolynomial) {
  15700. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15701. }
  15702. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15703. if (_this._caps.textureLOD) {
  15704. // Do not add extra process if texture lod is supported.
  15705. if (onLoad) {
  15706. onLoad(texture);
  15707. }
  15708. return;
  15709. }
  15710. var mipSlices = 3;
  15711. var gl = _this._gl;
  15712. var width = loadData.width;
  15713. if (!width) {
  15714. return;
  15715. }
  15716. var textures = [];
  15717. for (var i = 0; i < mipSlices; i++) {
  15718. //compute LOD from even spacing in smoothness (matching shader calculation)
  15719. var smoothness = i / (mipSlices - 1);
  15720. var roughness = 1 - smoothness;
  15721. var minLODIndex = lodOffset; // roughness = 0
  15722. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15723. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15724. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15725. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15726. glTextureFromLod.isCube = true;
  15727. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15732. if (loadData.isDDS) {
  15733. var info = loadData.info;
  15734. var data = loadData.data;
  15735. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15736. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15737. }
  15738. else {
  15739. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15740. }
  15741. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15742. // Wrap in a base texture for easy binding.
  15743. var lodTexture = new BABYLON.BaseTexture(scene);
  15744. lodTexture.isCube = true;
  15745. lodTexture._texture = glTextureFromLod;
  15746. glTextureFromLod.isReady = true;
  15747. textures.push(lodTexture);
  15748. }
  15749. texture._lodTextureHigh = textures[2];
  15750. texture._lodTextureMid = textures[1];
  15751. texture._lodTextureLow = textures[0];
  15752. if (onLoad) {
  15753. onLoad(texture);
  15754. }
  15755. };
  15756. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15757. };
  15758. /**
  15759. * Creates a cube texture
  15760. * @param rootUrl defines the url where the files to load is located
  15761. * @param scene defines the current scene
  15762. * @param files defines the list of files to load (1 per face)
  15763. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15764. * @param onLoad defines an optional callback raised when the texture is loaded
  15765. * @param onError defines an optional callback raised if there is an issue to load the texture
  15766. * @param format defines the format of the data
  15767. * @param forcedExtension defines the extension to use to pick the right loader
  15768. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15769. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15770. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15771. * @returns the cube texture as an InternalTexture
  15772. */
  15773. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15774. var _this = this;
  15775. if (onLoad === void 0) { onLoad = null; }
  15776. if (onError === void 0) { onError = null; }
  15777. if (forcedExtension === void 0) { forcedExtension = null; }
  15778. if (createPolynomials === void 0) { createPolynomials = false; }
  15779. if (lodScale === void 0) { lodScale = 0; }
  15780. if (lodOffset === void 0) { lodOffset = 0; }
  15781. var gl = this._gl;
  15782. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15783. texture.isCube = true;
  15784. texture.url = rootUrl;
  15785. texture.generateMipMaps = !noMipmap;
  15786. texture._lodGenerationScale = lodScale;
  15787. texture._lodGenerationOffset = lodOffset;
  15788. if (!this._doNotHandleContextLost) {
  15789. texture._extension = forcedExtension;
  15790. texture._files = files;
  15791. }
  15792. var isKTX = false;
  15793. var isDDS = false;
  15794. var isEnv = false;
  15795. var lastDot = rootUrl.lastIndexOf('.');
  15796. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15797. if (this._textureFormatInUse) {
  15798. extension = this._textureFormatInUse;
  15799. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15800. isKTX = true;
  15801. }
  15802. else {
  15803. isDDS = (extension === ".dds");
  15804. isEnv = (extension === ".env");
  15805. }
  15806. var onerror = function (request, exception) {
  15807. if (onError && request) {
  15808. onError(request.status + " " + request.statusText, exception);
  15809. }
  15810. };
  15811. if (isKTX) {
  15812. this._loadFile(rootUrl, function (data) {
  15813. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15814. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15815. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15816. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15817. ktx.uploadLevels(_this._gl, !noMipmap);
  15818. _this.setCubeMapTextureParams(gl, loadMipmap);
  15819. texture.width = ktx.pixelWidth;
  15820. texture.height = ktx.pixelHeight;
  15821. texture.isReady = true;
  15822. }, undefined, undefined, true, onerror);
  15823. }
  15824. else if (isEnv) {
  15825. this._loadFile(rootUrl, function (data) {
  15826. data = data;
  15827. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15828. if (info) {
  15829. texture.width = info.width;
  15830. texture.height = info.width;
  15831. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15832. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15833. texture.isReady = true;
  15834. if (onLoad) {
  15835. onLoad();
  15836. }
  15837. });
  15838. }
  15839. else if (onError) {
  15840. onError("Can not parse the environment file", null);
  15841. }
  15842. }, undefined, undefined, true, onerror);
  15843. }
  15844. else if (isDDS) {
  15845. if (files && files.length === 6) {
  15846. this._cascadeLoadFiles(scene, function (imgs) {
  15847. var info;
  15848. var loadMipmap = false;
  15849. var width = 0;
  15850. for (var index = 0; index < imgs.length; index++) {
  15851. var data = imgs[index];
  15852. info = BABYLON.DDSTools.GetDDSInfo(data);
  15853. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15854. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15855. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15856. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15857. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15858. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15859. }
  15860. texture.width = info.width;
  15861. texture.height = info.height;
  15862. texture.type = info.textureType;
  15863. width = info.width;
  15864. }
  15865. _this.setCubeMapTextureParams(gl, loadMipmap);
  15866. texture.isReady = true;
  15867. if (onLoad) {
  15868. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15869. }
  15870. }, files, onError);
  15871. }
  15872. else {
  15873. this._loadFile(rootUrl, function (data) {
  15874. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15875. if (createPolynomials) {
  15876. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15877. }
  15878. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15879. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15880. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15881. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15882. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15883. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15884. }
  15885. _this.setCubeMapTextureParams(gl, loadMipmap);
  15886. texture.width = info.width;
  15887. texture.height = info.height;
  15888. texture.isReady = true;
  15889. texture.type = info.textureType;
  15890. if (onLoad) {
  15891. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15892. }
  15893. }, undefined, undefined, true, onerror);
  15894. }
  15895. }
  15896. else {
  15897. if (!files) {
  15898. throw new Error("Cannot load cubemap because files were not defined");
  15899. }
  15900. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15901. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15902. var height = width;
  15903. _this._prepareWorkingCanvas();
  15904. if (!_this._workingCanvas || !_this._workingContext) {
  15905. return;
  15906. }
  15907. _this._workingCanvas.width = width;
  15908. _this._workingCanvas.height = height;
  15909. var faces = [
  15910. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15911. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15912. ];
  15913. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15914. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15915. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15916. for (var index = 0; index < faces.length; index++) {
  15917. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15918. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15919. }
  15920. if (!noMipmap) {
  15921. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15922. }
  15923. _this.setCubeMapTextureParams(gl, !noMipmap);
  15924. texture.width = width;
  15925. texture.height = height;
  15926. texture.isReady = true;
  15927. if (format) {
  15928. texture.format = format;
  15929. }
  15930. texture.onLoadedObservable.notifyObservers(texture);
  15931. texture.onLoadedObservable.clear();
  15932. if (onLoad) {
  15933. onLoad();
  15934. }
  15935. }, files, onError);
  15936. }
  15937. this._internalTexturesCache.push(texture);
  15938. return texture;
  15939. };
  15940. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15945. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15946. // this.resetTextureCache();
  15947. };
  15948. /**
  15949. * Update a raw cube texture
  15950. * @param texture defines the texture to udpdate
  15951. * @param data defines the data to store
  15952. * @param format defines the data format
  15953. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15954. * @param invertY defines if data must be stored with Y axis inverted
  15955. * @param compression defines the compression used (null by default)
  15956. * @param level defines which level of the texture to update
  15957. */
  15958. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15959. if (compression === void 0) { compression = null; }
  15960. if (level === void 0) { level = 0; }
  15961. texture._bufferViewArray = data;
  15962. texture.format = format;
  15963. texture.type = type;
  15964. texture.invertY = invertY;
  15965. texture._compression = compression;
  15966. var gl = this._gl;
  15967. var textureType = this._getWebGLTextureType(type);
  15968. var internalFormat = this._getInternalFormat(format);
  15969. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15970. var needConversion = false;
  15971. if (internalFormat === gl.RGB) {
  15972. internalFormat = gl.RGBA;
  15973. needConversion = true;
  15974. }
  15975. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15976. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15977. if (texture.width % 4 !== 0) {
  15978. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15979. }
  15980. // Data are known to be in +X +Y +Z -X -Y -Z
  15981. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15982. var faceData = data[faceIndex];
  15983. if (compression) {
  15984. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15985. }
  15986. else {
  15987. if (needConversion) {
  15988. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15989. }
  15990. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15991. }
  15992. }
  15993. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15994. if (isPot && texture.generateMipMaps && level === 0) {
  15995. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15996. }
  15997. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15998. // this.resetTextureCache();
  15999. texture.isReady = true;
  16000. };
  16001. /**
  16002. * Creates a new raw cube texture
  16003. * @param data defines the array of data to use to create each face
  16004. * @param size defines the size of the textures
  16005. * @param format defines the format of the data
  16006. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16007. * @param generateMipMaps defines if the engine should generate the mip levels
  16008. * @param invertY defines if data must be stored with Y axis inverted
  16009. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16010. * @param compression defines the compression used (null by default)
  16011. * @returns the cube texture as an InternalTexture
  16012. */
  16013. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16014. if (compression === void 0) { compression = null; }
  16015. var gl = this._gl;
  16016. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16017. texture.isCube = true;
  16018. texture.generateMipMaps = generateMipMaps;
  16019. texture.format = format;
  16020. texture.type = type;
  16021. if (!this._doNotHandleContextLost) {
  16022. texture._bufferViewArray = data;
  16023. }
  16024. var textureType = this._getWebGLTextureType(type);
  16025. var internalFormat = this._getInternalFormat(format);
  16026. if (internalFormat === gl.RGB) {
  16027. internalFormat = gl.RGBA;
  16028. }
  16029. var width = size;
  16030. var height = width;
  16031. texture.width = width;
  16032. texture.height = height;
  16033. // Double check on POT to generate Mips.
  16034. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16035. if (!isPot) {
  16036. generateMipMaps = false;
  16037. }
  16038. // Upload data if needed. The texture won't be ready until then.
  16039. if (data) {
  16040. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16041. }
  16042. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16043. // Filters
  16044. if (data && generateMipMaps) {
  16045. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16046. }
  16047. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16048. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16050. }
  16051. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16052. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16053. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16054. }
  16055. else {
  16056. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16059. }
  16060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16062. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16063. return texture;
  16064. };
  16065. /**
  16066. * Creates a new raw cube texture from a specified url
  16067. * @param url defines the url where the data is located
  16068. * @param scene defines the current scene
  16069. * @param size defines the size of the textures
  16070. * @param format defines the format of the data
  16071. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16072. * @param noMipmap defines if the engine should avoid generating the mip levels
  16073. * @param callback defines a callback used to extract texture data from loaded data
  16074. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16075. * @param onLoad defines a callback called when texture is loaded
  16076. * @param onError defines a callback called if there is an error
  16077. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16078. * @param invertY defines if data must be stored with Y axis inverted
  16079. * @returns the cube texture as an InternalTexture
  16080. */
  16081. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16082. var _this = this;
  16083. if (onLoad === void 0) { onLoad = null; }
  16084. if (onError === void 0) { onError = null; }
  16085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16086. if (invertY === void 0) { invertY = false; }
  16087. var gl = this._gl;
  16088. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16089. scene._addPendingData(texture);
  16090. texture.url = url;
  16091. this._internalTexturesCache.push(texture);
  16092. var onerror = function (request, exception) {
  16093. scene._removePendingData(texture);
  16094. if (onError && request) {
  16095. onError(request.status + " " + request.statusText, exception);
  16096. }
  16097. };
  16098. var internalCallback = function (data) {
  16099. var width = texture.width;
  16100. var faceDataArrays = callback(data);
  16101. if (!faceDataArrays) {
  16102. return;
  16103. }
  16104. if (mipmapGenerator) {
  16105. var textureType = _this._getWebGLTextureType(type);
  16106. var internalFormat = _this._getInternalFormat(format);
  16107. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16108. var needConversion = false;
  16109. if (internalFormat === gl.RGB) {
  16110. internalFormat = gl.RGBA;
  16111. needConversion = true;
  16112. }
  16113. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16114. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16115. var mipData = mipmapGenerator(faceDataArrays);
  16116. for (var level = 0; level < mipData.length; level++) {
  16117. var mipSize = width >> level;
  16118. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16119. var mipFaceData = mipData[level][faceIndex];
  16120. if (needConversion) {
  16121. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16122. }
  16123. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16124. }
  16125. }
  16126. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16127. }
  16128. else {
  16129. texture.generateMipMaps = !noMipmap;
  16130. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16131. }
  16132. texture.isReady = true;
  16133. // this.resetTextureCache();
  16134. scene._removePendingData(texture);
  16135. if (onLoad) {
  16136. onLoad();
  16137. }
  16138. };
  16139. this._loadFile(url, function (data) {
  16140. internalCallback(data);
  16141. }, undefined, scene.database, true, onerror);
  16142. return texture;
  16143. };
  16144. ;
  16145. /**
  16146. * Update a raw 3D texture
  16147. * @param texture defines the texture to update
  16148. * @param data defines the data to store
  16149. * @param format defines the data format
  16150. * @param invertY defines if data must be stored with Y axis inverted
  16151. * @param compression defines the used compression (can be null)
  16152. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16153. */
  16154. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16155. if (compression === void 0) { compression = null; }
  16156. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16157. var internalType = this._getWebGLTextureType(textureType);
  16158. var internalFormat = this._getInternalFormat(format);
  16159. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16160. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16161. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16162. if (!this._doNotHandleContextLost) {
  16163. texture._bufferView = data;
  16164. texture.format = format;
  16165. texture.invertY = invertY;
  16166. texture._compression = compression;
  16167. }
  16168. if (texture.width % 4 !== 0) {
  16169. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16170. }
  16171. if (compression && data) {
  16172. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16173. }
  16174. else {
  16175. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16176. }
  16177. if (texture.generateMipMaps) {
  16178. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16179. }
  16180. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16181. // this.resetTextureCache();
  16182. texture.isReady = true;
  16183. };
  16184. /**
  16185. * Creates a new raw 3D texture
  16186. * @param data defines the data used to create the texture
  16187. * @param width defines the width of the texture
  16188. * @param height defines the height of the texture
  16189. * @param depth defines the depth of the texture
  16190. * @param format defines the format of the texture
  16191. * @param generateMipMaps defines if the engine must generate mip levels
  16192. * @param invertY defines if data must be stored with Y axis inverted
  16193. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16194. * @param compression defines the compressed used (can be null)
  16195. * @param textureType defines the compressed used (can be null)
  16196. * @returns a new raw 3D texture (stored in an InternalTexture)
  16197. */
  16198. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16199. if (compression === void 0) { compression = null; }
  16200. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16201. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16202. texture.baseWidth = width;
  16203. texture.baseHeight = height;
  16204. texture.baseDepth = depth;
  16205. texture.width = width;
  16206. texture.height = height;
  16207. texture.depth = depth;
  16208. texture.format = format;
  16209. texture.type = textureType;
  16210. texture.generateMipMaps = generateMipMaps;
  16211. texture.samplingMode = samplingMode;
  16212. texture.is3D = true;
  16213. if (!this._doNotHandleContextLost) {
  16214. texture._bufferView = data;
  16215. }
  16216. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16217. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16218. // Filters
  16219. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16220. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16221. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16222. if (generateMipMaps) {
  16223. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16224. }
  16225. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16226. this._internalTexturesCache.push(texture);
  16227. return texture;
  16228. };
  16229. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16230. var gl = this._gl;
  16231. if (!gl) {
  16232. return;
  16233. }
  16234. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16235. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16236. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16237. if (!noMipmap && !isCompressed) {
  16238. gl.generateMipmap(gl.TEXTURE_2D);
  16239. }
  16240. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16241. // this.resetTextureCache();
  16242. if (scene) {
  16243. scene._removePendingData(texture);
  16244. }
  16245. texture.onLoadedObservable.notifyObservers(texture);
  16246. texture.onLoadedObservable.clear();
  16247. };
  16248. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16249. var _this = this;
  16250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16251. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16252. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16253. var gl = this._gl;
  16254. if (!gl) {
  16255. return;
  16256. }
  16257. if (!texture._webGLTexture) {
  16258. // this.resetTextureCache();
  16259. if (scene) {
  16260. scene._removePendingData(texture);
  16261. }
  16262. return;
  16263. }
  16264. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16265. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16266. texture.baseWidth = width;
  16267. texture.baseHeight = height;
  16268. texture.width = potWidth;
  16269. texture.height = potHeight;
  16270. texture.isReady = true;
  16271. if (processFunction(potWidth, potHeight, function () {
  16272. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16273. })) {
  16274. // Returning as texture needs extra async steps
  16275. return;
  16276. }
  16277. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16278. };
  16279. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16280. // Create new RGBA data container.
  16281. var rgbaData;
  16282. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16283. rgbaData = new Float32Array(width * height * 4);
  16284. }
  16285. else {
  16286. rgbaData = new Uint32Array(width * height * 4);
  16287. }
  16288. // Convert each pixel.
  16289. for (var x = 0; x < width; x++) {
  16290. for (var y = 0; y < height; y++) {
  16291. var index = (y * width + x) * 3;
  16292. var newIndex = (y * width + x) * 4;
  16293. // Map Old Value to new value.
  16294. rgbaData[newIndex + 0] = rgbData[index + 0];
  16295. rgbaData[newIndex + 1] = rgbData[index + 1];
  16296. rgbaData[newIndex + 2] = rgbData[index + 2];
  16297. // Add fully opaque alpha channel.
  16298. rgbaData[newIndex + 3] = 1;
  16299. }
  16300. }
  16301. return rgbaData;
  16302. };
  16303. /** @hidden */
  16304. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16305. var gl = this._gl;
  16306. if (texture._framebuffer) {
  16307. gl.deleteFramebuffer(texture._framebuffer);
  16308. texture._framebuffer = null;
  16309. }
  16310. if (texture._depthStencilBuffer) {
  16311. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16312. texture._depthStencilBuffer = null;
  16313. }
  16314. if (texture._MSAAFramebuffer) {
  16315. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16316. texture._MSAAFramebuffer = null;
  16317. }
  16318. if (texture._MSAARenderBuffer) {
  16319. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16320. texture._MSAARenderBuffer = null;
  16321. }
  16322. };
  16323. /** @hidden */
  16324. Engine.prototype._releaseTexture = function (texture) {
  16325. var gl = this._gl;
  16326. this._releaseFramebufferObjects(texture);
  16327. gl.deleteTexture(texture._webGLTexture);
  16328. // Unbind channels
  16329. this.unbindAllTextures();
  16330. var index = this._internalTexturesCache.indexOf(texture);
  16331. if (index !== -1) {
  16332. this._internalTexturesCache.splice(index, 1);
  16333. }
  16334. // Integrated fixed lod samplers.
  16335. if (texture._lodTextureHigh) {
  16336. texture._lodTextureHigh.dispose();
  16337. }
  16338. if (texture._lodTextureMid) {
  16339. texture._lodTextureMid.dispose();
  16340. }
  16341. if (texture._lodTextureLow) {
  16342. texture._lodTextureLow.dispose();
  16343. }
  16344. // Set output texture of post process to null if the texture has been released/disposed
  16345. this.scenes.forEach(function (scene) {
  16346. scene.postProcesses.forEach(function (postProcess) {
  16347. if (postProcess._outputTexture == texture) {
  16348. postProcess._outputTexture = null;
  16349. }
  16350. });
  16351. scene.cameras.forEach(function (camera) {
  16352. camera._postProcesses.forEach(function (postProcess) {
  16353. if (postProcess) {
  16354. if (postProcess._outputTexture == texture) {
  16355. postProcess._outputTexture = null;
  16356. }
  16357. }
  16358. });
  16359. });
  16360. });
  16361. };
  16362. Engine.prototype.setProgram = function (program) {
  16363. if (this._currentProgram !== program) {
  16364. this._gl.useProgram(program);
  16365. this._currentProgram = program;
  16366. }
  16367. };
  16368. /**
  16369. * Binds an effect to the webGL context
  16370. * @param effect defines the effect to bind
  16371. */
  16372. Engine.prototype.bindSamplers = function (effect) {
  16373. this.setProgram(effect.getProgram());
  16374. var samplers = effect.getSamplers();
  16375. for (var index = 0; index < samplers.length; index++) {
  16376. var uniform = effect.getUniform(samplers[index]);
  16377. if (uniform) {
  16378. this._boundUniforms[index] = uniform;
  16379. }
  16380. }
  16381. this._currentEffect = null;
  16382. };
  16383. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16384. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16385. return;
  16386. }
  16387. // Remove
  16388. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16389. // Bind last to it
  16390. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16391. // Bind to dummy
  16392. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16393. };
  16394. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16395. if (!internalTexture) {
  16396. return -1;
  16397. }
  16398. internalTexture._initialSlot = channel;
  16399. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16400. if (channel !== internalTexture._designatedSlot) {
  16401. this._textureCollisions.addCount(1, false);
  16402. }
  16403. }
  16404. else {
  16405. if (channel !== internalTexture._designatedSlot) {
  16406. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16407. return internalTexture._designatedSlot;
  16408. }
  16409. else {
  16410. // No slot for this texture, let's pick a new one (if we find a free slot)
  16411. if (this._nextFreeTextureSlots.length) {
  16412. return this._nextFreeTextureSlots[0];
  16413. }
  16414. // We need to recycle the oldest bound texture, sorry.
  16415. this._textureCollisions.addCount(1, false);
  16416. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16417. }
  16418. }
  16419. }
  16420. return channel;
  16421. };
  16422. Engine.prototype._linkTrackers = function (previous, next) {
  16423. previous.next = next;
  16424. next.previous = previous;
  16425. };
  16426. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16427. var currentSlot = internalTexture._designatedSlot;
  16428. if (currentSlot === -1) {
  16429. return -1;
  16430. }
  16431. internalTexture._designatedSlot = -1;
  16432. if (this.disableTextureBindingOptimization) {
  16433. return -1;
  16434. }
  16435. // Remove from bound list
  16436. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16437. // Free the slot
  16438. this._boundTexturesCache[currentSlot] = null;
  16439. this._nextFreeTextureSlots.push(currentSlot);
  16440. return currentSlot;
  16441. };
  16442. Engine.prototype._activateCurrentTexture = function () {
  16443. if (this._currentTextureChannel !== this._activeChannel) {
  16444. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16445. this._currentTextureChannel = this._activeChannel;
  16446. }
  16447. };
  16448. /** @hidden */
  16449. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16450. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16451. if (force === void 0) { force = false; }
  16452. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16453. this._activeChannel = texture._designatedSlot;
  16454. }
  16455. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16456. var isTextureForRendering = texture && texture._initialSlot > -1;
  16457. if (currentTextureBound !== texture || force) {
  16458. if (currentTextureBound) {
  16459. this._removeDesignatedSlot(currentTextureBound);
  16460. }
  16461. this._activateCurrentTexture();
  16462. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16463. this._boundTexturesCache[this._activeChannel] = texture;
  16464. if (texture) {
  16465. if (!this.disableTextureBindingOptimization) {
  16466. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16467. if (slotIndex > -1) {
  16468. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16469. }
  16470. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16471. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16472. }
  16473. texture._designatedSlot = this._activeChannel;
  16474. }
  16475. }
  16476. else if (forTextureDataUpdate) {
  16477. this._activateCurrentTexture();
  16478. }
  16479. if (isTextureForRendering && !forTextureDataUpdate) {
  16480. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16481. }
  16482. };
  16483. /** @hidden */
  16484. Engine.prototype._bindTexture = function (channel, texture) {
  16485. if (channel < 0) {
  16486. return;
  16487. }
  16488. if (texture) {
  16489. channel = this._getCorrectTextureChannel(channel, texture);
  16490. }
  16491. this._activeChannel = channel;
  16492. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16493. };
  16494. /**
  16495. * Sets a texture to the webGL context from a postprocess
  16496. * @param channel defines the channel to use
  16497. * @param postProcess defines the source postprocess
  16498. */
  16499. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16500. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16501. };
  16502. /**
  16503. * Binds the output of the passed in post process to the texture channel specified
  16504. * @param channel The channel the texture should be bound to
  16505. * @param postProcess The post process which's output should be bound
  16506. */
  16507. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16508. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16509. };
  16510. /**
  16511. * Unbind all textures from the webGL context
  16512. */
  16513. Engine.prototype.unbindAllTextures = function () {
  16514. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16515. this._activeChannel = channel;
  16516. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16517. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16518. if (this.webGLVersion > 1) {
  16519. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16520. }
  16521. }
  16522. };
  16523. /**
  16524. * Sets a texture to the according uniform.
  16525. * @param channel The texture channel
  16526. * @param uniform The uniform to set
  16527. * @param texture The texture to apply
  16528. */
  16529. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16530. if (channel < 0) {
  16531. return;
  16532. }
  16533. if (uniform) {
  16534. this._boundUniforms[channel] = uniform;
  16535. }
  16536. this._setTexture(channel, texture);
  16537. };
  16538. /**
  16539. * Sets a depth stencil texture from a render target to the according uniform.
  16540. * @param channel The texture channel
  16541. * @param uniform The uniform to set
  16542. * @param texture The render target texture containing the depth stencil texture to apply
  16543. */
  16544. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16545. if (channel < 0) {
  16546. return;
  16547. }
  16548. if (uniform) {
  16549. this._boundUniforms[channel] = uniform;
  16550. }
  16551. if (!texture || !texture.depthStencilTexture) {
  16552. this._setTexture(channel, null);
  16553. }
  16554. else {
  16555. this._setTexture(channel, texture, false, true);
  16556. }
  16557. };
  16558. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16559. var uniform = this._boundUniforms[sourceSlot];
  16560. if (uniform._currentState === destination) {
  16561. return;
  16562. }
  16563. this._gl.uniform1i(uniform, destination);
  16564. uniform._currentState = destination;
  16565. };
  16566. Engine.prototype._getTextureWrapMode = function (mode) {
  16567. switch (mode) {
  16568. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16569. return this._gl.REPEAT;
  16570. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16571. return this._gl.CLAMP_TO_EDGE;
  16572. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16573. return this._gl.MIRRORED_REPEAT;
  16574. }
  16575. return this._gl.REPEAT;
  16576. };
  16577. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16578. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16579. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16580. // Not ready?
  16581. if (!texture) {
  16582. if (this._boundTexturesCache[channel] != null) {
  16583. this._activeChannel = channel;
  16584. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16585. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16586. if (this.webGLVersion > 1) {
  16587. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16588. }
  16589. }
  16590. return false;
  16591. }
  16592. // Video
  16593. if (texture.video) {
  16594. this._activeChannel = channel;
  16595. texture.update();
  16596. }
  16597. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16598. texture.delayLoad();
  16599. return false;
  16600. }
  16601. var internalTexture;
  16602. if (depthStencilTexture) {
  16603. internalTexture = texture.depthStencilTexture;
  16604. }
  16605. else if (texture.isReady()) {
  16606. internalTexture = texture.getInternalTexture();
  16607. }
  16608. else if (texture.isCube) {
  16609. internalTexture = this.emptyCubeTexture;
  16610. }
  16611. else if (texture.is3D) {
  16612. internalTexture = this.emptyTexture3D;
  16613. }
  16614. else {
  16615. internalTexture = this.emptyTexture;
  16616. }
  16617. if (!isPartOfTextureArray) {
  16618. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16619. }
  16620. var needToBind = true;
  16621. if (this._boundTexturesCache[channel] === internalTexture) {
  16622. this._moveBoundTextureOnTop(internalTexture);
  16623. if (!isPartOfTextureArray) {
  16624. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16625. }
  16626. needToBind = false;
  16627. }
  16628. this._activeChannel = channel;
  16629. if (internalTexture && internalTexture.is3D) {
  16630. if (needToBind) {
  16631. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16632. }
  16633. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16634. internalTexture._cachedWrapU = texture.wrapU;
  16635. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16636. }
  16637. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16638. internalTexture._cachedWrapV = texture.wrapV;
  16639. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16640. }
  16641. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16642. internalTexture._cachedWrapR = texture.wrapR;
  16643. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16644. }
  16645. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16646. }
  16647. else if (internalTexture && internalTexture.isCube) {
  16648. if (needToBind) {
  16649. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16650. }
  16651. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16652. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16653. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16654. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16655. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16656. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16657. }
  16658. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16659. }
  16660. else {
  16661. if (needToBind) {
  16662. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16663. }
  16664. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16665. internalTexture._cachedWrapU = texture.wrapU;
  16666. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16667. }
  16668. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16669. internalTexture._cachedWrapV = texture.wrapV;
  16670. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16671. }
  16672. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16673. }
  16674. return true;
  16675. };
  16676. /**
  16677. * Sets an array of texture to the webGL context
  16678. * @param channel defines the channel where the texture array must be set
  16679. * @param uniform defines the associated uniform location
  16680. * @param textures defines the array of textures to bind
  16681. */
  16682. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16683. if (channel < 0 || !uniform) {
  16684. return;
  16685. }
  16686. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16687. this._textureUnits = new Int32Array(textures.length);
  16688. }
  16689. for (var i = 0; i < textures.length; i++) {
  16690. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16691. }
  16692. this._gl.uniform1iv(uniform, this._textureUnits);
  16693. for (var index = 0; index < textures.length; index++) {
  16694. this._setTexture(this._textureUnits[index], textures[index], true);
  16695. }
  16696. };
  16697. /** @hidden */
  16698. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16699. var internalTexture = texture.getInternalTexture();
  16700. if (!internalTexture) {
  16701. return;
  16702. }
  16703. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16704. var value = texture.anisotropicFilteringLevel;
  16705. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16706. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16707. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16708. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16709. }
  16710. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16711. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16712. internalTexture._cachedAnisotropicFilteringLevel = value;
  16713. }
  16714. };
  16715. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16716. this._bindTextureDirectly(target, texture, true, true);
  16717. this._gl.texParameterf(target, parameter, value);
  16718. };
  16719. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16720. if (texture) {
  16721. this._bindTextureDirectly(target, texture, true, true);
  16722. }
  16723. this._gl.texParameteri(target, parameter, value);
  16724. };
  16725. /**
  16726. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16727. * @param x defines the x coordinate of the rectangle where pixels must be read
  16728. * @param y defines the y coordinate of the rectangle where pixels must be read
  16729. * @param width defines the width of the rectangle where pixels must be read
  16730. * @param height defines the height of the rectangle where pixels must be read
  16731. * @returns a Uint8Array containing RGBA colors
  16732. */
  16733. Engine.prototype.readPixels = function (x, y, width, height) {
  16734. var data = new Uint8Array(height * width * 4);
  16735. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16736. return data;
  16737. };
  16738. /**
  16739. * Add an externaly attached data from its key.
  16740. * This method call will fail and return false, if such key already exists.
  16741. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16742. * @param key the unique key that identifies the data
  16743. * @param data the data object to associate to the key for this Engine instance
  16744. * @return true if no such key were already present and the data was added successfully, false otherwise
  16745. */
  16746. Engine.prototype.addExternalData = function (key, data) {
  16747. if (!this._externalData) {
  16748. this._externalData = new BABYLON.StringDictionary();
  16749. }
  16750. return this._externalData.add(key, data);
  16751. };
  16752. /**
  16753. * Get an externaly attached data from its key
  16754. * @param key the unique key that identifies the data
  16755. * @return the associated data, if present (can be null), or undefined if not present
  16756. */
  16757. Engine.prototype.getExternalData = function (key) {
  16758. if (!this._externalData) {
  16759. this._externalData = new BABYLON.StringDictionary();
  16760. }
  16761. return this._externalData.get(key);
  16762. };
  16763. /**
  16764. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16765. * @param key the unique key that identifies the data
  16766. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16767. * @return the associated data, can be null if the factory returned null.
  16768. */
  16769. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16770. if (!this._externalData) {
  16771. this._externalData = new BABYLON.StringDictionary();
  16772. }
  16773. return this._externalData.getOrAddWithFactory(key, factory);
  16774. };
  16775. /**
  16776. * Remove an externaly attached data from the Engine instance
  16777. * @param key the unique key that identifies the data
  16778. * @return true if the data was successfully removed, false if it doesn't exist
  16779. */
  16780. Engine.prototype.removeExternalData = function (key) {
  16781. if (!this._externalData) {
  16782. this._externalData = new BABYLON.StringDictionary();
  16783. }
  16784. return this._externalData.remove(key);
  16785. };
  16786. /**
  16787. * Unbind all vertex attributes from the webGL context
  16788. */
  16789. Engine.prototype.unbindAllAttributes = function () {
  16790. if (this._mustWipeVertexAttributes) {
  16791. this._mustWipeVertexAttributes = false;
  16792. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16793. this._gl.disableVertexAttribArray(i);
  16794. this._vertexAttribArraysEnabled[i] = false;
  16795. this._currentBufferPointers[i].active = false;
  16796. }
  16797. return;
  16798. }
  16799. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16800. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16801. continue;
  16802. }
  16803. this._gl.disableVertexAttribArray(i);
  16804. this._vertexAttribArraysEnabled[i] = false;
  16805. this._currentBufferPointers[i].active = false;
  16806. }
  16807. };
  16808. /**
  16809. * 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
  16810. */
  16811. Engine.prototype.releaseEffects = function () {
  16812. for (var name in this._compiledEffects) {
  16813. this._deleteProgram(this._compiledEffects[name]._program);
  16814. }
  16815. this._compiledEffects = {};
  16816. };
  16817. /**
  16818. * Dispose and release all associated resources
  16819. */
  16820. Engine.prototype.dispose = function () {
  16821. this.hideLoadingUI();
  16822. this.stopRenderLoop();
  16823. // Release postProcesses
  16824. while (this.postProcesses.length) {
  16825. this.postProcesses[0].dispose();
  16826. }
  16827. // Empty texture
  16828. if (this._emptyTexture) {
  16829. this._releaseTexture(this._emptyTexture);
  16830. this._emptyTexture = null;
  16831. }
  16832. if (this._emptyCubeTexture) {
  16833. this._releaseTexture(this._emptyCubeTexture);
  16834. this._emptyCubeTexture = null;
  16835. }
  16836. // Rescale PP
  16837. if (this._rescalePostProcess) {
  16838. this._rescalePostProcess.dispose();
  16839. }
  16840. // Release scenes
  16841. while (this.scenes.length) {
  16842. this.scenes[0].dispose();
  16843. }
  16844. // Release audio engine
  16845. if (Engine.audioEngine) {
  16846. Engine.audioEngine.dispose();
  16847. }
  16848. // Release effects
  16849. this.releaseEffects();
  16850. // Unbind
  16851. this.unbindAllAttributes();
  16852. this._boundUniforms = [];
  16853. if (this._dummyFramebuffer) {
  16854. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16855. }
  16856. //WebVR
  16857. this.disableVR();
  16858. // Events
  16859. if (BABYLON.Tools.IsWindowObjectExist()) {
  16860. window.removeEventListener("blur", this._onBlur);
  16861. window.removeEventListener("focus", this._onFocus);
  16862. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16863. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16864. if (this._renderingCanvas) {
  16865. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16866. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16867. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16868. if (!this._doNotHandleContextLost) {
  16869. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16870. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16871. }
  16872. }
  16873. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16874. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16875. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16876. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16877. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16878. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16879. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16880. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16881. if (this._onVrDisplayConnect) {
  16882. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16883. if (this._onVrDisplayDisconnect) {
  16884. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16885. }
  16886. if (this._onVrDisplayPresentChange) {
  16887. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16888. }
  16889. this._onVrDisplayConnect = null;
  16890. this._onVrDisplayDisconnect = null;
  16891. }
  16892. }
  16893. // Remove from Instances
  16894. var index = Engine.Instances.indexOf(this);
  16895. if (index >= 0) {
  16896. Engine.Instances.splice(index, 1);
  16897. }
  16898. this._workingCanvas = null;
  16899. this._workingContext = null;
  16900. this._currentBufferPointers = [];
  16901. this._renderingCanvas = null;
  16902. this._currentProgram = null;
  16903. this._bindedRenderFunction = null;
  16904. this.onResizeObservable.clear();
  16905. this.onCanvasBlurObservable.clear();
  16906. this.onCanvasFocusObservable.clear();
  16907. this.onCanvasPointerOutObservable.clear();
  16908. this.onBeginFrameObservable.clear();
  16909. this.onEndFrameObservable.clear();
  16910. BABYLON.Effect.ResetCache();
  16911. // Abort active requests
  16912. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16913. var request = _a[_i];
  16914. request.abort();
  16915. }
  16916. };
  16917. // Loading screen
  16918. /**
  16919. * Display the loading screen
  16920. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16921. */
  16922. Engine.prototype.displayLoadingUI = function () {
  16923. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16924. return;
  16925. }
  16926. var loadingScreen = this.loadingScreen;
  16927. if (loadingScreen) {
  16928. loadingScreen.displayLoadingUI();
  16929. }
  16930. };
  16931. /**
  16932. * Hide the loading screen
  16933. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16934. */
  16935. Engine.prototype.hideLoadingUI = function () {
  16936. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16937. return;
  16938. }
  16939. var loadingScreen = this.loadingScreen;
  16940. if (loadingScreen) {
  16941. loadingScreen.hideLoadingUI();
  16942. }
  16943. };
  16944. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16945. /**
  16946. * Gets the current loading screen object
  16947. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16948. */
  16949. get: function () {
  16950. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16951. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16952. return this._loadingScreen;
  16953. },
  16954. /**
  16955. * Sets the current loading screen object
  16956. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16957. */
  16958. set: function (loadingScreen) {
  16959. this._loadingScreen = loadingScreen;
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16965. /**
  16966. * Sets the current loading screen text
  16967. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16968. */
  16969. set: function (text) {
  16970. this.loadingScreen.loadingUIText = text;
  16971. },
  16972. enumerable: true,
  16973. configurable: true
  16974. });
  16975. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16976. /**
  16977. * Sets the current loading screen background color
  16978. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16979. */
  16980. set: function (color) {
  16981. this.loadingScreen.loadingUIBackgroundColor = color;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. /**
  16987. * Attach a new callback raised when context lost event is fired
  16988. * @param callback defines the callback to call
  16989. */
  16990. Engine.prototype.attachContextLostEvent = function (callback) {
  16991. if (this._renderingCanvas) {
  16992. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16993. }
  16994. };
  16995. /**
  16996. * Attach a new callback raised when context restored event is fired
  16997. * @param callback defines the callback to call
  16998. */
  16999. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17000. if (this._renderingCanvas) {
  17001. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17002. }
  17003. };
  17004. /**
  17005. * Gets the source code of the vertex shader associated with a specific webGL program
  17006. * @param program defines the program to use
  17007. * @returns a string containing the source code of the vertex shader associated with the program
  17008. */
  17009. Engine.prototype.getVertexShaderSource = function (program) {
  17010. var shaders = this._gl.getAttachedShaders(program);
  17011. if (!shaders) {
  17012. return null;
  17013. }
  17014. return this._gl.getShaderSource(shaders[0]);
  17015. };
  17016. /**
  17017. * Gets the source code of the fragment shader associated with a specific webGL program
  17018. * @param program defines the program to use
  17019. * @returns a string containing the source code of the fragment shader associated with the program
  17020. */
  17021. Engine.prototype.getFragmentShaderSource = function (program) {
  17022. var shaders = this._gl.getAttachedShaders(program);
  17023. if (!shaders) {
  17024. return null;
  17025. }
  17026. return this._gl.getShaderSource(shaders[1]);
  17027. };
  17028. /**
  17029. * Get the current error code of the webGL context
  17030. * @returns the error code
  17031. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17032. */
  17033. Engine.prototype.getError = function () {
  17034. return this._gl.getError();
  17035. };
  17036. // FPS
  17037. /**
  17038. * Gets the current framerate
  17039. * @returns a number representing the framerate
  17040. */
  17041. Engine.prototype.getFps = function () {
  17042. return this._fps;
  17043. };
  17044. /**
  17045. * Gets the time spent between current and previous frame
  17046. * @returns a number representing the delta time in ms
  17047. */
  17048. Engine.prototype.getDeltaTime = function () {
  17049. return this._deltaTime;
  17050. };
  17051. Engine.prototype._measureFps = function () {
  17052. this._performanceMonitor.sampleFrame();
  17053. this._fps = this._performanceMonitor.averageFPS;
  17054. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17055. };
  17056. /** @hidden */
  17057. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17058. if (faceIndex === void 0) { faceIndex = -1; }
  17059. if (level === void 0) { level = 0; }
  17060. var gl = this._gl;
  17061. if (!this._dummyFramebuffer) {
  17062. var dummy = gl.createFramebuffer();
  17063. if (!dummy) {
  17064. throw new Error("Unable to create dummy framebuffer");
  17065. }
  17066. this._dummyFramebuffer = dummy;
  17067. }
  17068. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17069. if (faceIndex > -1) {
  17070. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17071. }
  17072. else {
  17073. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17074. }
  17075. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17076. var buffer;
  17077. switch (readType) {
  17078. case gl.UNSIGNED_BYTE:
  17079. buffer = new Uint8Array(4 * width * height);
  17080. readType = gl.UNSIGNED_BYTE;
  17081. break;
  17082. default:
  17083. buffer = new Float32Array(4 * width * height);
  17084. readType = gl.FLOAT;
  17085. break;
  17086. }
  17087. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17088. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17089. return buffer;
  17090. };
  17091. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17092. if (this._webGLVersion > 1) {
  17093. return this._caps.colorBufferFloat;
  17094. }
  17095. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17096. };
  17097. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17098. if (this._webGLVersion > 1) {
  17099. return this._caps.colorBufferFloat;
  17100. }
  17101. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17102. };
  17103. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17104. Engine.prototype._canRenderToFramebuffer = function (type) {
  17105. var gl = this._gl;
  17106. //clear existing errors
  17107. while (gl.getError() !== gl.NO_ERROR) { }
  17108. var successful = true;
  17109. var texture = gl.createTexture();
  17110. gl.bindTexture(gl.TEXTURE_2D, texture);
  17111. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17113. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17114. var fb = gl.createFramebuffer();
  17115. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17116. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17117. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17118. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17119. successful = successful && (gl.getError() === gl.NO_ERROR);
  17120. //try render by clearing frame buffer's color buffer
  17121. if (successful) {
  17122. gl.clear(gl.COLOR_BUFFER_BIT);
  17123. successful = successful && (gl.getError() === gl.NO_ERROR);
  17124. }
  17125. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17126. if (successful) {
  17127. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17128. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17129. var readFormat = gl.RGBA;
  17130. var readType = gl.UNSIGNED_BYTE;
  17131. var buffer = new Uint8Array(4);
  17132. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17133. successful = successful && (gl.getError() === gl.NO_ERROR);
  17134. }
  17135. //clean up
  17136. gl.deleteTexture(texture);
  17137. gl.deleteFramebuffer(fb);
  17138. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17139. //clear accumulated errors
  17140. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17141. return successful;
  17142. };
  17143. /** @hidden */
  17144. Engine.prototype._getWebGLTextureType = function (type) {
  17145. if (type === Engine.TEXTURETYPE_FLOAT) {
  17146. return this._gl.FLOAT;
  17147. }
  17148. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17149. // Add Half Float Constant.
  17150. return this._gl.HALF_FLOAT_OES;
  17151. }
  17152. return this._gl.UNSIGNED_BYTE;
  17153. };
  17154. ;
  17155. Engine.prototype._getInternalFormat = function (format) {
  17156. var internalFormat = this._gl.RGBA;
  17157. switch (format) {
  17158. case Engine.TEXTUREFORMAT_ALPHA:
  17159. internalFormat = this._gl.ALPHA;
  17160. break;
  17161. case Engine.TEXTUREFORMAT_LUMINANCE:
  17162. internalFormat = this._gl.LUMINANCE;
  17163. break;
  17164. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17165. internalFormat = this._gl.LUMINANCE_ALPHA;
  17166. break;
  17167. case Engine.TEXTUREFORMAT_RGB:
  17168. internalFormat = this._gl.RGB;
  17169. break;
  17170. case Engine.TEXTUREFORMAT_RGBA:
  17171. internalFormat = this._gl.RGBA;
  17172. break;
  17173. case Engine.TEXTUREFORMAT_R:
  17174. internalFormat = this._gl.RED;
  17175. break;
  17176. case Engine.TEXTUREFORMAT_RG:
  17177. internalFormat = this._gl.RG;
  17178. break;
  17179. }
  17180. return internalFormat;
  17181. };
  17182. /** @hidden */
  17183. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17184. if (this._webGLVersion === 1) {
  17185. if (format !== undefined) {
  17186. switch (format) {
  17187. case Engine.TEXTUREFORMAT_LUMINANCE:
  17188. return this._gl.LUMINANCE;
  17189. case Engine.TEXTUREFORMAT_ALPHA:
  17190. return this._gl.ALPHA;
  17191. }
  17192. }
  17193. return this._gl.RGBA;
  17194. }
  17195. if (type === Engine.TEXTURETYPE_FLOAT) {
  17196. if (format !== undefined) {
  17197. switch (format) {
  17198. case Engine.TEXTUREFORMAT_R:
  17199. return this._gl.R32F;
  17200. case Engine.TEXTUREFORMAT_RG:
  17201. return this._gl.RG32F;
  17202. case Engine.TEXTUREFORMAT_RGB:
  17203. return this._gl.RGB32F;
  17204. }
  17205. }
  17206. return this._gl.RGBA32F;
  17207. }
  17208. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17209. if (format) {
  17210. switch (format) {
  17211. case Engine.TEXTUREFORMAT_R:
  17212. return this._gl.R16F;
  17213. case Engine.TEXTUREFORMAT_RG:
  17214. return this._gl.RG16F;
  17215. case Engine.TEXTUREFORMAT_RGB:
  17216. return this._gl.RGB16F;
  17217. }
  17218. }
  17219. return this._gl.RGBA16F;
  17220. }
  17221. if (format !== undefined) {
  17222. switch (format) {
  17223. case Engine.TEXTUREFORMAT_LUMINANCE:
  17224. return this._gl.LUMINANCE;
  17225. case Engine.TEXTUREFORMAT_RGB:
  17226. return this._gl.RGB;
  17227. case Engine.TEXTUREFORMAT_R:
  17228. return this._gl.R8;
  17229. case Engine.TEXTUREFORMAT_RG:
  17230. return this._gl.RG8;
  17231. case Engine.TEXTUREFORMAT_ALPHA:
  17232. return this._gl.ALPHA;
  17233. }
  17234. }
  17235. return this._gl.RGBA;
  17236. };
  17237. ;
  17238. /** @hidden */
  17239. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17240. if (type === Engine.TEXTURETYPE_FLOAT) {
  17241. return this._gl.RGBA32F;
  17242. }
  17243. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17244. return this._gl.RGBA16F;
  17245. }
  17246. return this._gl.RGBA8;
  17247. };
  17248. ;
  17249. /**
  17250. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17251. * @return the new query
  17252. */
  17253. Engine.prototype.createQuery = function () {
  17254. return this._gl.createQuery();
  17255. };
  17256. /**
  17257. * Delete and release a webGL query
  17258. * @param query defines the query to delete
  17259. * @return the current engine
  17260. */
  17261. Engine.prototype.deleteQuery = function (query) {
  17262. this._gl.deleteQuery(query);
  17263. return this;
  17264. };
  17265. /**
  17266. * Check if a given query has resolved and got its value
  17267. * @param query defines the query to check
  17268. * @returns true if the query got its value
  17269. */
  17270. Engine.prototype.isQueryResultAvailable = function (query) {
  17271. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17272. };
  17273. /**
  17274. * Gets the value of a given query
  17275. * @param query defines the query to check
  17276. * @returns the value of the query
  17277. */
  17278. Engine.prototype.getQueryResult = function (query) {
  17279. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17280. };
  17281. /**
  17282. * Initiates an occlusion query
  17283. * @param algorithmType defines the algorithm to use
  17284. * @param query defines the query to use
  17285. * @returns the current engine
  17286. * @see http://doc.babylonjs.com/features/occlusionquery
  17287. */
  17288. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17289. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17290. this._gl.beginQuery(glAlgorithm, query);
  17291. return this;
  17292. };
  17293. /**
  17294. * Ends an occlusion query
  17295. * @see http://doc.babylonjs.com/features/occlusionquery
  17296. * @param algorithmType defines the algorithm to use
  17297. * @returns the current engine
  17298. */
  17299. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17300. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17301. this._gl.endQuery(glAlgorithm);
  17302. return this;
  17303. };
  17304. /* Time queries */
  17305. Engine.prototype._createTimeQuery = function () {
  17306. var timerQuery = this._caps.timerQuery;
  17307. if (timerQuery.createQueryEXT) {
  17308. return timerQuery.createQueryEXT();
  17309. }
  17310. return this.createQuery();
  17311. };
  17312. Engine.prototype._deleteTimeQuery = function (query) {
  17313. var timerQuery = this._caps.timerQuery;
  17314. if (timerQuery.deleteQueryEXT) {
  17315. timerQuery.deleteQueryEXT(query);
  17316. return;
  17317. }
  17318. this.deleteQuery(query);
  17319. };
  17320. Engine.prototype._getTimeQueryResult = function (query) {
  17321. var timerQuery = this._caps.timerQuery;
  17322. if (timerQuery.getQueryObjectEXT) {
  17323. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17324. }
  17325. return this.getQueryResult(query);
  17326. };
  17327. Engine.prototype._getTimeQueryAvailability = function (query) {
  17328. var timerQuery = this._caps.timerQuery;
  17329. if (timerQuery.getQueryObjectEXT) {
  17330. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17331. }
  17332. return this.isQueryResultAvailable(query);
  17333. };
  17334. /**
  17335. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17336. * Please note that only one query can be issued at a time
  17337. * @returns a time token used to track the time span
  17338. */
  17339. Engine.prototype.startTimeQuery = function () {
  17340. var timerQuery = this._caps.timerQuery;
  17341. if (!timerQuery) {
  17342. return null;
  17343. }
  17344. var token = new BABYLON._TimeToken();
  17345. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17346. if (this._caps.canUseTimestampForTimerQuery) {
  17347. token._startTimeQuery = this._createTimeQuery();
  17348. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17349. }
  17350. else {
  17351. if (this._currentNonTimestampToken) {
  17352. return this._currentNonTimestampToken;
  17353. }
  17354. token._timeElapsedQuery = this._createTimeQuery();
  17355. if (timerQuery.beginQueryEXT) {
  17356. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17357. }
  17358. else {
  17359. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17360. }
  17361. this._currentNonTimestampToken = token;
  17362. }
  17363. return token;
  17364. };
  17365. /**
  17366. * Ends a time query
  17367. * @param token defines the token used to measure the time span
  17368. * @returns the time spent (in ns)
  17369. */
  17370. Engine.prototype.endTimeQuery = function (token) {
  17371. var timerQuery = this._caps.timerQuery;
  17372. if (!timerQuery || !token) {
  17373. return -1;
  17374. }
  17375. if (this._caps.canUseTimestampForTimerQuery) {
  17376. if (!token._startTimeQuery) {
  17377. return -1;
  17378. }
  17379. if (!token._endTimeQuery) {
  17380. token._endTimeQuery = this._createTimeQuery();
  17381. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17382. }
  17383. }
  17384. else if (!token._timeElapsedQueryEnded) {
  17385. if (!token._timeElapsedQuery) {
  17386. return -1;
  17387. }
  17388. if (timerQuery.endQueryEXT) {
  17389. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17390. }
  17391. else {
  17392. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17393. }
  17394. token._timeElapsedQueryEnded = true;
  17395. }
  17396. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17397. var available = false;
  17398. if (token._endTimeQuery) {
  17399. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17400. }
  17401. else if (token._timeElapsedQuery) {
  17402. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17403. }
  17404. if (available && !disjoint) {
  17405. var result = 0;
  17406. if (this._caps.canUseTimestampForTimerQuery) {
  17407. if (!token._startTimeQuery || !token._endTimeQuery) {
  17408. return -1;
  17409. }
  17410. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17411. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17412. result = timeEnd - timeStart;
  17413. this._deleteTimeQuery(token._startTimeQuery);
  17414. this._deleteTimeQuery(token._endTimeQuery);
  17415. token._startTimeQuery = null;
  17416. token._endTimeQuery = null;
  17417. }
  17418. else {
  17419. if (!token._timeElapsedQuery) {
  17420. return -1;
  17421. }
  17422. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17423. this._deleteTimeQuery(token._timeElapsedQuery);
  17424. token._timeElapsedQuery = null;
  17425. token._timeElapsedQueryEnded = false;
  17426. this._currentNonTimestampToken = null;
  17427. }
  17428. return result;
  17429. }
  17430. return -1;
  17431. };
  17432. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17433. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17434. };
  17435. // Transform feedback
  17436. /**
  17437. * Creates a webGL transform feedback object
  17438. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17439. * @returns the webGL transform feedback object
  17440. */
  17441. Engine.prototype.createTransformFeedback = function () {
  17442. return this._gl.createTransformFeedback();
  17443. };
  17444. /**
  17445. * Delete a webGL transform feedback object
  17446. * @param value defines the webGL transform feedback object to delete
  17447. */
  17448. Engine.prototype.deleteTransformFeedback = function (value) {
  17449. this._gl.deleteTransformFeedback(value);
  17450. };
  17451. /**
  17452. * Bind a webGL transform feedback object to the webgl context
  17453. * @param value defines the webGL transform feedback object to bind
  17454. */
  17455. Engine.prototype.bindTransformFeedback = function (value) {
  17456. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17457. };
  17458. /**
  17459. * Begins a transform feedback operation
  17460. * @param usePoints defines if points or triangles must be used
  17461. */
  17462. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17463. if (usePoints === void 0) { usePoints = true; }
  17464. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17465. };
  17466. /**
  17467. * Ends a transform feedback operation
  17468. */
  17469. Engine.prototype.endTransformFeedback = function () {
  17470. this._gl.endTransformFeedback();
  17471. };
  17472. /**
  17473. * Specify the varyings to use with transform feedback
  17474. * @param program defines the associated webGL program
  17475. * @param value defines the list of strings representing the varying names
  17476. */
  17477. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17478. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17479. };
  17480. /**
  17481. * Bind a webGL buffer for a transform feedback operation
  17482. * @param value defines the webGL buffer to bind
  17483. */
  17484. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17485. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17486. };
  17487. /** @hidden */
  17488. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17489. var _this = this;
  17490. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17491. this._activeRequests.push(request);
  17492. request.onCompleteObservable.add(function (request) {
  17493. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17494. });
  17495. return request;
  17496. };
  17497. /** @hidden */
  17498. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17499. var _this = this;
  17500. return new Promise(function (resolve, reject) {
  17501. _this._loadFile(url, function (data) {
  17502. resolve(data);
  17503. }, undefined, database, useArrayBuffer, function (request, exception) {
  17504. reject(exception);
  17505. });
  17506. });
  17507. };
  17508. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17509. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17510. var onload = function (data) {
  17511. loadedFiles[index] = data;
  17512. loadedFiles._internalCount++;
  17513. if (loadedFiles._internalCount === 6) {
  17514. onfinish(loadedFiles);
  17515. }
  17516. };
  17517. var onerror = function (request, exception) {
  17518. if (onErrorCallBack && request) {
  17519. onErrorCallBack(request.status + " " + request.statusText, exception);
  17520. }
  17521. };
  17522. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17523. };
  17524. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17525. if (onError === void 0) { onError = null; }
  17526. var loadedFiles = [];
  17527. loadedFiles._internalCount = 0;
  17528. for (var index = 0; index < 6; index++) {
  17529. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17530. }
  17531. };
  17532. // Statics
  17533. /**
  17534. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17535. * @returns true if the engine can be created
  17536. * @ignorenaming
  17537. */
  17538. Engine.isSupported = function () {
  17539. try {
  17540. var tempcanvas = document.createElement("canvas");
  17541. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17542. return gl != null && !!window.WebGLRenderingContext;
  17543. }
  17544. catch (e) {
  17545. return false;
  17546. }
  17547. };
  17548. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17549. Engine.ExceptionList = [
  17550. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17551. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17552. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17553. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17554. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17555. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17556. ];
  17557. /** Gets the list of created engines */
  17558. Engine.Instances = new Array();
  17559. // Const statics
  17560. Engine._ALPHA_DISABLE = 0;
  17561. Engine._ALPHA_ADD = 1;
  17562. Engine._ALPHA_COMBINE = 2;
  17563. Engine._ALPHA_SUBTRACT = 3;
  17564. Engine._ALPHA_MULTIPLY = 4;
  17565. Engine._ALPHA_MAXIMIZED = 5;
  17566. Engine._ALPHA_ONEONE = 6;
  17567. Engine._ALPHA_PREMULTIPLIED = 7;
  17568. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17569. Engine._ALPHA_INTERPOLATE = 9;
  17570. Engine._ALPHA_SCREENMODE = 10;
  17571. Engine._DELAYLOADSTATE_NONE = 0;
  17572. Engine._DELAYLOADSTATE_LOADED = 1;
  17573. Engine._DELAYLOADSTATE_LOADING = 2;
  17574. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17575. Engine._TEXTUREFORMAT_ALPHA = 0;
  17576. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17577. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17578. Engine._TEXTUREFORMAT_RGB = 4;
  17579. Engine._TEXTUREFORMAT_RGBA = 5;
  17580. Engine._TEXTUREFORMAT_R = 6;
  17581. Engine._TEXTUREFORMAT_RG = 7;
  17582. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17583. Engine._TEXTURETYPE_FLOAT = 1;
  17584. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17585. // Depht or Stencil test Constants.
  17586. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17587. 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.
  17588. 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.
  17589. 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.
  17590. 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.
  17591. 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.
  17592. 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.
  17593. 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.
  17594. // Stencil Actions Constants.
  17595. Engine._KEEP = 0x1E00;
  17596. Engine._REPLACE = 0x1E01;
  17597. Engine._INCR = 0x1E02;
  17598. Engine._DECR = 0x1E03;
  17599. Engine._INVERT = 0x150A;
  17600. Engine._INCR_WRAP = 0x8507;
  17601. Engine._DECR_WRAP = 0x8508;
  17602. // Texture rescaling mode
  17603. Engine._SCALEMODE_FLOOR = 1;
  17604. Engine._SCALEMODE_NEAREST = 2;
  17605. Engine._SCALEMODE_CEILING = 3;
  17606. // Updatable statics so stick with vars here
  17607. /**
  17608. * Gets or sets the epsilon value used by collision engine
  17609. */
  17610. Engine.CollisionsEpsilon = 0.001;
  17611. /**
  17612. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17613. */
  17614. Engine.CodeRepository = "src/";
  17615. /**
  17616. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17617. */
  17618. Engine.ShadersRepository = "src/Shaders/";
  17619. return Engine;
  17620. }());
  17621. BABYLON.Engine = Engine;
  17622. })(BABYLON || (BABYLON = {}));
  17623. //# sourceMappingURL=babylon.engine.js.map
  17624. var BABYLON;
  17625. (function (BABYLON) {
  17626. /**
  17627. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17628. */
  17629. var Node = /** @class */ (function () {
  17630. /**
  17631. * Creates a new Node
  17632. * @param {string} name - the name and id to be given to this node
  17633. * @param {BABYLON.Scene} the scene this node will be added to
  17634. */
  17635. function Node(name, scene) {
  17636. if (scene === void 0) { scene = null; }
  17637. /**
  17638. * Gets or sets a string used to store user defined state for the node
  17639. */
  17640. this.state = "";
  17641. /**
  17642. * Gets or sets an object used to store user defined information for the node
  17643. */
  17644. this.metadata = null;
  17645. /**
  17646. * Gets or sets a boolean used to define if the node must be serialized
  17647. */
  17648. this.doNotSerialize = false;
  17649. /** @hidden */
  17650. this._isDisposed = false;
  17651. /**
  17652. * Gets a list of Animations associated with the node
  17653. */
  17654. this.animations = new Array();
  17655. this._ranges = {};
  17656. this._isEnabled = true;
  17657. this._isReady = true;
  17658. /** @hidden */
  17659. this._currentRenderId = -1;
  17660. this._parentRenderId = -1;
  17661. this._childRenderId = -1;
  17662. this._animationPropertiesOverride = null;
  17663. /**
  17664. * An event triggered when the mesh is disposed
  17665. */
  17666. this.onDisposeObservable = new BABYLON.Observable();
  17667. // Behaviors
  17668. this._behaviors = new Array();
  17669. this.name = name;
  17670. this.id = name;
  17671. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17672. this.uniqueId = this._scene.getUniqueId();
  17673. this._initCache();
  17674. }
  17675. /**
  17676. * Gets a boolean indicating if the node has been disposed
  17677. * @returns true if the node was disposed
  17678. */
  17679. Node.prototype.isDisposed = function () {
  17680. return this._isDisposed;
  17681. };
  17682. Object.defineProperty(Node.prototype, "parent", {
  17683. get: function () {
  17684. return this._parentNode;
  17685. },
  17686. /**
  17687. * Gets or sets the parent of the node
  17688. */
  17689. set: function (parent) {
  17690. if (this._parentNode === parent) {
  17691. return;
  17692. }
  17693. // Remove self from list of children of parent
  17694. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17695. var index = this._parentNode._children.indexOf(this);
  17696. if (index !== -1) {
  17697. this._parentNode._children.splice(index, 1);
  17698. }
  17699. }
  17700. // Store new parent
  17701. this._parentNode = parent;
  17702. // Add as child to new parent
  17703. if (this._parentNode) {
  17704. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17705. this._parentNode._children = new Array();
  17706. }
  17707. this._parentNode._children.push(this);
  17708. }
  17709. },
  17710. enumerable: true,
  17711. configurable: true
  17712. });
  17713. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17714. /**
  17715. * Gets or sets the animation properties override
  17716. */
  17717. get: function () {
  17718. if (!this._animationPropertiesOverride) {
  17719. return this._scene.animationPropertiesOverride;
  17720. }
  17721. return this._animationPropertiesOverride;
  17722. },
  17723. set: function (value) {
  17724. this._animationPropertiesOverride = value;
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. /**
  17730. * Gets a string idenfifying the name of the class
  17731. * @returns "Node" string
  17732. */
  17733. Node.prototype.getClassName = function () {
  17734. return "Node";
  17735. };
  17736. Object.defineProperty(Node.prototype, "onDispose", {
  17737. /**
  17738. * Sets a callback that will be raised when the node will be disposed
  17739. */
  17740. set: function (callback) {
  17741. if (this._onDisposeObserver) {
  17742. this.onDisposeObservable.remove(this._onDisposeObserver);
  17743. }
  17744. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. /**
  17750. * Gets the scene of the node
  17751. * @returns a {BABYLON.Scene}
  17752. */
  17753. Node.prototype.getScene = function () {
  17754. return this._scene;
  17755. };
  17756. /**
  17757. * Gets the engine of the node
  17758. * @returns a {BABYLON.Engine}
  17759. */
  17760. Node.prototype.getEngine = function () {
  17761. return this._scene.getEngine();
  17762. };
  17763. /**
  17764. * Attach a behavior to the node
  17765. * @see http://doc.babylonjs.com/features/behaviour
  17766. * @param behavior defines the behavior to attach
  17767. * @returns the current Node
  17768. */
  17769. Node.prototype.addBehavior = function (behavior) {
  17770. var _this = this;
  17771. var index = this._behaviors.indexOf(behavior);
  17772. if (index !== -1) {
  17773. return this;
  17774. }
  17775. behavior.init();
  17776. if (this._scene.isLoading) {
  17777. // We defer the attach when the scene will be loaded
  17778. this._scene.onDataLoadedObservable.addOnce(function () {
  17779. behavior.attach(_this);
  17780. });
  17781. }
  17782. else {
  17783. behavior.attach(this);
  17784. }
  17785. this._behaviors.push(behavior);
  17786. return this;
  17787. };
  17788. /**
  17789. * Remove an attached behavior
  17790. * @see http://doc.babylonjs.com/features/behaviour
  17791. * @param behavior defines the behavior to attach
  17792. * @returns the current Node
  17793. */
  17794. Node.prototype.removeBehavior = function (behavior) {
  17795. var index = this._behaviors.indexOf(behavior);
  17796. if (index === -1) {
  17797. return this;
  17798. }
  17799. this._behaviors[index].detach();
  17800. this._behaviors.splice(index, 1);
  17801. return this;
  17802. };
  17803. Object.defineProperty(Node.prototype, "behaviors", {
  17804. /**
  17805. * Gets the list of attached behaviors
  17806. * @see http://doc.babylonjs.com/features/behaviour
  17807. */
  17808. get: function () {
  17809. return this._behaviors;
  17810. },
  17811. enumerable: true,
  17812. configurable: true
  17813. });
  17814. /**
  17815. * Gets an attached behavior by name
  17816. * @param name defines the name of the behavior to look for
  17817. * @see http://doc.babylonjs.com/features/behaviour
  17818. * @returns null if behavior was not found else the requested behavior
  17819. */
  17820. Node.prototype.getBehaviorByName = function (name) {
  17821. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17822. var behavior = _a[_i];
  17823. if (behavior.name === name) {
  17824. return behavior;
  17825. }
  17826. }
  17827. return null;
  17828. };
  17829. /**
  17830. * Returns the world matrix of the node
  17831. * @returns a matrix containing the node's world matrix
  17832. */
  17833. Node.prototype.getWorldMatrix = function () {
  17834. return BABYLON.Matrix.Identity();
  17835. };
  17836. /** @hidden */
  17837. Node.prototype._getWorldMatrixDeterminant = function () {
  17838. return 1;
  17839. };
  17840. // override it in derived class if you add new variables to the cache
  17841. // and call the parent class method
  17842. /** @hidden */
  17843. Node.prototype._initCache = function () {
  17844. this._cache = {};
  17845. this._cache.parent = undefined;
  17846. };
  17847. /** @hidden */
  17848. Node.prototype.updateCache = function (force) {
  17849. if (!force && this.isSynchronized())
  17850. return;
  17851. this._cache.parent = this.parent;
  17852. this._updateCache();
  17853. };
  17854. // override it in derived class if you add new variables to the cache
  17855. // and call the parent class method if !ignoreParentClass
  17856. /** @hidden */
  17857. Node.prototype._updateCache = function (ignoreParentClass) {
  17858. };
  17859. // override it in derived class if you add new variables to the cache
  17860. /** @hidden */
  17861. Node.prototype._isSynchronized = function () {
  17862. return true;
  17863. };
  17864. /** @hidden */
  17865. Node.prototype._markSyncedWithParent = function () {
  17866. if (this.parent) {
  17867. this._parentRenderId = this.parent._childRenderId;
  17868. }
  17869. };
  17870. /** @hidden */
  17871. Node.prototype.isSynchronizedWithParent = function () {
  17872. if (!this.parent) {
  17873. return true;
  17874. }
  17875. if (this._parentRenderId !== this.parent._childRenderId) {
  17876. return false;
  17877. }
  17878. return this.parent.isSynchronized();
  17879. };
  17880. /** @hidden */
  17881. Node.prototype.isSynchronized = function (updateCache) {
  17882. var check = this.hasNewParent();
  17883. check = check || !this.isSynchronizedWithParent();
  17884. check = check || !this._isSynchronized();
  17885. if (updateCache)
  17886. this.updateCache(true);
  17887. return !check;
  17888. };
  17889. /** @hidden */
  17890. Node.prototype.hasNewParent = function (update) {
  17891. if (this._cache.parent === this.parent)
  17892. return false;
  17893. if (update)
  17894. this._cache.parent = this.parent;
  17895. return true;
  17896. };
  17897. /**
  17898. * Is this node ready to be used/rendered
  17899. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17900. * @return true if the node is ready
  17901. */
  17902. Node.prototype.isReady = function (completeCheck) {
  17903. if (completeCheck === void 0) { completeCheck = false; }
  17904. return this._isReady;
  17905. };
  17906. /**
  17907. * Is this node enabled?
  17908. * 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
  17909. * @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
  17910. * @return whether this node (and its parent) is enabled
  17911. */
  17912. Node.prototype.isEnabled = function (checkAncestors) {
  17913. if (checkAncestors === void 0) { checkAncestors = true; }
  17914. if (checkAncestors === false) {
  17915. return this._isEnabled;
  17916. }
  17917. if (this._isEnabled === false) {
  17918. return false;
  17919. }
  17920. if (this.parent !== undefined && this.parent !== null) {
  17921. return this.parent.isEnabled(checkAncestors);
  17922. }
  17923. return true;
  17924. };
  17925. /**
  17926. * Set the enabled state of this node
  17927. * @param value defines the new enabled state
  17928. */
  17929. Node.prototype.setEnabled = function (value) {
  17930. this._isEnabled = value;
  17931. };
  17932. /**
  17933. * Is this node a descendant of the given node?
  17934. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17935. * @param ancestor defines the parent node to inspect
  17936. * @returns a boolean indicating if this node is a descendant of the given node
  17937. */
  17938. Node.prototype.isDescendantOf = function (ancestor) {
  17939. if (this.parent) {
  17940. if (this.parent === ancestor) {
  17941. return true;
  17942. }
  17943. return this.parent.isDescendantOf(ancestor);
  17944. }
  17945. return false;
  17946. };
  17947. /** @hidden */
  17948. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17949. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17950. if (!this._children) {
  17951. return;
  17952. }
  17953. for (var index = 0; index < this._children.length; index++) {
  17954. var item = this._children[index];
  17955. if (!predicate || predicate(item)) {
  17956. results.push(item);
  17957. }
  17958. if (!directDescendantsOnly) {
  17959. item._getDescendants(results, false, predicate);
  17960. }
  17961. }
  17962. };
  17963. /**
  17964. * Will return all nodes that have this node as ascendant
  17965. * @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
  17966. * @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
  17967. * @return all children nodes of all types
  17968. */
  17969. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17970. var results = new Array();
  17971. this._getDescendants(results, directDescendantsOnly, predicate);
  17972. return results;
  17973. };
  17974. /**
  17975. * Get all child-meshes of this node
  17976. * @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
  17977. * @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
  17978. * @returns an array of {BABYLON.AbstractMesh}
  17979. */
  17980. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17981. var results = [];
  17982. this._getDescendants(results, directDescendantsOnly, function (node) {
  17983. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17984. });
  17985. return results;
  17986. };
  17987. /**
  17988. * Get all child-transformNodes of this node
  17989. * @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
  17990. * @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
  17991. * @returns an array of {BABYLON.TransformNode}
  17992. */
  17993. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17994. var results = [];
  17995. this._getDescendants(results, directDescendantsOnly, function (node) {
  17996. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17997. });
  17998. return results;
  17999. };
  18000. /**
  18001. * Get all direct children of this node
  18002. * @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
  18003. * @returns an array of {BABYLON.Node}
  18004. */
  18005. Node.prototype.getChildren = function (predicate) {
  18006. return this.getDescendants(true, predicate);
  18007. };
  18008. /** @hidden */
  18009. Node.prototype._setReady = function (state) {
  18010. if (state === this._isReady) {
  18011. return;
  18012. }
  18013. if (!state) {
  18014. this._isReady = false;
  18015. return;
  18016. }
  18017. if (this.onReady) {
  18018. this.onReady(this);
  18019. }
  18020. this._isReady = true;
  18021. };
  18022. /**
  18023. * Get an animation by name
  18024. * @param name defines the name of the animation to look for
  18025. * @returns null if not found else the requested animation
  18026. */
  18027. Node.prototype.getAnimationByName = function (name) {
  18028. for (var i = 0; i < this.animations.length; i++) {
  18029. var animation = this.animations[i];
  18030. if (animation.name === name) {
  18031. return animation;
  18032. }
  18033. }
  18034. return null;
  18035. };
  18036. /**
  18037. * Creates an animation range for this node
  18038. * @param name defines the name of the range
  18039. * @param from defines the starting key
  18040. * @param to defines the end key
  18041. */
  18042. Node.prototype.createAnimationRange = function (name, from, to) {
  18043. // check name not already in use
  18044. if (!this._ranges[name]) {
  18045. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18046. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18047. if (this.animations[i]) {
  18048. this.animations[i].createRange(name, from, to);
  18049. }
  18050. }
  18051. }
  18052. };
  18053. /**
  18054. * Delete a specific animation range
  18055. * @param name defines the name of the range to delete
  18056. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18057. */
  18058. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18059. if (deleteFrames === void 0) { deleteFrames = true; }
  18060. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18061. if (this.animations[i]) {
  18062. this.animations[i].deleteRange(name, deleteFrames);
  18063. }
  18064. }
  18065. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18066. };
  18067. /**
  18068. * Get an animation range by name
  18069. * @param name defines the name of the animation range to look for
  18070. * @returns null if not found else the requested animation range
  18071. */
  18072. Node.prototype.getAnimationRange = function (name) {
  18073. return this._ranges[name];
  18074. };
  18075. /**
  18076. * Will start the animation sequence
  18077. * @param name defines the range frames for animation sequence
  18078. * @param loop defines if the animation should loop (false by default)
  18079. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18080. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18081. * @returns the object created for this animation. If range does not exist, it will return null
  18082. */
  18083. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18084. var range = this.getAnimationRange(name);
  18085. if (!range) {
  18086. return null;
  18087. }
  18088. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18089. };
  18090. /**
  18091. * Serialize animation ranges into a JSON compatible object
  18092. * @returns serialization object
  18093. */
  18094. Node.prototype.serializeAnimationRanges = function () {
  18095. var serializationRanges = [];
  18096. for (var name in this._ranges) {
  18097. var localRange = this._ranges[name];
  18098. if (!localRange) {
  18099. continue;
  18100. }
  18101. var range = {};
  18102. range.name = name;
  18103. range.from = localRange.from;
  18104. range.to = localRange.to;
  18105. serializationRanges.push(range);
  18106. }
  18107. return serializationRanges;
  18108. };
  18109. /**
  18110. * Computes the world matrix of the node
  18111. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18112. * @returns the world matrix
  18113. */
  18114. Node.prototype.computeWorldMatrix = function (force) {
  18115. return BABYLON.Matrix.Identity();
  18116. };
  18117. /**
  18118. * Releases resources associated with this node.
  18119. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18120. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18121. */
  18122. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18123. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18124. if (!doNotRecurse) {
  18125. var nodes = this.getDescendants(true);
  18126. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18127. var node = nodes_1[_i];
  18128. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18129. }
  18130. }
  18131. else {
  18132. var transformNodes = this.getChildTransformNodes(true);
  18133. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18134. var transformNode = transformNodes_1[_a];
  18135. transformNode.parent = null;
  18136. transformNode.computeWorldMatrix(true);
  18137. }
  18138. }
  18139. this.parent = null;
  18140. // Callback
  18141. this.onDisposeObservable.notifyObservers(this);
  18142. this.onDisposeObservable.clear();
  18143. // Behaviors
  18144. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18145. var behavior = _c[_b];
  18146. behavior.detach();
  18147. }
  18148. this._behaviors = [];
  18149. this._isDisposed = true;
  18150. };
  18151. /**
  18152. * Parse animation range data from a serialization object and store them into a given node
  18153. * @param node defines where to store the animation ranges
  18154. * @param parsedNode defines the serialization object to read data from
  18155. * @param scene defines the hosting scene
  18156. */
  18157. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18158. if (parsedNode.ranges) {
  18159. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18160. var data = parsedNode.ranges[index];
  18161. node.createAnimationRange(data.name, data.from, data.to);
  18162. }
  18163. }
  18164. };
  18165. __decorate([
  18166. BABYLON.serialize()
  18167. ], Node.prototype, "name", void 0);
  18168. __decorate([
  18169. BABYLON.serialize()
  18170. ], Node.prototype, "id", void 0);
  18171. __decorate([
  18172. BABYLON.serialize()
  18173. ], Node.prototype, "uniqueId", void 0);
  18174. __decorate([
  18175. BABYLON.serialize()
  18176. ], Node.prototype, "state", void 0);
  18177. __decorate([
  18178. BABYLON.serialize()
  18179. ], Node.prototype, "metadata", void 0);
  18180. return Node;
  18181. }());
  18182. BABYLON.Node = Node;
  18183. })(BABYLON || (BABYLON = {}));
  18184. //# sourceMappingURL=babylon.node.js.map
  18185. var BABYLON;
  18186. (function (BABYLON) {
  18187. var BoundingSphere = /** @class */ (function () {
  18188. /**
  18189. * Creates a new bounding sphere
  18190. * @param min defines the minimum vector (in local space)
  18191. * @param max defines the maximum vector (in local space)
  18192. */
  18193. function BoundingSphere(min, max) {
  18194. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18195. this.reConstruct(min, max);
  18196. }
  18197. /**
  18198. * Recreates the entire bounding sphere from scratch
  18199. * @param min defines the new minimum vector (in local space)
  18200. * @param max defines the new maximum vector (in local space)
  18201. */
  18202. BoundingSphere.prototype.reConstruct = function (min, max) {
  18203. this.minimum = min.clone();
  18204. this.maximum = max.clone();
  18205. var distance = BABYLON.Vector3.Distance(min, max);
  18206. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18207. this.radius = distance * 0.5;
  18208. this.centerWorld = BABYLON.Vector3.Zero();
  18209. this._update(BABYLON.Matrix.Identity());
  18210. };
  18211. // Methods
  18212. BoundingSphere.prototype._update = function (world) {
  18213. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18214. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18215. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18216. };
  18217. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18218. for (var i = 0; i < 6; i++) {
  18219. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18220. return false;
  18221. }
  18222. return true;
  18223. };
  18224. BoundingSphere.prototype.intersectsPoint = function (point) {
  18225. var x = this.centerWorld.x - point.x;
  18226. var y = this.centerWorld.y - point.y;
  18227. var z = this.centerWorld.z - point.z;
  18228. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18229. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18230. return false;
  18231. return true;
  18232. };
  18233. // Statics
  18234. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18235. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18236. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18237. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18238. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18239. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18240. return false;
  18241. return true;
  18242. };
  18243. return BoundingSphere;
  18244. }());
  18245. BABYLON.BoundingSphere = BoundingSphere;
  18246. })(BABYLON || (BABYLON = {}));
  18247. //# sourceMappingURL=babylon.boundingSphere.js.map
  18248. var BABYLON;
  18249. (function (BABYLON) {
  18250. var BoundingBox = /** @class */ (function () {
  18251. /**
  18252. * Creates a new bounding box
  18253. * @param min defines the minimum vector (in local space)
  18254. * @param max defines the maximum vector (in local space)
  18255. */
  18256. function BoundingBox(min, max) {
  18257. this.vectorsWorld = new Array();
  18258. this.reConstruct(min, max);
  18259. }
  18260. // Methods
  18261. /**
  18262. * Recreates the entire bounding box from scratch
  18263. * @param min defines the new minimum vector (in local space)
  18264. * @param max defines the new maximum vector (in local space)
  18265. */
  18266. BoundingBox.prototype.reConstruct = function (min, max) {
  18267. this.minimum = min.clone();
  18268. this.maximum = max.clone();
  18269. // Bounding vectors
  18270. this.vectors = new Array();
  18271. this.vectors.push(this.minimum.clone());
  18272. this.vectors.push(this.maximum.clone());
  18273. this.vectors.push(this.minimum.clone());
  18274. this.vectors[2].x = this.maximum.x;
  18275. this.vectors.push(this.minimum.clone());
  18276. this.vectors[3].y = this.maximum.y;
  18277. this.vectors.push(this.minimum.clone());
  18278. this.vectors[4].z = this.maximum.z;
  18279. this.vectors.push(this.maximum.clone());
  18280. this.vectors[5].z = this.minimum.z;
  18281. this.vectors.push(this.maximum.clone());
  18282. this.vectors[6].x = this.minimum.x;
  18283. this.vectors.push(this.maximum.clone());
  18284. this.vectors[7].y = this.minimum.y;
  18285. // OBB
  18286. this.center = this.maximum.add(this.minimum).scale(0.5);
  18287. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18288. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18289. // World
  18290. for (var index = 0; index < this.vectors.length; index++) {
  18291. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18292. }
  18293. this.minimumWorld = BABYLON.Vector3.Zero();
  18294. this.maximumWorld = BABYLON.Vector3.Zero();
  18295. this.centerWorld = BABYLON.Vector3.Zero();
  18296. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18297. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18298. };
  18299. BoundingBox.prototype.getWorldMatrix = function () {
  18300. return this._worldMatrix;
  18301. };
  18302. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18303. this._worldMatrix.copyFrom(matrix);
  18304. return this;
  18305. };
  18306. BoundingBox.prototype._update = function (world) {
  18307. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18308. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18309. for (var index = 0; index < this.vectors.length; index++) {
  18310. var v = this.vectorsWorld[index];
  18311. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18312. if (v.x < this.minimumWorld.x)
  18313. this.minimumWorld.x = v.x;
  18314. if (v.y < this.minimumWorld.y)
  18315. this.minimumWorld.y = v.y;
  18316. if (v.z < this.minimumWorld.z)
  18317. this.minimumWorld.z = v.z;
  18318. if (v.x > this.maximumWorld.x)
  18319. this.maximumWorld.x = v.x;
  18320. if (v.y > this.maximumWorld.y)
  18321. this.maximumWorld.y = v.y;
  18322. if (v.z > this.maximumWorld.z)
  18323. this.maximumWorld.z = v.z;
  18324. }
  18325. // Extend
  18326. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18327. this.extendSizeWorld.scaleInPlace(0.5);
  18328. // OBB
  18329. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18330. this.centerWorld.scaleInPlace(0.5);
  18331. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18332. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18333. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18334. this._worldMatrix = world;
  18335. };
  18336. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18337. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18338. };
  18339. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18340. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18341. };
  18342. BoundingBox.prototype.intersectsPoint = function (point) {
  18343. var delta = -BABYLON.Epsilon;
  18344. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18345. return false;
  18346. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18347. return false;
  18348. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18349. return false;
  18350. return true;
  18351. };
  18352. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18353. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18354. };
  18355. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18356. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18357. return false;
  18358. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18359. return false;
  18360. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18361. return false;
  18362. return true;
  18363. };
  18364. // Statics
  18365. BoundingBox.Intersects = function (box0, box1) {
  18366. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18367. return false;
  18368. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18369. return false;
  18370. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18371. return false;
  18372. return true;
  18373. };
  18374. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18375. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18376. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18377. return (num <= (sphereRadius * sphereRadius));
  18378. };
  18379. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18380. for (var p = 0; p < 6; p++) {
  18381. for (var i = 0; i < 8; i++) {
  18382. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18383. return false;
  18384. }
  18385. }
  18386. }
  18387. return true;
  18388. };
  18389. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18390. for (var p = 0; p < 6; p++) {
  18391. var inCount = 8;
  18392. for (var i = 0; i < 8; i++) {
  18393. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18394. --inCount;
  18395. }
  18396. else {
  18397. break;
  18398. }
  18399. }
  18400. if (inCount === 0)
  18401. return false;
  18402. }
  18403. return true;
  18404. };
  18405. return BoundingBox;
  18406. }());
  18407. BABYLON.BoundingBox = BoundingBox;
  18408. })(BABYLON || (BABYLON = {}));
  18409. //# sourceMappingURL=babylon.boundingBox.js.map
  18410. var BABYLON;
  18411. (function (BABYLON) {
  18412. var computeBoxExtents = function (axis, box) {
  18413. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18414. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18415. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18416. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18417. var r = r0 + r1 + r2;
  18418. return {
  18419. min: p - r,
  18420. max: p + r
  18421. };
  18422. };
  18423. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18424. var axisOverlap = function (axis, box0, box1) {
  18425. var result0 = computeBoxExtents(axis, box0);
  18426. var result1 = computeBoxExtents(axis, box1);
  18427. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18428. };
  18429. var BoundingInfo = /** @class */ (function () {
  18430. function BoundingInfo(minimum, maximum) {
  18431. this.minimum = minimum;
  18432. this.maximum = maximum;
  18433. this._isLocked = false;
  18434. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18435. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18436. }
  18437. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18438. get: function () {
  18439. return this._isLocked;
  18440. },
  18441. set: function (value) {
  18442. this._isLocked = value;
  18443. },
  18444. enumerable: true,
  18445. configurable: true
  18446. });
  18447. // Methods
  18448. BoundingInfo.prototype.update = function (world) {
  18449. if (this._isLocked) {
  18450. return;
  18451. }
  18452. this.boundingBox._update(world);
  18453. this.boundingSphere._update(world);
  18454. };
  18455. /**
  18456. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18457. * @param center New center of the bounding info
  18458. * @param extend New extend of the bounding info
  18459. */
  18460. BoundingInfo.prototype.centerOn = function (center, extend) {
  18461. this.minimum = center.subtract(extend);
  18462. this.maximum = center.add(extend);
  18463. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18464. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18465. return this;
  18466. };
  18467. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18468. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18469. return false;
  18470. return this.boundingBox.isInFrustum(frustumPlanes);
  18471. };
  18472. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18473. /**
  18474. * Gets the world distance between the min and max points of the bounding box
  18475. */
  18476. get: function () {
  18477. var boundingBox = this.boundingBox;
  18478. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18479. return size.length();
  18480. },
  18481. enumerable: true,
  18482. configurable: true
  18483. });
  18484. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18485. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18486. };
  18487. BoundingInfo.prototype._checkCollision = function (collider) {
  18488. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18489. };
  18490. BoundingInfo.prototype.intersectsPoint = function (point) {
  18491. if (!this.boundingSphere.centerWorld) {
  18492. return false;
  18493. }
  18494. if (!this.boundingSphere.intersectsPoint(point)) {
  18495. return false;
  18496. }
  18497. if (!this.boundingBox.intersectsPoint(point)) {
  18498. return false;
  18499. }
  18500. return true;
  18501. };
  18502. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18503. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18504. return false;
  18505. }
  18506. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18507. return false;
  18508. }
  18509. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18510. return false;
  18511. }
  18512. if (!precise) {
  18513. return true;
  18514. }
  18515. var box0 = this.boundingBox;
  18516. var box1 = boundingInfo.boundingBox;
  18517. if (!axisOverlap(box0.directions[0], box0, box1))
  18518. return false;
  18519. if (!axisOverlap(box0.directions[1], box0, box1))
  18520. return false;
  18521. if (!axisOverlap(box0.directions[2], box0, box1))
  18522. return false;
  18523. if (!axisOverlap(box1.directions[0], box0, box1))
  18524. return false;
  18525. if (!axisOverlap(box1.directions[1], box0, box1))
  18526. return false;
  18527. if (!axisOverlap(box1.directions[2], box0, box1))
  18528. return false;
  18529. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18530. return false;
  18531. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18532. return false;
  18533. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18534. return false;
  18535. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18536. return false;
  18537. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18538. return false;
  18539. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18540. return false;
  18541. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18542. return false;
  18543. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18544. return false;
  18545. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18546. return false;
  18547. return true;
  18548. };
  18549. return BoundingInfo;
  18550. }());
  18551. BABYLON.BoundingInfo = BoundingInfo;
  18552. })(BABYLON || (BABYLON = {}));
  18553. //# sourceMappingURL=babylon.boundingInfo.js.map
  18554. var BABYLON;
  18555. (function (BABYLON) {
  18556. var TransformNode = /** @class */ (function (_super) {
  18557. __extends(TransformNode, _super);
  18558. function TransformNode(name, scene, isPure) {
  18559. if (scene === void 0) { scene = null; }
  18560. if (isPure === void 0) { isPure = true; }
  18561. var _this = _super.call(this, name, scene) || this;
  18562. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18563. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18564. _this._up = new BABYLON.Vector3(0, 1, 0);
  18565. _this._right = new BABYLON.Vector3(1, 0, 0);
  18566. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18567. // Properties
  18568. _this._rotation = BABYLON.Vector3.Zero();
  18569. _this._scaling = BABYLON.Vector3.One();
  18570. _this._isDirty = false;
  18571. /**
  18572. * Set the billboard mode. Default is 0.
  18573. *
  18574. * | Value | Type | Description |
  18575. * | --- | --- | --- |
  18576. * | 0 | BILLBOARDMODE_NONE | |
  18577. * | 1 | BILLBOARDMODE_X | |
  18578. * | 2 | BILLBOARDMODE_Y | |
  18579. * | 4 | BILLBOARDMODE_Z | |
  18580. * | 7 | BILLBOARDMODE_ALL | |
  18581. *
  18582. */
  18583. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18584. _this.scalingDeterminant = 1;
  18585. _this.infiniteDistance = false;
  18586. /**
  18587. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18588. * By default the system will update normals to compensate
  18589. */
  18590. _this.ignoreNonUniformScaling = false;
  18591. _this.position = BABYLON.Vector3.Zero();
  18592. _this._localWorld = BABYLON.Matrix.Zero();
  18593. _this._worldMatrix = BABYLON.Matrix.Zero();
  18594. _this._worldMatrixDeterminant = 0;
  18595. _this._absolutePosition = BABYLON.Vector3.Zero();
  18596. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18597. _this._postMultiplyPivotMatrix = false;
  18598. _this._isWorldMatrixFrozen = false;
  18599. /**
  18600. * An event triggered after the world matrix is updated
  18601. */
  18602. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18603. _this._nonUniformScaling = false;
  18604. if (isPure) {
  18605. _this.getScene().addTransformNode(_this);
  18606. }
  18607. return _this;
  18608. }
  18609. /**
  18610. * Gets a string idenfifying the name of the class
  18611. * @returns "TransformNode" string
  18612. */
  18613. TransformNode.prototype.getClassName = function () {
  18614. return "TransformNode";
  18615. };
  18616. Object.defineProperty(TransformNode.prototype, "rotation", {
  18617. /**
  18618. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18619. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18620. * Default : (0.0, 0.0, 0.0)
  18621. */
  18622. get: function () {
  18623. return this._rotation;
  18624. },
  18625. set: function (newRotation) {
  18626. this._rotation = newRotation;
  18627. },
  18628. enumerable: true,
  18629. configurable: true
  18630. });
  18631. Object.defineProperty(TransformNode.prototype, "scaling", {
  18632. /**
  18633. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18634. * Default : (1.0, 1.0, 1.0)
  18635. */
  18636. get: function () {
  18637. return this._scaling;
  18638. },
  18639. /**
  18640. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18641. * Default : (1.0, 1.0, 1.0)
  18642. */
  18643. set: function (newScaling) {
  18644. this._scaling = newScaling;
  18645. },
  18646. enumerable: true,
  18647. configurable: true
  18648. });
  18649. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18650. /**
  18651. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18652. * It's null by default.
  18653. * 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)
  18654. */
  18655. get: function () {
  18656. return this._rotationQuaternion;
  18657. },
  18658. set: function (quaternion) {
  18659. this._rotationQuaternion = quaternion;
  18660. //reset the rotation vector.
  18661. if (quaternion && this.rotation.length()) {
  18662. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18663. }
  18664. },
  18665. enumerable: true,
  18666. configurable: true
  18667. });
  18668. Object.defineProperty(TransformNode.prototype, "forward", {
  18669. /**
  18670. * The forward direction of that transform in world space.
  18671. */
  18672. get: function () {
  18673. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. Object.defineProperty(TransformNode.prototype, "up", {
  18679. /**
  18680. * The up direction of that transform in world space.
  18681. */
  18682. get: function () {
  18683. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. Object.defineProperty(TransformNode.prototype, "right", {
  18689. /**
  18690. * The right direction of that transform in world space.
  18691. */
  18692. get: function () {
  18693. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. /**
  18699. * Returns the latest update of the World matrix
  18700. * Returns a Matrix.
  18701. */
  18702. TransformNode.prototype.getWorldMatrix = function () {
  18703. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18704. this.computeWorldMatrix();
  18705. }
  18706. return this._worldMatrix;
  18707. };
  18708. /** @hidden */
  18709. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18710. return this._worldMatrixDeterminant;
  18711. };
  18712. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18713. /**
  18714. * Returns directly the latest state of the mesh World matrix.
  18715. * A Matrix is returned.
  18716. */
  18717. get: function () {
  18718. return this._worldMatrix;
  18719. },
  18720. enumerable: true,
  18721. configurable: true
  18722. });
  18723. /**
  18724. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18725. * Returns the TransformNode.
  18726. */
  18727. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18728. this._poseMatrix.copyFrom(matrix);
  18729. return this;
  18730. };
  18731. /**
  18732. * Returns the mesh Pose matrix.
  18733. * Returned object : Matrix
  18734. */
  18735. TransformNode.prototype.getPoseMatrix = function () {
  18736. return this._poseMatrix;
  18737. };
  18738. TransformNode.prototype._isSynchronized = function () {
  18739. if (this._isDirty) {
  18740. return false;
  18741. }
  18742. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18743. return false;
  18744. if (this._cache.pivotMatrixUpdated) {
  18745. return false;
  18746. }
  18747. if (this.infiniteDistance) {
  18748. return false;
  18749. }
  18750. if (!this._cache.position.equals(this.position))
  18751. return false;
  18752. if (this.rotationQuaternion) {
  18753. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18754. return false;
  18755. }
  18756. if (!this._cache.rotation.equals(this.rotation))
  18757. return false;
  18758. if (!this._cache.scaling.equals(this.scaling))
  18759. return false;
  18760. return true;
  18761. };
  18762. TransformNode.prototype._initCache = function () {
  18763. _super.prototype._initCache.call(this);
  18764. this._cache.localMatrixUpdated = false;
  18765. this._cache.position = BABYLON.Vector3.Zero();
  18766. this._cache.scaling = BABYLON.Vector3.Zero();
  18767. this._cache.rotation = BABYLON.Vector3.Zero();
  18768. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18769. this._cache.billboardMode = -1;
  18770. };
  18771. TransformNode.prototype.markAsDirty = function (property) {
  18772. if (property === "rotation") {
  18773. this.rotationQuaternion = null;
  18774. }
  18775. this._currentRenderId = Number.MAX_VALUE;
  18776. this._isDirty = true;
  18777. return this;
  18778. };
  18779. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18780. /**
  18781. * Returns the current mesh absolute position.
  18782. * Retuns a Vector3.
  18783. */
  18784. get: function () {
  18785. return this._absolutePosition;
  18786. },
  18787. enumerable: true,
  18788. configurable: true
  18789. });
  18790. /**
  18791. * Sets a new matrix to apply before all other transformation
  18792. * @param matrix defines the transform matrix
  18793. * @returns the current TransformNode
  18794. */
  18795. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18796. return this.setPivotMatrix(matrix, false);
  18797. };
  18798. /**
  18799. * Sets a new pivot matrix to the current node
  18800. * @param matrix defines the new pivot matrix to use
  18801. * @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
  18802. * @returns the current TransformNode
  18803. */
  18804. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18805. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18806. this._pivotMatrix = matrix.clone();
  18807. this._cache.pivotMatrixUpdated = true;
  18808. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18809. if (this._postMultiplyPivotMatrix) {
  18810. if (!this._pivotMatrixInverse) {
  18811. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18812. }
  18813. else {
  18814. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18815. }
  18816. }
  18817. return this;
  18818. };
  18819. /**
  18820. * Returns the mesh pivot matrix.
  18821. * Default : Identity.
  18822. * A Matrix is returned.
  18823. */
  18824. TransformNode.prototype.getPivotMatrix = function () {
  18825. return this._pivotMatrix;
  18826. };
  18827. /**
  18828. * Prevents the World matrix to be computed any longer.
  18829. * Returns the TransformNode.
  18830. */
  18831. TransformNode.prototype.freezeWorldMatrix = function () {
  18832. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18833. this.computeWorldMatrix(true);
  18834. this._isWorldMatrixFrozen = true;
  18835. return this;
  18836. };
  18837. /**
  18838. * Allows back the World matrix computation.
  18839. * Returns the TransformNode.
  18840. */
  18841. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18842. this._isWorldMatrixFrozen = false;
  18843. this.computeWorldMatrix(true);
  18844. return this;
  18845. };
  18846. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18847. /**
  18848. * True if the World matrix has been frozen.
  18849. * Returns a boolean.
  18850. */
  18851. get: function () {
  18852. return this._isWorldMatrixFrozen;
  18853. },
  18854. enumerable: true,
  18855. configurable: true
  18856. });
  18857. /**
  18858. * Retuns the mesh absolute position in the World.
  18859. * Returns a Vector3.
  18860. */
  18861. TransformNode.prototype.getAbsolutePosition = function () {
  18862. this.computeWorldMatrix();
  18863. return this._absolutePosition;
  18864. };
  18865. /**
  18866. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18867. * Returns the TransformNode.
  18868. */
  18869. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18870. if (!absolutePosition) {
  18871. return this;
  18872. }
  18873. var absolutePositionX;
  18874. var absolutePositionY;
  18875. var absolutePositionZ;
  18876. if (absolutePosition.x === undefined) {
  18877. if (arguments.length < 3) {
  18878. return this;
  18879. }
  18880. absolutePositionX = arguments[0];
  18881. absolutePositionY = arguments[1];
  18882. absolutePositionZ = arguments[2];
  18883. }
  18884. else {
  18885. absolutePositionX = absolutePosition.x;
  18886. absolutePositionY = absolutePosition.y;
  18887. absolutePositionZ = absolutePosition.z;
  18888. }
  18889. if (this.parent) {
  18890. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18891. invertParentWorldMatrix.invert();
  18892. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18893. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18894. }
  18895. else {
  18896. this.position.x = absolutePositionX;
  18897. this.position.y = absolutePositionY;
  18898. this.position.z = absolutePositionZ;
  18899. }
  18900. return this;
  18901. };
  18902. /**
  18903. * Sets the mesh position in its local space.
  18904. * Returns the TransformNode.
  18905. */
  18906. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18907. this.computeWorldMatrix();
  18908. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18909. return this;
  18910. };
  18911. /**
  18912. * Returns the mesh position in the local space from the current World matrix values.
  18913. * Returns a new Vector3.
  18914. */
  18915. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18916. this.computeWorldMatrix();
  18917. var invLocalWorldMatrix = this._localWorld.clone();
  18918. invLocalWorldMatrix.invert();
  18919. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18920. };
  18921. /**
  18922. * Translates the mesh along the passed Vector3 in its local space.
  18923. * Returns the TransformNode.
  18924. */
  18925. TransformNode.prototype.locallyTranslate = function (vector3) {
  18926. this.computeWorldMatrix(true);
  18927. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18928. return this;
  18929. };
  18930. /**
  18931. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18932. * @param targetPoint the position (must be in same space as current mesh) to look at
  18933. * @param yawCor optional yaw (y-axis) correction in radians
  18934. * @param pitchCor optional pitch (x-axis) correction in radians
  18935. * @param rollCor optional roll (z-axis) correction in radians
  18936. * @param space the choosen space of the target
  18937. * @returns the TransformNode.
  18938. */
  18939. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18940. if (yawCor === void 0) { yawCor = 0; }
  18941. if (pitchCor === void 0) { pitchCor = 0; }
  18942. if (rollCor === void 0) { rollCor = 0; }
  18943. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18944. var dv = TransformNode._lookAtVectorCache;
  18945. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18946. targetPoint.subtractToRef(pos, dv);
  18947. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18948. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18949. var pitch = Math.atan2(dv.y, len);
  18950. if (this.rotationQuaternion) {
  18951. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18952. }
  18953. else {
  18954. this.rotation.x = pitch + pitchCor;
  18955. this.rotation.y = yaw + yawCor;
  18956. this.rotation.z = rollCor;
  18957. }
  18958. return this;
  18959. };
  18960. /**
  18961. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18962. * This Vector3 is expressed in the World space.
  18963. */
  18964. TransformNode.prototype.getDirection = function (localAxis) {
  18965. var result = BABYLON.Vector3.Zero();
  18966. this.getDirectionToRef(localAxis, result);
  18967. return result;
  18968. };
  18969. /**
  18970. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18971. * localAxis is expressed in the mesh local space.
  18972. * result is computed in the Wordl space from the mesh World matrix.
  18973. * Returns the TransformNode.
  18974. */
  18975. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18976. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18977. return this;
  18978. };
  18979. /**
  18980. * Sets a new pivot point to the current node
  18981. * @param point defines the new pivot point to use
  18982. * @param space defines if the point is in world or local space (local by default)
  18983. * @returns the current TransformNode
  18984. */
  18985. TransformNode.prototype.setPivotPoint = function (point, space) {
  18986. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18987. if (this.getScene().getRenderId() == 0) {
  18988. this.computeWorldMatrix(true);
  18989. }
  18990. var wm = this.getWorldMatrix();
  18991. if (space == BABYLON.Space.WORLD) {
  18992. var tmat = BABYLON.Tmp.Matrix[0];
  18993. wm.invertToRef(tmat);
  18994. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18995. }
  18996. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18997. };
  18998. /**
  18999. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19000. */
  19001. TransformNode.prototype.getPivotPoint = function () {
  19002. var point = BABYLON.Vector3.Zero();
  19003. this.getPivotPointToRef(point);
  19004. return point;
  19005. };
  19006. /**
  19007. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19008. * Returns the TransformNode.
  19009. */
  19010. TransformNode.prototype.getPivotPointToRef = function (result) {
  19011. result.x = -this._pivotMatrix.m[12];
  19012. result.y = -this._pivotMatrix.m[13];
  19013. result.z = -this._pivotMatrix.m[14];
  19014. return this;
  19015. };
  19016. /**
  19017. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19018. */
  19019. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19020. var point = BABYLON.Vector3.Zero();
  19021. this.getAbsolutePivotPointToRef(point);
  19022. return point;
  19023. };
  19024. /**
  19025. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19026. * Returns the TransformNode.
  19027. */
  19028. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19029. result.x = this._pivotMatrix.m[12];
  19030. result.y = this._pivotMatrix.m[13];
  19031. result.z = this._pivotMatrix.m[14];
  19032. this.getPivotPointToRef(result);
  19033. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19034. return this;
  19035. };
  19036. /**
  19037. * Defines the passed node as the parent of the current node.
  19038. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19039. * Returns the TransformNode.
  19040. */
  19041. TransformNode.prototype.setParent = function (node) {
  19042. if (node === null) {
  19043. var rotation = BABYLON.Tmp.Quaternion[0];
  19044. var position = BABYLON.Tmp.Vector3[0];
  19045. var scale = BABYLON.Tmp.Vector3[1];
  19046. if (this.parent && this.parent.computeWorldMatrix) {
  19047. this.parent.computeWorldMatrix(true);
  19048. }
  19049. this.computeWorldMatrix(true);
  19050. this.getWorldMatrix().decompose(scale, rotation, position);
  19051. if (this.rotationQuaternion) {
  19052. this.rotationQuaternion.copyFrom(rotation);
  19053. }
  19054. else {
  19055. rotation.toEulerAnglesToRef(this.rotation);
  19056. }
  19057. this.scaling.x = scale.x;
  19058. this.scaling.y = scale.y;
  19059. this.scaling.z = scale.z;
  19060. this.position.x = position.x;
  19061. this.position.y = position.y;
  19062. this.position.z = position.z;
  19063. }
  19064. else {
  19065. var rotation = BABYLON.Tmp.Quaternion[0];
  19066. var position = BABYLON.Tmp.Vector3[0];
  19067. var scale = BABYLON.Tmp.Vector3[1];
  19068. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19069. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19070. this.computeWorldMatrix(true);
  19071. node.computeWorldMatrix(true);
  19072. node.getWorldMatrix().invertToRef(invParentMatrix);
  19073. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19074. diffMatrix.decompose(scale, rotation, position);
  19075. if (this.rotationQuaternion) {
  19076. this.rotationQuaternion.copyFrom(rotation);
  19077. }
  19078. else {
  19079. rotation.toEulerAnglesToRef(this.rotation);
  19080. }
  19081. this.position.x = position.x;
  19082. this.position.y = position.y;
  19083. this.position.z = position.z;
  19084. this.scaling.x = scale.x;
  19085. this.scaling.y = scale.y;
  19086. this.scaling.z = scale.z;
  19087. }
  19088. this.parent = node;
  19089. return this;
  19090. };
  19091. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19092. get: function () {
  19093. return this._nonUniformScaling;
  19094. },
  19095. enumerable: true,
  19096. configurable: true
  19097. });
  19098. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19099. if (this._nonUniformScaling === value) {
  19100. return false;
  19101. }
  19102. this._nonUniformScaling = value;
  19103. return true;
  19104. };
  19105. /**
  19106. * Attach the current TransformNode to another TransformNode associated with a bone
  19107. * @param bone Bone affecting the TransformNode
  19108. * @param affectedTransformNode TransformNode associated with the bone
  19109. */
  19110. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19111. this._transformToBoneReferal = affectedTransformNode;
  19112. this.parent = bone;
  19113. if (bone.getWorldMatrix().determinant() < 0) {
  19114. this.scalingDeterminant *= -1;
  19115. }
  19116. return this;
  19117. };
  19118. TransformNode.prototype.detachFromBone = function () {
  19119. if (!this.parent) {
  19120. return this;
  19121. }
  19122. if (this.parent.getWorldMatrix().determinant() < 0) {
  19123. this.scalingDeterminant *= -1;
  19124. }
  19125. this._transformToBoneReferal = null;
  19126. this.parent = null;
  19127. return this;
  19128. };
  19129. /**
  19130. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19131. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19132. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19133. * The passed axis is also normalized.
  19134. * Returns the TransformNode.
  19135. */
  19136. TransformNode.prototype.rotate = function (axis, amount, space) {
  19137. axis.normalize();
  19138. if (!this.rotationQuaternion) {
  19139. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19140. this.rotation = BABYLON.Vector3.Zero();
  19141. }
  19142. var rotationQuaternion;
  19143. if (!space || space === BABYLON.Space.LOCAL) {
  19144. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19145. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19146. }
  19147. else {
  19148. if (this.parent) {
  19149. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19150. invertParentWorldMatrix.invert();
  19151. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19152. }
  19153. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19154. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19155. }
  19156. return this;
  19157. };
  19158. /**
  19159. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19160. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19161. * The passed axis is also normalized.
  19162. * Returns the TransformNode.
  19163. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19164. */
  19165. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19166. axis.normalize();
  19167. if (!this.rotationQuaternion) {
  19168. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19169. this.rotation.copyFromFloats(0, 0, 0);
  19170. }
  19171. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19172. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19173. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19174. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19175. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19176. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19177. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19178. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19179. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19180. return this;
  19181. };
  19182. /**
  19183. * Translates the mesh along the axis vector for the passed distance in the given space.
  19184. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19185. * Returns the TransformNode.
  19186. */
  19187. TransformNode.prototype.translate = function (axis, distance, space) {
  19188. var displacementVector = axis.scale(distance);
  19189. if (!space || space === BABYLON.Space.LOCAL) {
  19190. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19191. this.setPositionWithLocalVector(tempV3);
  19192. }
  19193. else {
  19194. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19195. }
  19196. return this;
  19197. };
  19198. /**
  19199. * Adds a rotation step to the mesh current rotation.
  19200. * x, y, z are Euler angles expressed in radians.
  19201. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19202. * This means this rotation is made in the mesh local space only.
  19203. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19204. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19205. * ```javascript
  19206. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19207. * ```
  19208. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19209. * 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.
  19210. * Returns the TransformNode.
  19211. */
  19212. TransformNode.prototype.addRotation = function (x, y, z) {
  19213. var rotationQuaternion;
  19214. if (this.rotationQuaternion) {
  19215. rotationQuaternion = this.rotationQuaternion;
  19216. }
  19217. else {
  19218. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19219. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19220. }
  19221. var accumulation = BABYLON.Tmp.Quaternion[0];
  19222. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19223. rotationQuaternion.multiplyInPlace(accumulation);
  19224. if (!this.rotationQuaternion) {
  19225. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19226. }
  19227. return this;
  19228. };
  19229. /**
  19230. * Computes the mesh World matrix and returns it.
  19231. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19232. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19233. * If the parameter `force`is set to `true`, the actual computation is done.
  19234. * Returns the mesh World Matrix.
  19235. */
  19236. TransformNode.prototype.computeWorldMatrix = function (force) {
  19237. if (this._isWorldMatrixFrozen) {
  19238. return this._worldMatrix;
  19239. }
  19240. if (!force && this.isSynchronized(true)) {
  19241. this._currentRenderId = this.getScene().getRenderId();
  19242. return this._worldMatrix;
  19243. }
  19244. this._cache.position.copyFrom(this.position);
  19245. this._cache.scaling.copyFrom(this.scaling);
  19246. this._cache.pivotMatrixUpdated = false;
  19247. this._cache.billboardMode = this.billboardMode;
  19248. this._currentRenderId = this.getScene().getRenderId();
  19249. this._childRenderId = this.getScene().getRenderId();
  19250. this._isDirty = false;
  19251. // Scaling
  19252. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19253. // Rotation
  19254. //rotate, if quaternion is set and rotation was used
  19255. if (this.rotationQuaternion) {
  19256. var len = this.rotation.length();
  19257. if (len) {
  19258. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19259. this.rotation.copyFromFloats(0, 0, 0);
  19260. }
  19261. }
  19262. if (this.rotationQuaternion) {
  19263. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19264. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19265. }
  19266. else {
  19267. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19268. this._cache.rotation.copyFrom(this.rotation);
  19269. }
  19270. // Translation
  19271. var camera = this.getScene().activeCamera;
  19272. if (this.infiniteDistance && !this.parent && camera) {
  19273. var cameraWorldMatrix = camera.getWorldMatrix();
  19274. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19275. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19276. }
  19277. else {
  19278. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19279. }
  19280. // Composing transformations
  19281. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19282. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19283. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19284. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19285. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19286. // Need to decompose each rotation here
  19287. var currentPosition = BABYLON.Tmp.Vector3[3];
  19288. if (this.parent && this.parent.getWorldMatrix) {
  19289. if (this._transformToBoneReferal) {
  19290. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19291. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19292. }
  19293. else {
  19294. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19295. }
  19296. }
  19297. else {
  19298. currentPosition.copyFrom(this.position);
  19299. }
  19300. currentPosition.subtractInPlace(camera.globalPosition);
  19301. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19302. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19303. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19304. }
  19305. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19306. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19307. }
  19308. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19309. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19310. }
  19311. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19312. }
  19313. else {
  19314. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19315. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19316. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19317. }
  19318. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19319. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19320. }
  19321. // Local world
  19322. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19323. // Parent
  19324. if (this.parent && this.parent.getWorldMatrix) {
  19325. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19326. if (this._transformToBoneReferal) {
  19327. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19328. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19329. }
  19330. else {
  19331. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19332. }
  19333. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19334. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19335. this._worldMatrix.copyFrom(this._localWorld);
  19336. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19337. }
  19338. else {
  19339. if (this._transformToBoneReferal) {
  19340. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19341. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19342. }
  19343. else {
  19344. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19345. }
  19346. }
  19347. this._markSyncedWithParent();
  19348. }
  19349. else {
  19350. this._worldMatrix.copyFrom(this._localWorld);
  19351. }
  19352. // Post multiply inverse of pivotMatrix
  19353. if (this._postMultiplyPivotMatrix) {
  19354. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19355. }
  19356. // Normal matrix
  19357. if (!this.ignoreNonUniformScaling) {
  19358. if (this.scaling.isNonUniform) {
  19359. this._updateNonUniformScalingState(true);
  19360. }
  19361. else if (this.parent && this.parent._nonUniformScaling) {
  19362. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19363. }
  19364. else {
  19365. this._updateNonUniformScalingState(false);
  19366. }
  19367. }
  19368. else {
  19369. this._updateNonUniformScalingState(false);
  19370. }
  19371. this._afterComputeWorldMatrix();
  19372. // Absolute position
  19373. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19374. // Callbacks
  19375. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19376. if (!this._poseMatrix) {
  19377. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19378. }
  19379. // Cache the determinant
  19380. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19381. return this._worldMatrix;
  19382. };
  19383. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19384. };
  19385. /**
  19386. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19387. * @param func: callback function to add
  19388. *
  19389. * Returns the TransformNode.
  19390. */
  19391. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19392. this.onAfterWorldMatrixUpdateObservable.add(func);
  19393. return this;
  19394. };
  19395. /**
  19396. * Removes a registered callback function.
  19397. * Returns the TransformNode.
  19398. */
  19399. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19400. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19401. return this;
  19402. };
  19403. /**
  19404. * Clone the current transform node
  19405. * Returns the new transform node
  19406. * @param name Name of the new clone
  19407. * @param newParent New parent for the clone
  19408. * @param doNotCloneChildren Do not clone children hierarchy
  19409. */
  19410. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19411. var _this = this;
  19412. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19413. result.name = name;
  19414. result.id = name;
  19415. if (newParent) {
  19416. result.parent = newParent;
  19417. }
  19418. if (!doNotCloneChildren) {
  19419. // Children
  19420. var directDescendants = this.getDescendants(true);
  19421. for (var index = 0; index < directDescendants.length; index++) {
  19422. var child = directDescendants[index];
  19423. if (child.clone) {
  19424. child.clone(name + "." + child.name, result);
  19425. }
  19426. }
  19427. }
  19428. return result;
  19429. };
  19430. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19431. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19432. serializationObject.type = this.getClassName();
  19433. // Parent
  19434. if (this.parent) {
  19435. serializationObject.parentId = this.parent.id;
  19436. }
  19437. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19438. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19439. }
  19440. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19441. serializationObject.isEnabled = this.isEnabled();
  19442. // Parent
  19443. if (this.parent) {
  19444. serializationObject.parentId = this.parent.id;
  19445. }
  19446. return serializationObject;
  19447. };
  19448. // Statics
  19449. /**
  19450. * Returns a new TransformNode object parsed from the source provided.
  19451. * The parameter `parsedMesh` is the source.
  19452. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19453. */
  19454. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19455. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19456. if (BABYLON.Tags) {
  19457. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19458. }
  19459. if (parsedTransformNode.localMatrix) {
  19460. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19461. }
  19462. else if (parsedTransformNode.pivotMatrix) {
  19463. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19464. }
  19465. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19466. // Parent
  19467. if (parsedTransformNode.parentId) {
  19468. transformNode._waitingParentId = parsedTransformNode.parentId;
  19469. }
  19470. return transformNode;
  19471. };
  19472. /**
  19473. * Releases resources associated with this transform node.
  19474. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19475. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19476. */
  19477. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19478. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19479. // Animations
  19480. this.getScene().stopAnimation(this);
  19481. // Remove from scene
  19482. this.getScene().removeTransformNode(this);
  19483. this.onAfterWorldMatrixUpdateObservable.clear();
  19484. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19485. };
  19486. // Statics
  19487. TransformNode.BILLBOARDMODE_NONE = 0;
  19488. TransformNode.BILLBOARDMODE_X = 1;
  19489. TransformNode.BILLBOARDMODE_Y = 2;
  19490. TransformNode.BILLBOARDMODE_Z = 4;
  19491. TransformNode.BILLBOARDMODE_ALL = 7;
  19492. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19493. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19494. __decorate([
  19495. BABYLON.serializeAsVector3()
  19496. ], TransformNode.prototype, "_rotation", void 0);
  19497. __decorate([
  19498. BABYLON.serializeAsQuaternion()
  19499. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19500. __decorate([
  19501. BABYLON.serializeAsVector3()
  19502. ], TransformNode.prototype, "_scaling", void 0);
  19503. __decorate([
  19504. BABYLON.serialize()
  19505. ], TransformNode.prototype, "billboardMode", void 0);
  19506. __decorate([
  19507. BABYLON.serialize()
  19508. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19509. __decorate([
  19510. BABYLON.serialize()
  19511. ], TransformNode.prototype, "infiniteDistance", void 0);
  19512. __decorate([
  19513. BABYLON.serialize()
  19514. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19515. __decorate([
  19516. BABYLON.serializeAsVector3()
  19517. ], TransformNode.prototype, "position", void 0);
  19518. return TransformNode;
  19519. }(BABYLON.Node));
  19520. BABYLON.TransformNode = TransformNode;
  19521. })(BABYLON || (BABYLON = {}));
  19522. //# sourceMappingURL=babylon.transformNode.js.map
  19523. var BABYLON;
  19524. (function (BABYLON) {
  19525. /**
  19526. * Class used to store all common mesh properties
  19527. */
  19528. var AbstractMesh = /** @class */ (function (_super) {
  19529. __extends(AbstractMesh, _super);
  19530. // Constructor
  19531. /**
  19532. * Creates a new AbstractMesh
  19533. * @param name defines the name of the mesh
  19534. * @param scene defines the hosting scene
  19535. */
  19536. function AbstractMesh(name, scene) {
  19537. if (scene === void 0) { scene = null; }
  19538. var _this = _super.call(this, name, scene, false) || this;
  19539. _this._facetNb = 0; // facet number
  19540. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19541. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19542. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19543. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19544. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19545. _this._subDiv = {
  19546. max: 1,
  19547. X: 1,
  19548. Y: 1,
  19549. Z: 1
  19550. };
  19551. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19552. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19553. // Events
  19554. /**
  19555. * An event triggered when this mesh collides with another one
  19556. */
  19557. _this.onCollideObservable = new BABYLON.Observable();
  19558. /**
  19559. * An event triggered when the collision's position changes
  19560. */
  19561. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19562. /**
  19563. * An event triggered when material is changed
  19564. */
  19565. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19566. // Properties
  19567. /**
  19568. * Gets or sets the orientation for POV movement & rotation
  19569. */
  19570. _this.definedFacingForward = true;
  19571. /**
  19572. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19573. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19574. * * 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.
  19575. * @see http://doc.babylonjs.com/features/occlusionquery
  19576. */
  19577. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19578. /**
  19579. * 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:
  19580. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19581. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19582. * * 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.
  19583. * @see http://doc.babylonjs.com/features/occlusionquery
  19584. */
  19585. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19586. /**
  19587. * 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.
  19588. * The default value is -1 which means don't break the query and wait till the result
  19589. * @see http://doc.babylonjs.com/features/occlusionquery
  19590. */
  19591. _this.occlusionRetryCount = -1;
  19592. _this._occlusionInternalRetryCounter = 0;
  19593. _this._isOccluded = false;
  19594. _this._isOcclusionQueryInProgress = false;
  19595. _this._visibility = 1.0;
  19596. /** Gets or sets the alpha index used to sort transparent meshes
  19597. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19598. */
  19599. _this.alphaIndex = Number.MAX_VALUE;
  19600. /**
  19601. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19602. */
  19603. _this.isVisible = true;
  19604. /**
  19605. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19606. */
  19607. _this.isPickable = true;
  19608. /**
  19609. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19610. */
  19611. _this.showBoundingBox = false;
  19612. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19613. _this.showSubMeshesBoundingBox = false;
  19614. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19615. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19616. */
  19617. _this.isBlocker = false;
  19618. /**
  19619. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19620. */
  19621. _this.enablePointerMoveEvents = false;
  19622. /**
  19623. * Specifies the rendering group id for this mesh (0 by default)
  19624. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19625. */
  19626. _this.renderingGroupId = 0;
  19627. _this._receiveShadows = false;
  19628. /**
  19629. * Gets or sets a boolean indicating if the outline must be rendered as well
  19630. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19631. */
  19632. _this.renderOutline = false;
  19633. /** Defines color to use when rendering outline */
  19634. _this.outlineColor = BABYLON.Color3.Red();
  19635. /** Define width to use when rendering outline */
  19636. _this.outlineWidth = 0.02;
  19637. /**
  19638. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19639. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19640. */
  19641. _this.renderOverlay = false;
  19642. /** Defines color to use when rendering overlay */
  19643. _this.overlayColor = BABYLON.Color3.Red();
  19644. /** Defines alpha to use when rendering overlay */
  19645. _this.overlayAlpha = 0.5;
  19646. _this._hasVertexAlpha = false;
  19647. _this._useVertexColors = true;
  19648. _this._computeBonesUsingShaders = true;
  19649. _this._numBoneInfluencers = 4;
  19650. _this._applyFog = true;
  19651. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19652. _this.useOctreeForRenderingSelection = true;
  19653. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19654. _this.useOctreeForPicking = true;
  19655. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19656. _this.useOctreeForCollisions = true;
  19657. _this._layerMask = 0x0FFFFFFF;
  19658. /**
  19659. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19660. */
  19661. _this.alwaysSelectAsActiveMesh = false;
  19662. /**
  19663. * Gets or sets the current action manager
  19664. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19665. */
  19666. _this.actionManager = null;
  19667. /**
  19668. * Gets or sets impostor used for physic simulation
  19669. * @see http://doc.babylonjs.com/features/physics_engine
  19670. */
  19671. _this.physicsImpostor = null;
  19672. // Collisions
  19673. _this._checkCollisions = false;
  19674. _this._collisionMask = -1;
  19675. _this._collisionGroup = -1;
  19676. /**
  19677. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19678. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19679. */
  19680. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19681. /**
  19682. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19683. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19684. */
  19685. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19686. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19687. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19688. // Edges
  19689. /**
  19690. * Defines edge width used when edgesRenderer is enabled
  19691. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19692. */
  19693. _this.edgesWidth = 1;
  19694. /**
  19695. * Defines edge color used when edgesRenderer is enabled
  19696. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19697. */
  19698. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19699. // Cache
  19700. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19701. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19702. /** @hidden */
  19703. _this._renderId = 0;
  19704. /** @hidden */
  19705. _this._intersectionsInProgress = new Array();
  19706. /** @hidden */
  19707. _this._unIndexed = false;
  19708. /** @hidden */
  19709. _this._lightSources = new Array();
  19710. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19711. if (collidedMesh === void 0) { collidedMesh = null; }
  19712. //TODO move this to the collision coordinator!
  19713. if (_this.getScene().workerCollisions)
  19714. newPosition.multiplyInPlace(_this._collider._radius);
  19715. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19716. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19717. _this.position.addInPlace(_this._diffPositionForCollisions);
  19718. }
  19719. if (collidedMesh) {
  19720. _this.onCollideObservable.notifyObservers(collidedMesh);
  19721. }
  19722. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19723. };
  19724. _this.getScene().addMesh(_this);
  19725. _this._resyncLightSources();
  19726. return _this;
  19727. }
  19728. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19729. /**
  19730. * No billboard
  19731. */
  19732. get: function () {
  19733. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19734. },
  19735. enumerable: true,
  19736. configurable: true
  19737. });
  19738. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19739. /** Billboard on X axis */
  19740. get: function () {
  19741. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19742. },
  19743. enumerable: true,
  19744. configurable: true
  19745. });
  19746. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19747. /** Billboard on Y axis */
  19748. get: function () {
  19749. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19750. },
  19751. enumerable: true,
  19752. configurable: true
  19753. });
  19754. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19755. /** Billboard on Z axis */
  19756. get: function () {
  19757. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19763. /** Billboard on all axes */
  19764. get: function () {
  19765. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19771. /**
  19772. * Gets the number of facets in the mesh
  19773. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19774. */
  19775. get: function () {
  19776. return this._facetNb;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19782. /**
  19783. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19784. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19785. */
  19786. get: function () {
  19787. return this._partitioningSubdivisions;
  19788. },
  19789. set: function (nb) {
  19790. this._partitioningSubdivisions = nb;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19796. /**
  19797. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19798. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19799. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19800. */
  19801. get: function () {
  19802. return this._partitioningBBoxRatio;
  19803. },
  19804. set: function (ratio) {
  19805. this._partitioningBBoxRatio = ratio;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19811. /**
  19812. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19813. * Works only for updatable meshes.
  19814. * Doesn't work with multi-materials
  19815. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19816. */
  19817. get: function () {
  19818. return this._facetDepthSort;
  19819. },
  19820. set: function (sort) {
  19821. this._facetDepthSort = sort;
  19822. },
  19823. enumerable: true,
  19824. configurable: true
  19825. });
  19826. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19827. /**
  19828. * The location (Vector3) where the facet depth sort must be computed from.
  19829. * By default, the active camera position.
  19830. * Used only when facet depth sort is enabled
  19831. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19832. */
  19833. get: function () {
  19834. return this._facetDepthSortFrom;
  19835. },
  19836. set: function (location) {
  19837. this._facetDepthSortFrom = location;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19843. /**
  19844. * gets a boolean indicating if facetData is enabled
  19845. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19846. */
  19847. get: function () {
  19848. return this._facetDataEnabled;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. /** @hidden */
  19854. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19855. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19856. return false;
  19857. }
  19858. this._markSubMeshesAsMiscDirty();
  19859. return true;
  19860. };
  19861. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19862. /** Set a function to call when this mesh collides with another one */
  19863. set: function (callback) {
  19864. if (this._onCollideObserver) {
  19865. this.onCollideObservable.remove(this._onCollideObserver);
  19866. }
  19867. this._onCollideObserver = this.onCollideObservable.add(callback);
  19868. },
  19869. enumerable: true,
  19870. configurable: true
  19871. });
  19872. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19873. /** Set a function to call when the collision's position changes */
  19874. set: function (callback) {
  19875. if (this._onCollisionPositionChangeObserver) {
  19876. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19877. }
  19878. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19884. /**
  19885. * 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
  19886. * @see http://doc.babylonjs.com/features/occlusionquery
  19887. */
  19888. get: function () {
  19889. return this._isOccluded;
  19890. },
  19891. set: function (value) {
  19892. this._isOccluded = value;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19898. /**
  19899. * Flag to check the progress status of the query
  19900. * @see http://doc.babylonjs.com/features/occlusionquery
  19901. */
  19902. get: function () {
  19903. return this._isOcclusionQueryInProgress;
  19904. },
  19905. enumerable: true,
  19906. configurable: true
  19907. });
  19908. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19909. /**
  19910. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19911. */
  19912. get: function () {
  19913. return this._visibility;
  19914. },
  19915. /**
  19916. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19917. */
  19918. set: function (value) {
  19919. if (this._visibility === value) {
  19920. return;
  19921. }
  19922. this._visibility = value;
  19923. this._markSubMeshesAsMiscDirty();
  19924. },
  19925. enumerable: true,
  19926. configurable: true
  19927. });
  19928. Object.defineProperty(AbstractMesh.prototype, "material", {
  19929. /** Gets or sets current material */
  19930. get: function () {
  19931. return this._material;
  19932. },
  19933. set: function (value) {
  19934. if (this._material === value) {
  19935. return;
  19936. }
  19937. this._material = value;
  19938. if (this.onMaterialChangedObservable.hasObservers) {
  19939. this.onMaterialChangedObservable.notifyObservers(this);
  19940. }
  19941. if (!this.subMeshes) {
  19942. return;
  19943. }
  19944. this._unBindEffect();
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19950. /**
  19951. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19952. * @see http://doc.babylonjs.com/babylon101/shadows
  19953. */
  19954. get: function () {
  19955. return this._receiveShadows;
  19956. },
  19957. set: function (value) {
  19958. if (this._receiveShadows === value) {
  19959. return;
  19960. }
  19961. this._receiveShadows = value;
  19962. this._markSubMeshesAsLightDirty();
  19963. },
  19964. enumerable: true,
  19965. configurable: true
  19966. });
  19967. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19968. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19969. get: function () {
  19970. return this._hasVertexAlpha;
  19971. },
  19972. set: function (value) {
  19973. if (this._hasVertexAlpha === value) {
  19974. return;
  19975. }
  19976. this._hasVertexAlpha = value;
  19977. this._markSubMeshesAsAttributesDirty();
  19978. this._markSubMeshesAsMiscDirty();
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19984. /** 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) */
  19985. get: function () {
  19986. return this._useVertexColors;
  19987. },
  19988. set: function (value) {
  19989. if (this._useVertexColors === value) {
  19990. return;
  19991. }
  19992. this._useVertexColors = value;
  19993. this._markSubMeshesAsAttributesDirty();
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19999. /**
  20000. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20001. */
  20002. get: function () {
  20003. return this._computeBonesUsingShaders;
  20004. },
  20005. set: function (value) {
  20006. if (this._computeBonesUsingShaders === value) {
  20007. return;
  20008. }
  20009. this._computeBonesUsingShaders = value;
  20010. this._markSubMeshesAsAttributesDirty();
  20011. },
  20012. enumerable: true,
  20013. configurable: true
  20014. });
  20015. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20016. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20017. get: function () {
  20018. return this._numBoneInfluencers;
  20019. },
  20020. set: function (value) {
  20021. if (this._numBoneInfluencers === value) {
  20022. return;
  20023. }
  20024. this._numBoneInfluencers = value;
  20025. this._markSubMeshesAsAttributesDirty();
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20031. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20032. get: function () {
  20033. return this._applyFog;
  20034. },
  20035. set: function (value) {
  20036. if (this._applyFog === value) {
  20037. return;
  20038. }
  20039. this._applyFog = value;
  20040. this._markSubMeshesAsMiscDirty();
  20041. },
  20042. enumerable: true,
  20043. configurable: true
  20044. });
  20045. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20046. /**
  20047. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20048. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20049. */
  20050. get: function () {
  20051. return this._layerMask;
  20052. },
  20053. set: function (value) {
  20054. if (value === this._layerMask) {
  20055. return;
  20056. }
  20057. this._layerMask = value;
  20058. this._resyncLightSources();
  20059. },
  20060. enumerable: true,
  20061. configurable: true
  20062. });
  20063. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20064. /**
  20065. * Gets or sets a collision mask used to mask collisions (default is -1).
  20066. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20067. */
  20068. get: function () {
  20069. return this._collisionMask;
  20070. },
  20071. set: function (mask) {
  20072. this._collisionMask = !isNaN(mask) ? mask : -1;
  20073. },
  20074. enumerable: true,
  20075. configurable: true
  20076. });
  20077. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20078. /**
  20079. * Gets or sets the current collision group mask (-1 by default).
  20080. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20081. */
  20082. get: function () {
  20083. return this._collisionGroup;
  20084. },
  20085. set: function (mask) {
  20086. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20092. /** @hidden */
  20093. get: function () {
  20094. return null;
  20095. },
  20096. enumerable: true,
  20097. configurable: true
  20098. });
  20099. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20100. get: function () {
  20101. return this._skeleton;
  20102. },
  20103. /**
  20104. * Gets or sets a skeleton to apply skining transformations
  20105. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20106. */
  20107. set: function (value) {
  20108. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20109. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20110. }
  20111. if (value && value.needInitialSkinMatrix) {
  20112. value._registerMeshWithPoseMatrix(this);
  20113. }
  20114. this._skeleton = value;
  20115. if (!this._skeleton) {
  20116. this._bonesTransformMatrices = null;
  20117. }
  20118. this._markSubMeshesAsAttributesDirty();
  20119. },
  20120. enumerable: true,
  20121. configurable: true
  20122. });
  20123. /**
  20124. * Returns the string "AbstractMesh"
  20125. * @returns "AbstractMesh"
  20126. */
  20127. AbstractMesh.prototype.getClassName = function () {
  20128. return "AbstractMesh";
  20129. };
  20130. /**
  20131. * Gets a string representation of the current mesh
  20132. * @param fullDetails defines a boolean indicating if full details must be included
  20133. * @returns a string representation of the current mesh
  20134. */
  20135. AbstractMesh.prototype.toString = function (fullDetails) {
  20136. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20137. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20138. if (this._skeleton) {
  20139. ret += ", skeleton: " + this._skeleton.name;
  20140. }
  20141. if (fullDetails) {
  20142. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20143. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20144. }
  20145. return ret;
  20146. };
  20147. /** @hidden */
  20148. AbstractMesh.prototype._rebuild = function () {
  20149. if (this._occlusionQuery) {
  20150. this._occlusionQuery = null;
  20151. }
  20152. if (this._edgesRenderer) {
  20153. this._edgesRenderer._rebuild();
  20154. }
  20155. if (!this.subMeshes) {
  20156. return;
  20157. }
  20158. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20159. var subMesh = _a[_i];
  20160. subMesh._rebuild();
  20161. }
  20162. };
  20163. /** @hidden */
  20164. AbstractMesh.prototype._resyncLightSources = function () {
  20165. this._lightSources.length = 0;
  20166. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20167. var light = _a[_i];
  20168. if (!light.isEnabled()) {
  20169. continue;
  20170. }
  20171. if (light.canAffectMesh(this)) {
  20172. this._lightSources.push(light);
  20173. }
  20174. }
  20175. this._markSubMeshesAsLightDirty();
  20176. };
  20177. /** @hidden */
  20178. AbstractMesh.prototype._resyncLighSource = function (light) {
  20179. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20180. var index = this._lightSources.indexOf(light);
  20181. if (index === -1) {
  20182. if (!isIn) {
  20183. return;
  20184. }
  20185. this._lightSources.push(light);
  20186. }
  20187. else {
  20188. if (isIn) {
  20189. return;
  20190. }
  20191. this._lightSources.splice(index, 1);
  20192. }
  20193. this._markSubMeshesAsLightDirty();
  20194. };
  20195. /** @hidden */
  20196. AbstractMesh.prototype._unBindEffect = function () {
  20197. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20198. var subMesh = _a[_i];
  20199. subMesh.setEffect(null);
  20200. }
  20201. };
  20202. /** @hidden */
  20203. AbstractMesh.prototype._removeLightSource = function (light) {
  20204. var index = this._lightSources.indexOf(light);
  20205. if (index === -1) {
  20206. return;
  20207. }
  20208. this._lightSources.splice(index, 1);
  20209. this._markSubMeshesAsLightDirty();
  20210. };
  20211. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20212. if (!this.subMeshes) {
  20213. return;
  20214. }
  20215. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20216. var subMesh = _a[_i];
  20217. if (subMesh._materialDefines) {
  20218. func(subMesh._materialDefines);
  20219. }
  20220. }
  20221. };
  20222. /** @hidden */
  20223. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20224. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20225. };
  20226. /** @hidden */
  20227. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20228. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20229. };
  20230. /** @hidden */
  20231. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20232. if (!this.subMeshes) {
  20233. return;
  20234. }
  20235. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20236. var subMesh = _a[_i];
  20237. var material = subMesh.getMaterial();
  20238. if (material) {
  20239. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20240. }
  20241. }
  20242. };
  20243. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20244. /**
  20245. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20246. */
  20247. get: function () {
  20248. return this._scaling;
  20249. },
  20250. set: function (newScaling) {
  20251. this._scaling = newScaling;
  20252. if (this.physicsImpostor) {
  20253. this.physicsImpostor.forceUpdate();
  20254. }
  20255. },
  20256. enumerable: true,
  20257. configurable: true
  20258. });
  20259. // Methods
  20260. /**
  20261. * Disables the mesh edge rendering mode
  20262. * @returns the currentAbstractMesh
  20263. */
  20264. AbstractMesh.prototype.disableEdgesRendering = function () {
  20265. if (this._edgesRenderer) {
  20266. this._edgesRenderer.dispose();
  20267. this._edgesRenderer = null;
  20268. }
  20269. return this;
  20270. };
  20271. /**
  20272. * Enables the edge rendering mode on the mesh.
  20273. * This mode makes the mesh edges visible
  20274. * @param epsilon defines the maximal distance between two angles to detect a face
  20275. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20276. * @returns the currentAbstractMesh
  20277. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20278. */
  20279. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20280. if (epsilon === void 0) { epsilon = 0.95; }
  20281. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20282. this.disableEdgesRendering();
  20283. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20284. return this;
  20285. };
  20286. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20287. /**
  20288. * Gets the edgesRenderer associated with the mesh
  20289. */
  20290. get: function () {
  20291. return this._edgesRenderer;
  20292. },
  20293. enumerable: true,
  20294. configurable: true
  20295. });
  20296. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20297. /**
  20298. * Returns true if the mesh is blocked. Implemented by child classes
  20299. */
  20300. get: function () {
  20301. return false;
  20302. },
  20303. enumerable: true,
  20304. configurable: true
  20305. });
  20306. /**
  20307. * Returns the mesh itself by default. Implemented by child classes
  20308. * @param camera defines the camera to use to pick the right LOD level
  20309. * @returns the currentAbstractMesh
  20310. */
  20311. AbstractMesh.prototype.getLOD = function (camera) {
  20312. return this;
  20313. };
  20314. /**
  20315. * Returns 0 by default. Implemented by child classes
  20316. * @returns an integer
  20317. */
  20318. AbstractMesh.prototype.getTotalVertices = function () {
  20319. return 0;
  20320. };
  20321. /**
  20322. * Returns null by default. Implemented by child classes
  20323. * @returns null
  20324. */
  20325. AbstractMesh.prototype.getIndices = function () {
  20326. return null;
  20327. };
  20328. /**
  20329. * Returns the array of the requested vertex data kind. Implemented by child classes
  20330. * @param kind defines the vertex data kind to use
  20331. * @returns null
  20332. */
  20333. AbstractMesh.prototype.getVerticesData = function (kind) {
  20334. return null;
  20335. };
  20336. /**
  20337. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20338. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20339. * Note that a new underlying VertexBuffer object is created each call.
  20340. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20341. * @param kind defines vertex data kind:
  20342. * * BABYLON.VertexBuffer.PositionKind
  20343. * * BABYLON.VertexBuffer.UVKind
  20344. * * BABYLON.VertexBuffer.UV2Kind
  20345. * * BABYLON.VertexBuffer.UV3Kind
  20346. * * BABYLON.VertexBuffer.UV4Kind
  20347. * * BABYLON.VertexBuffer.UV5Kind
  20348. * * BABYLON.VertexBuffer.UV6Kind
  20349. * * BABYLON.VertexBuffer.ColorKind
  20350. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20351. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20352. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20353. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20354. * @param data defines the data source
  20355. * @param updatable defines if the data must be flagged as updatable (or static)
  20356. * @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
  20357. * @returns the current mesh
  20358. */
  20359. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20360. return this;
  20361. };
  20362. /**
  20363. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20364. * If the mesh has no geometry, it is simply returned as it is.
  20365. * @param kind defines vertex data kind:
  20366. * * BABYLON.VertexBuffer.PositionKind
  20367. * * BABYLON.VertexBuffer.UVKind
  20368. * * BABYLON.VertexBuffer.UV2Kind
  20369. * * BABYLON.VertexBuffer.UV3Kind
  20370. * * BABYLON.VertexBuffer.UV4Kind
  20371. * * BABYLON.VertexBuffer.UV5Kind
  20372. * * BABYLON.VertexBuffer.UV6Kind
  20373. * * BABYLON.VertexBuffer.ColorKind
  20374. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20375. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20376. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20377. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20378. * @param data defines the data source
  20379. * @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
  20380. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20381. * @returns the current mesh
  20382. */
  20383. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20384. return this;
  20385. };
  20386. /**
  20387. * Sets the mesh indices,
  20388. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20389. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20390. * @param totalVertices Defines the total number of vertices
  20391. * @returns the current mesh
  20392. */
  20393. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20394. return this;
  20395. };
  20396. /**
  20397. * Gets a boolean indicating if specific vertex data is present
  20398. * @param kind defines the vertex data kind to use
  20399. * @returns true is data kind is present
  20400. */
  20401. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20402. return false;
  20403. };
  20404. /**
  20405. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20406. * @returns a BoundingInfo
  20407. */
  20408. AbstractMesh.prototype.getBoundingInfo = function () {
  20409. if (this._masterMesh) {
  20410. return this._masterMesh.getBoundingInfo();
  20411. }
  20412. if (!this._boundingInfo) {
  20413. // this._boundingInfo is being created here
  20414. this._updateBoundingInfo();
  20415. }
  20416. // cannot be null.
  20417. return this._boundingInfo;
  20418. };
  20419. /**
  20420. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20421. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20422. * @returns the current mesh
  20423. */
  20424. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20425. if (includeDescendants === void 0) { includeDescendants = true; }
  20426. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20427. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20428. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20429. if (maxDimension === 0) {
  20430. return this;
  20431. }
  20432. var scale = 1 / maxDimension;
  20433. this.scaling.scaleInPlace(scale);
  20434. return this;
  20435. };
  20436. /**
  20437. * Overwrite the current bounding info
  20438. * @param boundingInfo defines the new bounding info
  20439. * @returns the current mesh
  20440. */
  20441. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20442. this._boundingInfo = boundingInfo;
  20443. return this;
  20444. };
  20445. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20446. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20447. get: function () {
  20448. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20449. },
  20450. enumerable: true,
  20451. configurable: true
  20452. });
  20453. /** @hidden */
  20454. AbstractMesh.prototype._preActivate = function () {
  20455. };
  20456. /** @hidden */
  20457. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20458. };
  20459. /** @hidden */
  20460. AbstractMesh.prototype._activate = function (renderId) {
  20461. this._renderId = renderId;
  20462. };
  20463. /**
  20464. * Gets the current world matrix
  20465. * @returns a Matrix
  20466. */
  20467. AbstractMesh.prototype.getWorldMatrix = function () {
  20468. if (this._masterMesh) {
  20469. return this._masterMesh.getWorldMatrix();
  20470. }
  20471. return _super.prototype.getWorldMatrix.call(this);
  20472. };
  20473. /** @hidden */
  20474. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20475. if (this._masterMesh) {
  20476. return this._masterMesh._getWorldMatrixDeterminant();
  20477. }
  20478. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20479. };
  20480. // ================================== Point of View Movement =================================
  20481. /**
  20482. * Perform relative position change from the point of view of behind the front of the mesh.
  20483. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20484. * Supports definition of mesh facing forward or backward
  20485. * @param amountRight defines the distance on the right axis
  20486. * @param amountUp defines the distance on the up axis
  20487. * @param amountForward defines the distance on the forward axis
  20488. * @returns the current mesh
  20489. */
  20490. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20491. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20492. return this;
  20493. };
  20494. /**
  20495. * Calculate relative position change from the point of view of behind the front of the mesh.
  20496. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20497. * Supports definition of mesh facing forward or backward
  20498. * @param amountRight defines the distance on the right axis
  20499. * @param amountUp defines the distance on the up axis
  20500. * @param amountForward defines the distance on the forward axis
  20501. * @returns the new displacement vector
  20502. */
  20503. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20504. var rotMatrix = new BABYLON.Matrix();
  20505. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20506. rotQuaternion.toRotationMatrix(rotMatrix);
  20507. var translationDelta = BABYLON.Vector3.Zero();
  20508. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20509. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20510. return translationDelta;
  20511. };
  20512. // ================================== Point of View Rotation =================================
  20513. /**
  20514. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20515. * Supports definition of mesh facing forward or backward
  20516. * @param flipBack defines the flip
  20517. * @param twirlClockwise defines the twirl
  20518. * @param tiltRight defines the tilt
  20519. * @returns the current mesh
  20520. */
  20521. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20522. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20523. return this;
  20524. };
  20525. /**
  20526. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20527. * Supports definition of mesh facing forward or backward.
  20528. * @param flipBack defines the flip
  20529. * @param twirlClockwise defines the twirl
  20530. * @param tiltRight defines the tilt
  20531. * @returns the new rotation vector
  20532. */
  20533. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20534. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20535. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20536. };
  20537. /**
  20538. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20539. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20540. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20541. * @returns the new bounding vectors
  20542. */
  20543. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20544. if (includeDescendants === void 0) { includeDescendants = true; }
  20545. if (predicate === void 0) { predicate = null; }
  20546. // Ensures that all world matrix will be recomputed.
  20547. this.getScene().incrementRenderId();
  20548. this.computeWorldMatrix(true);
  20549. var min;
  20550. var max;
  20551. var boundingInfo = this.getBoundingInfo();
  20552. if (!this.subMeshes) {
  20553. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20554. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20555. }
  20556. else {
  20557. min = boundingInfo.boundingBox.minimumWorld;
  20558. max = boundingInfo.boundingBox.maximumWorld;
  20559. }
  20560. if (includeDescendants) {
  20561. var descendants = this.getDescendants(false);
  20562. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20563. var descendant = descendants_1[_i];
  20564. var childMesh = descendant;
  20565. childMesh.computeWorldMatrix(true);
  20566. // Filters meshes based on custom predicate function.
  20567. if (predicate && !predicate(childMesh)) {
  20568. continue;
  20569. }
  20570. //make sure we have the needed params to get mix and max
  20571. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20572. continue;
  20573. }
  20574. var childBoundingInfo = childMesh.getBoundingInfo();
  20575. var boundingBox = childBoundingInfo.boundingBox;
  20576. var minBox = boundingBox.minimumWorld;
  20577. var maxBox = boundingBox.maximumWorld;
  20578. BABYLON.Tools.CheckExtends(minBox, min, max);
  20579. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20580. }
  20581. }
  20582. return {
  20583. min: min,
  20584. max: max
  20585. };
  20586. };
  20587. /** @hidden */
  20588. AbstractMesh.prototype._updateBoundingInfo = function () {
  20589. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20590. this._boundingInfo.update(this.worldMatrixFromCache);
  20591. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20592. return this;
  20593. };
  20594. /** @hidden */
  20595. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20596. if (!this.subMeshes) {
  20597. return this;
  20598. }
  20599. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20600. var subMesh = this.subMeshes[subIndex];
  20601. if (!subMesh.IsGlobal) {
  20602. subMesh.updateBoundingInfo(matrix);
  20603. }
  20604. }
  20605. return this;
  20606. };
  20607. /** @hidden */
  20608. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20609. // Bounding info
  20610. this._updateBoundingInfo();
  20611. };
  20612. /**
  20613. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20614. * A mesh is in the frustum if its bounding box intersects the frustum
  20615. * @param frustumPlanes defines the frustum to test
  20616. * @returns true if the mesh is in the frustum planes
  20617. */
  20618. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20619. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20620. };
  20621. /**
  20622. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20623. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20624. * @param frustumPlanes defines the frustum to test
  20625. * @returns true if the mesh is completely in the frustum planes
  20626. */
  20627. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20628. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20629. };
  20630. /**
  20631. * True if the mesh intersects another mesh or a SolidParticle object
  20632. * @param mesh defines a target mesh or SolidParticle to test
  20633. * @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)
  20634. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20635. * @returns true if there is an intersection
  20636. */
  20637. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20638. if (precise === void 0) { precise = false; }
  20639. if (!this._boundingInfo || !mesh._boundingInfo) {
  20640. return false;
  20641. }
  20642. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20643. return true;
  20644. }
  20645. if (includeDescendants) {
  20646. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20647. var child = _a[_i];
  20648. if (child.intersectsMesh(mesh, precise, true)) {
  20649. return true;
  20650. }
  20651. }
  20652. }
  20653. return false;
  20654. };
  20655. /**
  20656. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20657. * @param point defines the point to test
  20658. * @returns true if there is an intersection
  20659. */
  20660. AbstractMesh.prototype.intersectsPoint = function (point) {
  20661. if (!this._boundingInfo) {
  20662. return false;
  20663. }
  20664. return this._boundingInfo.intersectsPoint(point);
  20665. };
  20666. /**
  20667. * Gets the current physics impostor
  20668. * @see http://doc.babylonjs.com/features/physics_engine
  20669. * @returns a physics impostor or null
  20670. */
  20671. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20672. return this.physicsImpostor;
  20673. };
  20674. /**
  20675. * Gets the position of the current mesh in camera space
  20676. * @param camera defines the camera to use
  20677. * @returns a position
  20678. */
  20679. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20680. if (camera === void 0) { camera = null; }
  20681. if (!camera) {
  20682. camera = this.getScene().activeCamera;
  20683. }
  20684. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20685. };
  20686. /**
  20687. * Returns the distance from the mesh to the active camera
  20688. * @param camera defines the camera to use
  20689. * @returns the distance
  20690. */
  20691. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20692. if (camera === void 0) { camera = null; }
  20693. if (!camera) {
  20694. camera = this.getScene().activeCamera;
  20695. }
  20696. return this.absolutePosition.subtract(camera.position).length();
  20697. };
  20698. /**
  20699. * Apply a physic impulse to the mesh
  20700. * @param force defines the force to apply
  20701. * @param contactPoint defines where to apply the force
  20702. * @returns the current mesh
  20703. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20704. */
  20705. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20706. if (!this.physicsImpostor) {
  20707. return this;
  20708. }
  20709. this.physicsImpostor.applyImpulse(force, contactPoint);
  20710. return this;
  20711. };
  20712. /**
  20713. * Creates a physic joint between two meshes
  20714. * @param otherMesh defines the other mesh to use
  20715. * @param pivot1 defines the pivot to use on this mesh
  20716. * @param pivot2 defines the pivot to use on the other mesh
  20717. * @param options defines additional options (can be plugin dependent)
  20718. * @returns the current mesh
  20719. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20720. */
  20721. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20722. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20723. return this;
  20724. }
  20725. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20726. mainPivot: pivot1,
  20727. connectedPivot: pivot2,
  20728. nativeParams: options
  20729. });
  20730. return this;
  20731. };
  20732. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20733. // Collisions
  20734. /**
  20735. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20736. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20737. */
  20738. get: function () {
  20739. return this._checkCollisions;
  20740. },
  20741. set: function (collisionEnabled) {
  20742. this._checkCollisions = collisionEnabled;
  20743. if (this.getScene().workerCollisions) {
  20744. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20745. }
  20746. },
  20747. enumerable: true,
  20748. configurable: true
  20749. });
  20750. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20751. /**
  20752. * Gets Collider object used to compute collisions (not physics)
  20753. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20754. */
  20755. get: function () {
  20756. return this._collider;
  20757. },
  20758. enumerable: true,
  20759. configurable: true
  20760. });
  20761. /**
  20762. * Move the mesh using collision engine
  20763. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20764. * @param displacement defines the requested displacement vector
  20765. * @returns the current mesh
  20766. */
  20767. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20768. var globalPosition = this.getAbsolutePosition();
  20769. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20770. if (!this._collider) {
  20771. this._collider = new BABYLON.Collider();
  20772. }
  20773. this._collider._radius = this.ellipsoid;
  20774. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20775. return this;
  20776. };
  20777. // Submeshes octree
  20778. /**
  20779. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20780. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20781. * @param maxCapacity defines the maximum size of each block (64 by default)
  20782. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20783. * @returns the new octree
  20784. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20785. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20786. */
  20787. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20788. if (maxCapacity === void 0) { maxCapacity = 64; }
  20789. if (maxDepth === void 0) { maxDepth = 2; }
  20790. if (!this._submeshesOctree) {
  20791. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20792. }
  20793. this.computeWorldMatrix(true);
  20794. var boundingInfo = this.getBoundingInfo();
  20795. // Update octree
  20796. var bbox = boundingInfo.boundingBox;
  20797. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20798. return this._submeshesOctree;
  20799. };
  20800. // Collisions
  20801. /** @hidden */
  20802. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20803. this._generatePointsArray();
  20804. if (!this._positions) {
  20805. return this;
  20806. }
  20807. // Transformation
  20808. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20809. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20810. subMesh._lastColliderWorldVertices = [];
  20811. subMesh._trianglePlanes = [];
  20812. var start = subMesh.verticesStart;
  20813. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20814. for (var i = start; i < end; i++) {
  20815. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20816. }
  20817. }
  20818. // Collide
  20819. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20820. if (collider.collisionFound) {
  20821. collider.collidedMesh = this;
  20822. }
  20823. return this;
  20824. };
  20825. /** @hidden */
  20826. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20827. var subMeshes;
  20828. var len;
  20829. // Octrees
  20830. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20831. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20832. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20833. len = intersections.length;
  20834. subMeshes = intersections.data;
  20835. }
  20836. else {
  20837. subMeshes = this.subMeshes;
  20838. len = subMeshes.length;
  20839. }
  20840. for (var index = 0; index < len; index++) {
  20841. var subMesh = subMeshes[index];
  20842. // Bounding test
  20843. if (len > 1 && !subMesh._checkCollision(collider))
  20844. continue;
  20845. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20846. }
  20847. return this;
  20848. };
  20849. /** @hidden */
  20850. AbstractMesh.prototype._checkCollision = function (collider) {
  20851. // Bounding box test
  20852. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20853. return this;
  20854. // Transformation matrix
  20855. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20856. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20857. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20858. return this;
  20859. };
  20860. // Picking
  20861. /** @hidden */
  20862. AbstractMesh.prototype._generatePointsArray = function () {
  20863. return false;
  20864. };
  20865. /**
  20866. * Checks if the passed Ray intersects with the mesh
  20867. * @param ray defines the ray to use
  20868. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20869. * @returns the picking info
  20870. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20871. */
  20872. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20873. var pickingInfo = new BABYLON.PickingInfo();
  20874. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20875. return pickingInfo;
  20876. }
  20877. if (!this._generatePointsArray()) {
  20878. return pickingInfo;
  20879. }
  20880. var intersectInfo = null;
  20881. // Octrees
  20882. var subMeshes;
  20883. var len;
  20884. if (this._submeshesOctree && this.useOctreeForPicking) {
  20885. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20886. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20887. len = intersections.length;
  20888. subMeshes = intersections.data;
  20889. }
  20890. else {
  20891. subMeshes = this.subMeshes;
  20892. len = subMeshes.length;
  20893. }
  20894. for (var index = 0; index < len; index++) {
  20895. var subMesh = subMeshes[index];
  20896. // Bounding test
  20897. if (len > 1 && !subMesh.canIntersects(ray))
  20898. continue;
  20899. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20900. if (currentIntersectInfo) {
  20901. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20902. intersectInfo = currentIntersectInfo;
  20903. intersectInfo.subMeshId = index;
  20904. if (fastCheck) {
  20905. break;
  20906. }
  20907. }
  20908. }
  20909. }
  20910. if (intersectInfo) {
  20911. // Get picked point
  20912. var world = this.getWorldMatrix();
  20913. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20914. var direction = ray.direction.clone();
  20915. direction = direction.scale(intersectInfo.distance);
  20916. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20917. var pickedPoint = worldOrigin.add(worldDirection);
  20918. // Return result
  20919. pickingInfo.hit = true;
  20920. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20921. pickingInfo.pickedPoint = pickedPoint;
  20922. pickingInfo.pickedMesh = this;
  20923. pickingInfo.bu = intersectInfo.bu || 0;
  20924. pickingInfo.bv = intersectInfo.bv || 0;
  20925. pickingInfo.faceId = intersectInfo.faceId;
  20926. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20927. return pickingInfo;
  20928. }
  20929. return pickingInfo;
  20930. };
  20931. /**
  20932. * Clones the current mesh
  20933. * @param name defines the mesh name
  20934. * @param newParent defines the new mesh parent
  20935. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20936. * @returns the new mesh
  20937. */
  20938. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20939. return null;
  20940. };
  20941. /**
  20942. * Disposes all the submeshes of the current meshnp
  20943. * @returns the current mesh
  20944. */
  20945. AbstractMesh.prototype.releaseSubMeshes = function () {
  20946. if (this.subMeshes) {
  20947. while (this.subMeshes.length) {
  20948. this.subMeshes[0].dispose();
  20949. }
  20950. }
  20951. else {
  20952. this.subMeshes = new Array();
  20953. }
  20954. return this;
  20955. };
  20956. /**
  20957. * Releases resources associated with this abstract mesh.
  20958. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20959. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20960. */
  20961. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20962. var _this = this;
  20963. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20964. var index;
  20965. // Smart Array Retainers.
  20966. this.getScene().freeActiveMeshes();
  20967. this.getScene().freeRenderingGroups();
  20968. // Action manager
  20969. if (this.actionManager !== undefined && this.actionManager !== null) {
  20970. this.actionManager.dispose();
  20971. this.actionManager = null;
  20972. }
  20973. // Skeleton
  20974. this._skeleton = null;
  20975. // Physics
  20976. if (this.physicsImpostor) {
  20977. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20978. }
  20979. // Intersections in progress
  20980. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20981. var other = this._intersectionsInProgress[index];
  20982. var pos = other._intersectionsInProgress.indexOf(this);
  20983. other._intersectionsInProgress.splice(pos, 1);
  20984. }
  20985. this._intersectionsInProgress = [];
  20986. // Lights
  20987. var lights = this.getScene().lights;
  20988. lights.forEach(function (light) {
  20989. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20990. if (meshIndex !== -1) {
  20991. light.includedOnlyMeshes.splice(meshIndex, 1);
  20992. }
  20993. meshIndex = light.excludedMeshes.indexOf(_this);
  20994. if (meshIndex !== -1) {
  20995. light.excludedMeshes.splice(meshIndex, 1);
  20996. }
  20997. // Shadow generators
  20998. var generator = light.getShadowGenerator();
  20999. if (generator) {
  21000. var shadowMap = generator.getShadowMap();
  21001. if (shadowMap && shadowMap.renderList) {
  21002. meshIndex = shadowMap.renderList.indexOf(_this);
  21003. if (meshIndex !== -1) {
  21004. shadowMap.renderList.splice(meshIndex, 1);
  21005. }
  21006. }
  21007. }
  21008. });
  21009. // Edges
  21010. if (this._edgesRenderer) {
  21011. this._edgesRenderer.dispose();
  21012. this._edgesRenderer = null;
  21013. }
  21014. // SubMeshes
  21015. if (this.getClassName() !== "InstancedMesh") {
  21016. this.releaseSubMeshes();
  21017. }
  21018. // Octree
  21019. var sceneOctree = this.getScene().selectionOctree;
  21020. if (sceneOctree !== undefined && sceneOctree !== null) {
  21021. var index = sceneOctree.dynamicContent.indexOf(this);
  21022. if (index !== -1) {
  21023. sceneOctree.dynamicContent.splice(index, 1);
  21024. }
  21025. }
  21026. // Query
  21027. var engine = this.getScene().getEngine();
  21028. if (this._occlusionQuery) {
  21029. this._isOcclusionQueryInProgress = false;
  21030. engine.deleteQuery(this._occlusionQuery);
  21031. this._occlusionQuery = null;
  21032. }
  21033. // Engine
  21034. engine.wipeCaches();
  21035. // Remove from scene
  21036. this.getScene().removeMesh(this);
  21037. if (disposeMaterialAndTextures) {
  21038. if (this.material) {
  21039. this.material.dispose(false, true);
  21040. }
  21041. }
  21042. if (!doNotRecurse) {
  21043. // Particles
  21044. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21045. if (this.getScene().particleSystems[index].emitter === this) {
  21046. this.getScene().particleSystems[index].dispose();
  21047. index--;
  21048. }
  21049. }
  21050. }
  21051. // facet data
  21052. if (this._facetDataEnabled) {
  21053. this.disableFacetData();
  21054. }
  21055. this.onAfterWorldMatrixUpdateObservable.clear();
  21056. this.onCollideObservable.clear();
  21057. this.onCollisionPositionChangeObservable.clear();
  21058. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21059. };
  21060. /**
  21061. * Adds the passed mesh as a child to the current mesh
  21062. * @param mesh defines the child mesh
  21063. * @returns the current mesh
  21064. */
  21065. AbstractMesh.prototype.addChild = function (mesh) {
  21066. mesh.setParent(this);
  21067. return this;
  21068. };
  21069. /**
  21070. * Removes the passed mesh from the current mesh children list
  21071. * @param mesh defines the child mesh
  21072. * @returns the current mesh
  21073. */
  21074. AbstractMesh.prototype.removeChild = function (mesh) {
  21075. mesh.setParent(null);
  21076. return this;
  21077. };
  21078. // Facet data
  21079. /** @hidden */
  21080. AbstractMesh.prototype._initFacetData = function () {
  21081. if (!this._facetNormals) {
  21082. this._facetNormals = new Array();
  21083. }
  21084. if (!this._facetPositions) {
  21085. this._facetPositions = new Array();
  21086. }
  21087. if (!this._facetPartitioning) {
  21088. this._facetPartitioning = new Array();
  21089. }
  21090. this._facetNb = (this.getIndices().length / 3) | 0;
  21091. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21092. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21093. for (var f = 0; f < this._facetNb; f++) {
  21094. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21095. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21096. }
  21097. this._facetDataEnabled = true;
  21098. return this;
  21099. };
  21100. /**
  21101. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21102. * This method can be called within the render loop.
  21103. * 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
  21104. * @returns the current mesh
  21105. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21106. */
  21107. AbstractMesh.prototype.updateFacetData = function () {
  21108. if (!this._facetDataEnabled) {
  21109. this._initFacetData();
  21110. }
  21111. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21112. var indices = this.getIndices();
  21113. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21114. var bInfo = this.getBoundingInfo();
  21115. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21116. // init arrays, matrix and sort function on first call
  21117. this._facetDepthSortEnabled = true;
  21118. if (indices instanceof Uint16Array) {
  21119. this._depthSortedIndices = new Uint16Array(indices);
  21120. }
  21121. else if (indices instanceof Uint32Array) {
  21122. this._depthSortedIndices = new Uint32Array(indices);
  21123. }
  21124. else {
  21125. var needs32bits = false;
  21126. for (var i = 0; i < indices.length; i++) {
  21127. if (indices[i] > 65535) {
  21128. needs32bits = true;
  21129. break;
  21130. }
  21131. }
  21132. if (needs32bits) {
  21133. this._depthSortedIndices = new Uint32Array(indices);
  21134. }
  21135. else {
  21136. this._depthSortedIndices = new Uint16Array(indices);
  21137. }
  21138. }
  21139. this._facetDepthSortFunction = function (f1, f2) {
  21140. return (f2.sqDistance - f1.sqDistance);
  21141. };
  21142. if (!this._facetDepthSortFrom) {
  21143. var camera = this.getScene().activeCamera;
  21144. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21145. }
  21146. this._depthSortedFacets = [];
  21147. for (var f = 0; f < this._facetNb; f++) {
  21148. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21149. this._depthSortedFacets.push(depthSortedFacet);
  21150. }
  21151. this._invertedMatrix = BABYLON.Matrix.Identity();
  21152. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21153. }
  21154. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21155. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21156. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21157. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21158. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21159. this._subDiv.max = this._partitioningSubdivisions;
  21160. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21161. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21162. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21163. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21164. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21165. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21166. // set the parameters for ComputeNormals()
  21167. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21168. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21169. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21170. this._facetParameters.bInfo = bInfo;
  21171. this._facetParameters.bbSize = this._bbSize;
  21172. this._facetParameters.subDiv = this._subDiv;
  21173. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21174. this._facetParameters.depthSort = this._facetDepthSort;
  21175. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21176. this.computeWorldMatrix(true);
  21177. this._worldMatrix.invertToRef(this._invertedMatrix);
  21178. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21179. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21180. }
  21181. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21182. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21183. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21184. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21185. var l = (this._depthSortedIndices.length / 3) | 0;
  21186. for (var f = 0; f < l; f++) {
  21187. var sind = this._depthSortedFacets[f].ind;
  21188. this._depthSortedIndices[f * 3] = indices[sind];
  21189. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21190. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21191. }
  21192. this.updateIndices(this._depthSortedIndices);
  21193. }
  21194. return this;
  21195. };
  21196. /**
  21197. * Returns the facetLocalNormals array.
  21198. * The normals are expressed in the mesh local spac
  21199. * @returns an array of Vector3
  21200. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21201. */
  21202. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21203. if (!this._facetNormals) {
  21204. this.updateFacetData();
  21205. }
  21206. return this._facetNormals;
  21207. };
  21208. /**
  21209. * Returns the facetLocalPositions array.
  21210. * The facet positions are expressed in the mesh local space
  21211. * @returns an array of Vector3
  21212. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21213. */
  21214. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21215. if (!this._facetPositions) {
  21216. this.updateFacetData();
  21217. }
  21218. return this._facetPositions;
  21219. };
  21220. /**
  21221. * Returns the facetLocalPartioning array
  21222. * @returns an array of array of numbers
  21223. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21224. */
  21225. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21226. if (!this._facetPartitioning) {
  21227. this.updateFacetData();
  21228. }
  21229. return this._facetPartitioning;
  21230. };
  21231. /**
  21232. * Returns the i-th facet position in the world system.
  21233. * This method allocates a new Vector3 per call
  21234. * @param i defines the facet index
  21235. * @returns a new Vector3
  21236. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21237. */
  21238. AbstractMesh.prototype.getFacetPosition = function (i) {
  21239. var pos = BABYLON.Vector3.Zero();
  21240. this.getFacetPositionToRef(i, pos);
  21241. return pos;
  21242. };
  21243. /**
  21244. * Sets the reference Vector3 with the i-th facet position in the world system
  21245. * @param i defines the facet index
  21246. * @param ref defines the target vector
  21247. * @returns the current mesh
  21248. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21249. */
  21250. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21251. var localPos = (this.getFacetLocalPositions())[i];
  21252. var world = this.getWorldMatrix();
  21253. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21254. return this;
  21255. };
  21256. /**
  21257. * Returns the i-th facet normal in the world system.
  21258. * This method allocates a new Vector3 per call
  21259. * @param i defines the facet index
  21260. * @returns a new Vector3
  21261. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21262. */
  21263. AbstractMesh.prototype.getFacetNormal = function (i) {
  21264. var norm = BABYLON.Vector3.Zero();
  21265. this.getFacetNormalToRef(i, norm);
  21266. return norm;
  21267. };
  21268. /**
  21269. * Sets the reference Vector3 with the i-th facet normal in the world system
  21270. * @param i defines the facet index
  21271. * @param ref defines the target vector
  21272. * @returns the current mesh
  21273. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21274. */
  21275. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21276. var localNorm = (this.getFacetLocalNormals())[i];
  21277. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21278. return this;
  21279. };
  21280. /**
  21281. * 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)
  21282. * @param x defines x coordinate
  21283. * @param y defines y coordinate
  21284. * @param z defines z coordinate
  21285. * @returns the array of facet indexes
  21286. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21287. */
  21288. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21289. var bInfo = this.getBoundingInfo();
  21290. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21291. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21292. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21293. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21294. return null;
  21295. }
  21296. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21297. };
  21298. /**
  21299. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21300. * @param projected sets as the (x,y,z) world projection on the facet
  21301. * @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
  21302. * @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
  21303. * @param x defines x coordinate
  21304. * @param y defines y coordinate
  21305. * @param z defines z coordinate
  21306. * @returns the face index if found (or null instead)
  21307. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21308. */
  21309. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21310. if (checkFace === void 0) { checkFace = false; }
  21311. if (facing === void 0) { facing = true; }
  21312. var world = this.getWorldMatrix();
  21313. var invMat = BABYLON.Tmp.Matrix[5];
  21314. world.invertToRef(invMat);
  21315. var invVect = BABYLON.Tmp.Vector3[8];
  21316. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21317. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21318. if (projected) {
  21319. // tranform the local computed projected vector to world coordinates
  21320. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21321. }
  21322. return closest;
  21323. };
  21324. /**
  21325. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21326. * @param projected sets as the (x,y,z) local projection on the facet
  21327. * @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
  21328. * @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
  21329. * @param x defines x coordinate
  21330. * @param y defines y coordinate
  21331. * @param z defines z coordinate
  21332. * @returns the face index if found (or null instead)
  21333. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21334. */
  21335. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21336. if (checkFace === void 0) { checkFace = false; }
  21337. if (facing === void 0) { facing = true; }
  21338. var closest = null;
  21339. var tmpx = 0.0;
  21340. var tmpy = 0.0;
  21341. var tmpz = 0.0;
  21342. var d = 0.0; // tmp dot facet normal * facet position
  21343. var t0 = 0.0;
  21344. var projx = 0.0;
  21345. var projy = 0.0;
  21346. var projz = 0.0;
  21347. // Get all the facets in the same partitioning block than (x, y, z)
  21348. var facetPositions = this.getFacetLocalPositions();
  21349. var facetNormals = this.getFacetLocalNormals();
  21350. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21351. if (!facetsInBlock) {
  21352. return null;
  21353. }
  21354. // Get the closest facet to (x, y, z)
  21355. var shortest = Number.MAX_VALUE; // init distance vars
  21356. var tmpDistance = shortest;
  21357. var fib; // current facet in the block
  21358. var norm; // current facet normal
  21359. var p0; // current facet barycenter position
  21360. // loop on all the facets in the current partitioning block
  21361. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21362. fib = facetsInBlock[idx];
  21363. norm = facetNormals[fib];
  21364. p0 = facetPositions[fib];
  21365. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21366. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21367. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21368. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21369. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21370. projx = x + norm.x * t0;
  21371. projy = y + norm.y * t0;
  21372. projz = z + norm.z * t0;
  21373. tmpx = projx - x;
  21374. tmpy = projy - y;
  21375. tmpz = projz - z;
  21376. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21377. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21378. shortest = tmpDistance;
  21379. closest = fib;
  21380. if (projected) {
  21381. projected.x = projx;
  21382. projected.y = projy;
  21383. projected.z = projz;
  21384. }
  21385. }
  21386. }
  21387. }
  21388. return closest;
  21389. };
  21390. /**
  21391. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21392. * @returns the parameters
  21393. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21394. */
  21395. AbstractMesh.prototype.getFacetDataParameters = function () {
  21396. return this._facetParameters;
  21397. };
  21398. /**
  21399. * Disables the feature FacetData and frees the related memory
  21400. * @returns the current mesh
  21401. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21402. */
  21403. AbstractMesh.prototype.disableFacetData = function () {
  21404. if (this._facetDataEnabled) {
  21405. this._facetDataEnabled = false;
  21406. this._facetPositions = new Array();
  21407. this._facetNormals = new Array();
  21408. this._facetPartitioning = new Array();
  21409. this._facetParameters = null;
  21410. this._depthSortedIndices = new Uint32Array(0);
  21411. }
  21412. return this;
  21413. };
  21414. /**
  21415. * Updates the AbstractMesh indices array
  21416. * @param indices defines the data source
  21417. * @returns the current mesh
  21418. */
  21419. AbstractMesh.prototype.updateIndices = function (indices) {
  21420. return this;
  21421. };
  21422. /**
  21423. * Creates new normals data for the mesh
  21424. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21425. * @returns the current mesh
  21426. */
  21427. AbstractMesh.prototype.createNormals = function (updatable) {
  21428. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21429. var indices = this.getIndices();
  21430. var normals;
  21431. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21432. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21433. }
  21434. else {
  21435. normals = [];
  21436. }
  21437. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21438. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21439. return this;
  21440. };
  21441. /**
  21442. * Align the mesh with a normal
  21443. * @param normal defines the normal to use
  21444. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21445. * @returns the current mesh
  21446. */
  21447. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21448. if (!upDirection) {
  21449. upDirection = BABYLON.Axis.Y;
  21450. }
  21451. var axisX = BABYLON.Tmp.Vector3[0];
  21452. var axisZ = BABYLON.Tmp.Vector3[1];
  21453. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21454. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21455. if (this.rotationQuaternion) {
  21456. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21457. }
  21458. else {
  21459. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21460. }
  21461. return this;
  21462. };
  21463. /** @hidden */
  21464. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21465. var engine = this.getEngine();
  21466. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21467. this._isOccluded = false;
  21468. return;
  21469. }
  21470. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21471. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21472. if (isOcclusionQueryAvailable) {
  21473. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21474. this._isOcclusionQueryInProgress = false;
  21475. this._occlusionInternalRetryCounter = 0;
  21476. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21477. }
  21478. else {
  21479. this._occlusionInternalRetryCounter++;
  21480. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21481. this._isOcclusionQueryInProgress = false;
  21482. this._occlusionInternalRetryCounter = 0;
  21483. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21484. // if strict continue the last state of the object.
  21485. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21486. }
  21487. else {
  21488. return;
  21489. }
  21490. }
  21491. }
  21492. var scene = this.getScene();
  21493. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21494. if (!this._occlusionQuery) {
  21495. this._occlusionQuery = engine.createQuery();
  21496. }
  21497. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21498. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21499. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21500. this._isOcclusionQueryInProgress = true;
  21501. };
  21502. /** No occlusion */
  21503. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21504. /** Occlusion set to optimisitic */
  21505. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21506. /** Occlusion set to strict */
  21507. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21508. /** Use an accurante occlusion algorithm */
  21509. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21510. /** Use a conservative occlusion algorithm */
  21511. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21512. return AbstractMesh;
  21513. }(BABYLON.TransformNode));
  21514. BABYLON.AbstractMesh = AbstractMesh;
  21515. })(BABYLON || (BABYLON = {}));
  21516. //# sourceMappingURL=babylon.abstractMesh.js.map
  21517. var BABYLON;
  21518. (function (BABYLON) {
  21519. /**
  21520. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21521. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21522. * 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.
  21523. */
  21524. var Light = /** @class */ (function (_super) {
  21525. __extends(Light, _super);
  21526. /**
  21527. * Creates a Light object in the scene.
  21528. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21529. * @param name The firendly name of the light
  21530. * @param scene The scene the light belongs too
  21531. */
  21532. function Light(name, scene) {
  21533. var _this = _super.call(this, name, scene) || this;
  21534. /**
  21535. * Diffuse gives the basic color to an object.
  21536. */
  21537. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21538. /**
  21539. * Specular produces a highlight color on an object.
  21540. * Note: This is note affecting PBR materials.
  21541. */
  21542. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21543. /**
  21544. * Strength of the light.
  21545. * Note: By default it is define in the framework own unit.
  21546. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21547. */
  21548. _this.intensity = 1.0;
  21549. /**
  21550. * Defines how far from the source the light is impacting in scene units.
  21551. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21552. */
  21553. _this.range = Number.MAX_VALUE;
  21554. /**
  21555. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21556. * of light.
  21557. */
  21558. _this._photometricScale = 1.0;
  21559. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21560. _this._radius = 0.00001;
  21561. /**
  21562. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21563. * exceeding the number allowed of the materials.
  21564. */
  21565. _this.renderPriority = 0;
  21566. _this._shadowEnabled = true;
  21567. _this._excludeWithLayerMask = 0;
  21568. _this._includeOnlyWithLayerMask = 0;
  21569. _this._lightmapMode = 0;
  21570. /**
  21571. * @hidden Internal use only.
  21572. */
  21573. _this._excludedMeshesIds = new Array();
  21574. /**
  21575. * @hidden Internal use only.
  21576. */
  21577. _this._includedOnlyMeshesIds = new Array();
  21578. _this.getScene().addLight(_this);
  21579. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21580. _this._buildUniformLayout();
  21581. _this.includedOnlyMeshes = new Array();
  21582. _this.excludedMeshes = new Array();
  21583. _this._resyncMeshes();
  21584. return _this;
  21585. }
  21586. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21587. /**
  21588. * If every light affecting the material is in this lightmapMode,
  21589. * material.lightmapTexture adds or multiplies
  21590. * (depends on material.useLightmapAsShadowmap)
  21591. * after every other light calculations.
  21592. */
  21593. get: function () {
  21594. return Light._LIGHTMAP_DEFAULT;
  21595. },
  21596. enumerable: true,
  21597. configurable: true
  21598. });
  21599. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21600. /**
  21601. * material.lightmapTexture as only diffuse lighting from this light
  21602. * adds only specular lighting from this light
  21603. * adds dynamic shadows
  21604. */
  21605. get: function () {
  21606. return Light._LIGHTMAP_SPECULAR;
  21607. },
  21608. enumerable: true,
  21609. configurable: true
  21610. });
  21611. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21612. /**
  21613. * material.lightmapTexture as only lighting
  21614. * no light calculation from this light
  21615. * only adds dynamic shadows from this light
  21616. */
  21617. get: function () {
  21618. return Light._LIGHTMAP_SHADOWSONLY;
  21619. },
  21620. enumerable: true,
  21621. configurable: true
  21622. });
  21623. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21624. /**
  21625. * Each light type uses the default quantity according to its type:
  21626. * point/spot lights use luminous intensity
  21627. * directional lights use illuminance
  21628. */
  21629. get: function () {
  21630. return Light._INTENSITYMODE_AUTOMATIC;
  21631. },
  21632. enumerable: true,
  21633. configurable: true
  21634. });
  21635. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21636. /**
  21637. * lumen (lm)
  21638. */
  21639. get: function () {
  21640. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21646. /**
  21647. * candela (lm/sr)
  21648. */
  21649. get: function () {
  21650. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21656. /**
  21657. * lux (lm/m^2)
  21658. */
  21659. get: function () {
  21660. return Light._INTENSITYMODE_ILLUMINANCE;
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21666. /**
  21667. * nit (cd/m^2)
  21668. */
  21669. get: function () {
  21670. return Light._INTENSITYMODE_LUMINANCE;
  21671. },
  21672. enumerable: true,
  21673. configurable: true
  21674. });
  21675. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21676. /**
  21677. * Light type const id of the point light.
  21678. */
  21679. get: function () {
  21680. return Light._LIGHTTYPEID_POINTLIGHT;
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21686. /**
  21687. * Light type const id of the directional light.
  21688. */
  21689. get: function () {
  21690. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21696. /**
  21697. * Light type const id of the spot light.
  21698. */
  21699. get: function () {
  21700. return Light._LIGHTTYPEID_SPOTLIGHT;
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21706. /**
  21707. * Light type const id of the hemispheric light.
  21708. */
  21709. get: function () {
  21710. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21711. },
  21712. enumerable: true,
  21713. configurable: true
  21714. });
  21715. Object.defineProperty(Light.prototype, "intensityMode", {
  21716. /**
  21717. * Gets the photometric scale used to interpret the intensity.
  21718. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21719. */
  21720. get: function () {
  21721. return this._intensityMode;
  21722. },
  21723. /**
  21724. * Sets the photometric scale used to interpret the intensity.
  21725. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21726. */
  21727. set: function (value) {
  21728. this._intensityMode = value;
  21729. this._computePhotometricScale();
  21730. },
  21731. enumerable: true,
  21732. configurable: true
  21733. });
  21734. ;
  21735. ;
  21736. Object.defineProperty(Light.prototype, "radius", {
  21737. /**
  21738. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21739. */
  21740. get: function () {
  21741. return this._radius;
  21742. },
  21743. /**
  21744. * sets the light radius used by PBR Materials to simulate soft area lights.
  21745. */
  21746. set: function (value) {
  21747. this._radius = value;
  21748. this._computePhotometricScale();
  21749. },
  21750. enumerable: true,
  21751. configurable: true
  21752. });
  21753. ;
  21754. ;
  21755. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21756. /**
  21757. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21758. * the current shadow generator.
  21759. */
  21760. get: function () {
  21761. return this._shadowEnabled;
  21762. },
  21763. /**
  21764. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21765. * the current shadow generator.
  21766. */
  21767. set: function (value) {
  21768. if (this._shadowEnabled === value) {
  21769. return;
  21770. }
  21771. this._shadowEnabled = value;
  21772. this._markMeshesAsLightDirty();
  21773. },
  21774. enumerable: true,
  21775. configurable: true
  21776. });
  21777. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21778. /**
  21779. * Gets the only meshes impacted by this light.
  21780. */
  21781. get: function () {
  21782. return this._includedOnlyMeshes;
  21783. },
  21784. /**
  21785. * Sets the only meshes impacted by this light.
  21786. */
  21787. set: function (value) {
  21788. this._includedOnlyMeshes = value;
  21789. this._hookArrayForIncludedOnly(value);
  21790. },
  21791. enumerable: true,
  21792. configurable: true
  21793. });
  21794. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21795. /**
  21796. * Gets the meshes not impacted by this light.
  21797. */
  21798. get: function () {
  21799. return this._excludedMeshes;
  21800. },
  21801. /**
  21802. * Sets the meshes not impacted by this light.
  21803. */
  21804. set: function (value) {
  21805. this._excludedMeshes = value;
  21806. this._hookArrayForExcluded(value);
  21807. },
  21808. enumerable: true,
  21809. configurable: true
  21810. });
  21811. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21812. /**
  21813. * Gets the layer id use to find what meshes are not impacted by the light.
  21814. * Inactive if 0
  21815. */
  21816. get: function () {
  21817. return this._excludeWithLayerMask;
  21818. },
  21819. /**
  21820. * Sets the layer id use to find what meshes are not impacted by the light.
  21821. * Inactive if 0
  21822. */
  21823. set: function (value) {
  21824. this._excludeWithLayerMask = value;
  21825. this._resyncMeshes();
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21831. /**
  21832. * Gets the layer id use to find what meshes are impacted by the light.
  21833. * Inactive if 0
  21834. */
  21835. get: function () {
  21836. return this._includeOnlyWithLayerMask;
  21837. },
  21838. /**
  21839. * Sets the layer id use to find what meshes are impacted by the light.
  21840. * Inactive if 0
  21841. */
  21842. set: function (value) {
  21843. this._includeOnlyWithLayerMask = value;
  21844. this._resyncMeshes();
  21845. },
  21846. enumerable: true,
  21847. configurable: true
  21848. });
  21849. Object.defineProperty(Light.prototype, "lightmapMode", {
  21850. /**
  21851. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21852. */
  21853. get: function () {
  21854. return this._lightmapMode;
  21855. },
  21856. /**
  21857. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21858. */
  21859. set: function (value) {
  21860. if (this._lightmapMode === value) {
  21861. return;
  21862. }
  21863. this._lightmapMode = value;
  21864. this._markMeshesAsLightDirty();
  21865. },
  21866. enumerable: true,
  21867. configurable: true
  21868. });
  21869. /**
  21870. * Returns the string "Light".
  21871. * @returns the class name
  21872. */
  21873. Light.prototype.getClassName = function () {
  21874. return "Light";
  21875. };
  21876. /**
  21877. * Converts the light information to a readable string for debug purpose.
  21878. * @param fullDetails Supports for multiple levels of logging within scene loading
  21879. * @returns the human readable light info
  21880. */
  21881. Light.prototype.toString = function (fullDetails) {
  21882. var ret = "Name: " + this.name;
  21883. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21884. if (this.animations) {
  21885. for (var i = 0; i < this.animations.length; i++) {
  21886. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21887. }
  21888. }
  21889. if (fullDetails) {
  21890. }
  21891. return ret;
  21892. };
  21893. /**
  21894. * Set the enabled state of this node.
  21895. * @param value - the new enabled state
  21896. */
  21897. Light.prototype.setEnabled = function (value) {
  21898. _super.prototype.setEnabled.call(this, value);
  21899. this._resyncMeshes();
  21900. };
  21901. /**
  21902. * Returns the Light associated shadow generator if any.
  21903. * @return the associated shadow generator.
  21904. */
  21905. Light.prototype.getShadowGenerator = function () {
  21906. return this._shadowGenerator;
  21907. };
  21908. /**
  21909. * Returns a Vector3, the absolute light position in the World.
  21910. * @returns the world space position of the light
  21911. */
  21912. Light.prototype.getAbsolutePosition = function () {
  21913. return BABYLON.Vector3.Zero();
  21914. };
  21915. /**
  21916. * Specifies if the light will affect the passed mesh.
  21917. * @param mesh The mesh to test against the light
  21918. * @return true the mesh is affected otherwise, false.
  21919. */
  21920. Light.prototype.canAffectMesh = function (mesh) {
  21921. if (!mesh) {
  21922. return true;
  21923. }
  21924. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21925. return false;
  21926. }
  21927. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21928. return false;
  21929. }
  21930. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21931. return false;
  21932. }
  21933. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21934. return false;
  21935. }
  21936. return true;
  21937. };
  21938. /**
  21939. * Computes and Returns the light World matrix.
  21940. * @returns the world matrix
  21941. */
  21942. Light.prototype.getWorldMatrix = function () {
  21943. this._currentRenderId = this.getScene().getRenderId();
  21944. this._childRenderId = this._currentRenderId;
  21945. var worldMatrix = this._getWorldMatrix();
  21946. if (this.parent && this.parent.getWorldMatrix) {
  21947. if (!this._parentedWorldMatrix) {
  21948. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21949. }
  21950. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21951. this._markSyncedWithParent();
  21952. return this._parentedWorldMatrix;
  21953. }
  21954. return worldMatrix;
  21955. };
  21956. /**
  21957. * Sort function to order lights for rendering.
  21958. * @param a First Light object to compare to second.
  21959. * @param b Second Light object to compare first.
  21960. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21961. */
  21962. Light.CompareLightsPriority = function (a, b) {
  21963. //shadow-casting lights have priority over non-shadow-casting lights
  21964. //the renderPrioirty is a secondary sort criterion
  21965. if (a.shadowEnabled !== b.shadowEnabled) {
  21966. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21967. }
  21968. return b.renderPriority - a.renderPriority;
  21969. };
  21970. /**
  21971. * Releases resources associated with this node.
  21972. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21973. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21974. */
  21975. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21976. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21977. if (this._shadowGenerator) {
  21978. this._shadowGenerator.dispose();
  21979. this._shadowGenerator = null;
  21980. }
  21981. // Animations
  21982. this.getScene().stopAnimation(this);
  21983. // Remove from meshes
  21984. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21985. var mesh = _a[_i];
  21986. mesh._removeLightSource(this);
  21987. }
  21988. this._uniformBuffer.dispose();
  21989. // Remove from scene
  21990. this.getScene().removeLight(this);
  21991. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21992. };
  21993. /**
  21994. * Returns the light type ID (integer).
  21995. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21996. */
  21997. Light.prototype.getTypeID = function () {
  21998. return 0;
  21999. };
  22000. /**
  22001. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22002. * @returns the scaled intensity in intensity mode unit
  22003. */
  22004. Light.prototype.getScaledIntensity = function () {
  22005. return this._photometricScale * this.intensity;
  22006. };
  22007. /**
  22008. * Returns a new Light object, named "name", from the current one.
  22009. * @param name The name of the cloned light
  22010. * @returns the new created light
  22011. */
  22012. Light.prototype.clone = function (name) {
  22013. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22014. if (!constructor) {
  22015. return null;
  22016. }
  22017. return BABYLON.SerializationHelper.Clone(constructor, this);
  22018. };
  22019. /**
  22020. * Serializes the current light into a Serialization object.
  22021. * @returns the serialized object.
  22022. */
  22023. Light.prototype.serialize = function () {
  22024. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22025. // Type
  22026. serializationObject.type = this.getTypeID();
  22027. // Parent
  22028. if (this.parent) {
  22029. serializationObject.parentId = this.parent.id;
  22030. }
  22031. // Inclusion / exclusions
  22032. if (this.excludedMeshes.length > 0) {
  22033. serializationObject.excludedMeshesIds = [];
  22034. this.excludedMeshes.forEach(function (mesh) {
  22035. serializationObject.excludedMeshesIds.push(mesh.id);
  22036. });
  22037. }
  22038. if (this.includedOnlyMeshes.length > 0) {
  22039. serializationObject.includedOnlyMeshesIds = [];
  22040. this.includedOnlyMeshes.forEach(function (mesh) {
  22041. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22042. });
  22043. }
  22044. // Animations
  22045. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22046. serializationObject.ranges = this.serializeAnimationRanges();
  22047. return serializationObject;
  22048. };
  22049. /**
  22050. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22051. * This new light is named "name" and added to the passed scene.
  22052. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22053. * @param name The friendly name of the light
  22054. * @param scene The scene the new light will belong to
  22055. * @returns the constructor function
  22056. */
  22057. Light.GetConstructorFromName = function (type, name, scene) {
  22058. switch (type) {
  22059. case 0:
  22060. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22061. case 1:
  22062. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22063. case 2:
  22064. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22065. case 3:
  22066. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22067. }
  22068. return null;
  22069. };
  22070. /**
  22071. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22072. * @param parsedLight The JSON representation of the light
  22073. * @param scene The scene to create the parsed light in
  22074. * @returns the created light after parsing
  22075. */
  22076. Light.Parse = function (parsedLight, scene) {
  22077. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22078. if (!constructor) {
  22079. return null;
  22080. }
  22081. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22082. // Inclusion / exclusions
  22083. if (parsedLight.excludedMeshesIds) {
  22084. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22085. }
  22086. if (parsedLight.includedOnlyMeshesIds) {
  22087. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22088. }
  22089. // Parent
  22090. if (parsedLight.parentId) {
  22091. light._waitingParentId = parsedLight.parentId;
  22092. }
  22093. // Animations
  22094. if (parsedLight.animations) {
  22095. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22096. var parsedAnimation = parsedLight.animations[animationIndex];
  22097. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22098. }
  22099. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22100. }
  22101. if (parsedLight.autoAnimate) {
  22102. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22103. }
  22104. return light;
  22105. };
  22106. Light.prototype._hookArrayForExcluded = function (array) {
  22107. var _this = this;
  22108. var oldPush = array.push;
  22109. array.push = function () {
  22110. var items = [];
  22111. for (var _i = 0; _i < arguments.length; _i++) {
  22112. items[_i] = arguments[_i];
  22113. }
  22114. var result = oldPush.apply(array, items);
  22115. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22116. var item = items_1[_a];
  22117. item._resyncLighSource(_this);
  22118. }
  22119. return result;
  22120. };
  22121. var oldSplice = array.splice;
  22122. array.splice = function (index, deleteCount) {
  22123. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22124. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22125. var item = deleted_1[_i];
  22126. item._resyncLighSource(_this);
  22127. }
  22128. return deleted;
  22129. };
  22130. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22131. var item = array_1[_i];
  22132. item._resyncLighSource(this);
  22133. }
  22134. };
  22135. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22136. var _this = this;
  22137. var oldPush = array.push;
  22138. array.push = function () {
  22139. var items = [];
  22140. for (var _i = 0; _i < arguments.length; _i++) {
  22141. items[_i] = arguments[_i];
  22142. }
  22143. var result = oldPush.apply(array, items);
  22144. _this._resyncMeshes();
  22145. return result;
  22146. };
  22147. var oldSplice = array.splice;
  22148. array.splice = function (index, deleteCount) {
  22149. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22150. _this._resyncMeshes();
  22151. return deleted;
  22152. };
  22153. this._resyncMeshes();
  22154. };
  22155. Light.prototype._resyncMeshes = function () {
  22156. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22157. var mesh = _a[_i];
  22158. mesh._resyncLighSource(this);
  22159. }
  22160. };
  22161. /**
  22162. * Forces the meshes to update their light related information in their rendering used effects
  22163. * @hidden Internal Use Only
  22164. */
  22165. Light.prototype._markMeshesAsLightDirty = function () {
  22166. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22167. var mesh = _a[_i];
  22168. if (mesh._lightSources.indexOf(this) !== -1) {
  22169. mesh._markSubMeshesAsLightDirty();
  22170. }
  22171. }
  22172. };
  22173. /**
  22174. * Recomputes the cached photometric scale if needed.
  22175. */
  22176. Light.prototype._computePhotometricScale = function () {
  22177. this._photometricScale = this._getPhotometricScale();
  22178. this.getScene().resetCachedMaterial();
  22179. };
  22180. /**
  22181. * Returns the Photometric Scale according to the light type and intensity mode.
  22182. */
  22183. Light.prototype._getPhotometricScale = function () {
  22184. var photometricScale = 0.0;
  22185. var lightTypeID = this.getTypeID();
  22186. //get photometric mode
  22187. var photometricMode = this.intensityMode;
  22188. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22189. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22190. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22191. }
  22192. else {
  22193. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22194. }
  22195. }
  22196. //compute photometric scale
  22197. switch (lightTypeID) {
  22198. case Light.LIGHTTYPEID_POINTLIGHT:
  22199. case Light.LIGHTTYPEID_SPOTLIGHT:
  22200. switch (photometricMode) {
  22201. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22202. photometricScale = 1.0 / (4.0 * Math.PI);
  22203. break;
  22204. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22205. photometricScale = 1.0;
  22206. break;
  22207. case Light.INTENSITYMODE_LUMINANCE:
  22208. photometricScale = this.radius * this.radius;
  22209. break;
  22210. }
  22211. break;
  22212. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22213. switch (photometricMode) {
  22214. case Light.INTENSITYMODE_ILLUMINANCE:
  22215. photometricScale = 1.0;
  22216. break;
  22217. case Light.INTENSITYMODE_LUMINANCE:
  22218. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22219. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22220. var apexAngleRadians = this.radius;
  22221. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22222. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22223. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22224. photometricScale = solidAngle;
  22225. break;
  22226. }
  22227. break;
  22228. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22229. // No fall off in hemisperic light.
  22230. photometricScale = 1.0;
  22231. break;
  22232. }
  22233. return photometricScale;
  22234. };
  22235. /**
  22236. * Reorder the light in the scene according to their defined priority.
  22237. * @hidden Internal Use Only
  22238. */
  22239. Light.prototype._reorderLightsInScene = function () {
  22240. var scene = this.getScene();
  22241. if (this._renderPriority != 0) {
  22242. scene.requireLightSorting = true;
  22243. }
  22244. this.getScene().sortLightsByPriority();
  22245. };
  22246. //lightmapMode Consts
  22247. Light._LIGHTMAP_DEFAULT = 0;
  22248. Light._LIGHTMAP_SPECULAR = 1;
  22249. Light._LIGHTMAP_SHADOWSONLY = 2;
  22250. // Intensity Mode Consts
  22251. Light._INTENSITYMODE_AUTOMATIC = 0;
  22252. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22253. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22254. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22255. Light._INTENSITYMODE_LUMINANCE = 4;
  22256. // Light types ids const.
  22257. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22258. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22259. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22260. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22261. __decorate([
  22262. BABYLON.serializeAsColor3()
  22263. ], Light.prototype, "diffuse", void 0);
  22264. __decorate([
  22265. BABYLON.serializeAsColor3()
  22266. ], Light.prototype, "specular", void 0);
  22267. __decorate([
  22268. BABYLON.serialize()
  22269. ], Light.prototype, "intensity", void 0);
  22270. __decorate([
  22271. BABYLON.serialize()
  22272. ], Light.prototype, "range", void 0);
  22273. __decorate([
  22274. BABYLON.serialize()
  22275. ], Light.prototype, "intensityMode", null);
  22276. __decorate([
  22277. BABYLON.serialize()
  22278. ], Light.prototype, "radius", null);
  22279. __decorate([
  22280. BABYLON.serialize()
  22281. ], Light.prototype, "_renderPriority", void 0);
  22282. __decorate([
  22283. BABYLON.expandToProperty("_reorderLightsInScene")
  22284. ], Light.prototype, "renderPriority", void 0);
  22285. __decorate([
  22286. BABYLON.serialize("shadowEnabled")
  22287. ], Light.prototype, "_shadowEnabled", void 0);
  22288. __decorate([
  22289. BABYLON.serialize("excludeWithLayerMask")
  22290. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22291. __decorate([
  22292. BABYLON.serialize("includeOnlyWithLayerMask")
  22293. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22294. __decorate([
  22295. BABYLON.serialize("lightmapMode")
  22296. ], Light.prototype, "_lightmapMode", void 0);
  22297. return Light;
  22298. }(BABYLON.Node));
  22299. BABYLON.Light = Light;
  22300. })(BABYLON || (BABYLON = {}));
  22301. //# sourceMappingURL=babylon.light.js.map
  22302. var BABYLON;
  22303. (function (BABYLON) {
  22304. var Camera = /** @class */ (function (_super) {
  22305. __extends(Camera, _super);
  22306. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22307. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22308. var _this = _super.call(this, name, scene) || this;
  22309. /**
  22310. * The vector the camera should consider as up.
  22311. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22312. */
  22313. _this.upVector = BABYLON.Vector3.Up();
  22314. _this.orthoLeft = null;
  22315. _this.orthoRight = null;
  22316. _this.orthoBottom = null;
  22317. _this.orthoTop = null;
  22318. /**
  22319. * FOV is set in Radians. (default is 0.8)
  22320. */
  22321. _this.fov = 0.8;
  22322. _this.minZ = 1;
  22323. _this.maxZ = 10000.0;
  22324. _this.inertia = 0.9;
  22325. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22326. _this.isIntermediate = false;
  22327. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22328. /**
  22329. * Restricts the camera to viewing objects with the same layerMask.
  22330. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22331. */
  22332. _this.layerMask = 0x0FFFFFFF;
  22333. /**
  22334. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22335. */
  22336. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22337. // Camera rig members
  22338. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22339. _this._rigCameras = new Array();
  22340. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22341. _this._skipRendering = false;
  22342. _this.customRenderTargets = new Array();
  22343. // Observables
  22344. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22345. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22346. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22347. _this.onRestoreStateObservable = new BABYLON.Observable();
  22348. // Cache
  22349. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22350. _this._projectionMatrix = new BABYLON.Matrix();
  22351. _this._doNotComputeProjectionMatrix = false;
  22352. _this._worldMatrix = BABYLON.Matrix.Identity();
  22353. _this._postProcesses = new Array();
  22354. _this._transformMatrix = BABYLON.Matrix.Zero();
  22355. _this._activeMeshes = new BABYLON.SmartArray(256);
  22356. _this._globalPosition = BABYLON.Vector3.Zero();
  22357. _this._refreshFrustumPlanes = true;
  22358. _this.getScene().addCamera(_this);
  22359. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22360. _this.getScene().activeCamera = _this;
  22361. }
  22362. _this.position = position;
  22363. return _this;
  22364. }
  22365. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22366. get: function () {
  22367. return Camera._PERSPECTIVE_CAMERA;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22373. get: function () {
  22374. return Camera._ORTHOGRAPHIC_CAMERA;
  22375. },
  22376. enumerable: true,
  22377. configurable: true
  22378. });
  22379. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22380. /**
  22381. * This is the default FOV mode for perspective cameras.
  22382. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22383. *
  22384. */
  22385. get: function () {
  22386. return Camera._FOVMODE_VERTICAL_FIXED;
  22387. },
  22388. enumerable: true,
  22389. configurable: true
  22390. });
  22391. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22392. /**
  22393. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22394. *
  22395. */
  22396. get: function () {
  22397. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22398. },
  22399. enumerable: true,
  22400. configurable: true
  22401. });
  22402. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22403. get: function () {
  22404. return Camera._RIG_MODE_NONE;
  22405. },
  22406. enumerable: true,
  22407. configurable: true
  22408. });
  22409. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22410. get: function () {
  22411. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22412. },
  22413. enumerable: true,
  22414. configurable: true
  22415. });
  22416. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22417. get: function () {
  22418. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22424. get: function () {
  22425. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22431. get: function () {
  22432. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22433. },
  22434. enumerable: true,
  22435. configurable: true
  22436. });
  22437. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22438. get: function () {
  22439. return Camera._RIG_MODE_VR;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22445. get: function () {
  22446. return Camera._RIG_MODE_WEBVR;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. /**
  22452. * Store current camera state (fov, position, etc..)
  22453. */
  22454. Camera.prototype.storeState = function () {
  22455. this._stateStored = true;
  22456. this._storedFov = this.fov;
  22457. return this;
  22458. };
  22459. /**
  22460. * Restores the camera state values if it has been stored. You must call storeState() first
  22461. */
  22462. Camera.prototype._restoreStateValues = function () {
  22463. if (!this._stateStored) {
  22464. return false;
  22465. }
  22466. this.fov = this._storedFov;
  22467. return true;
  22468. };
  22469. /**
  22470. * Restored camera state. You must call storeState() first
  22471. */
  22472. Camera.prototype.restoreState = function () {
  22473. if (this._restoreStateValues()) {
  22474. this.onRestoreStateObservable.notifyObservers(this);
  22475. return true;
  22476. }
  22477. return false;
  22478. };
  22479. Camera.prototype.getClassName = function () {
  22480. return "Camera";
  22481. };
  22482. /**
  22483. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22484. */
  22485. Camera.prototype.toString = function (fullDetails) {
  22486. var ret = "Name: " + this.name;
  22487. ret += ", type: " + this.getClassName();
  22488. if (this.animations) {
  22489. for (var i = 0; i < this.animations.length; i++) {
  22490. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22491. }
  22492. }
  22493. if (fullDetails) {
  22494. }
  22495. return ret;
  22496. };
  22497. Object.defineProperty(Camera.prototype, "globalPosition", {
  22498. get: function () {
  22499. return this._globalPosition;
  22500. },
  22501. enumerable: true,
  22502. configurable: true
  22503. });
  22504. Camera.prototype.getActiveMeshes = function () {
  22505. return this._activeMeshes;
  22506. };
  22507. Camera.prototype.isActiveMesh = function (mesh) {
  22508. return (this._activeMeshes.indexOf(mesh) !== -1);
  22509. };
  22510. /**
  22511. * Is this camera ready to be used/rendered
  22512. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22513. * @return true if the camera is ready
  22514. */
  22515. Camera.prototype.isReady = function (completeCheck) {
  22516. if (completeCheck === void 0) { completeCheck = false; }
  22517. if (completeCheck) {
  22518. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22519. var pp = _a[_i];
  22520. if (pp && !pp.isReady()) {
  22521. return false;
  22522. }
  22523. }
  22524. }
  22525. return _super.prototype.isReady.call(this, completeCheck);
  22526. };
  22527. //Cache
  22528. Camera.prototype._initCache = function () {
  22529. _super.prototype._initCache.call(this);
  22530. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22531. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22532. this._cache.mode = undefined;
  22533. this._cache.minZ = undefined;
  22534. this._cache.maxZ = undefined;
  22535. this._cache.fov = undefined;
  22536. this._cache.fovMode = undefined;
  22537. this._cache.aspectRatio = undefined;
  22538. this._cache.orthoLeft = undefined;
  22539. this._cache.orthoRight = undefined;
  22540. this._cache.orthoBottom = undefined;
  22541. this._cache.orthoTop = undefined;
  22542. this._cache.renderWidth = undefined;
  22543. this._cache.renderHeight = undefined;
  22544. };
  22545. Camera.prototype._updateCache = function (ignoreParentClass) {
  22546. if (!ignoreParentClass) {
  22547. _super.prototype._updateCache.call(this);
  22548. }
  22549. this._cache.position.copyFrom(this.position);
  22550. this._cache.upVector.copyFrom(this.upVector);
  22551. };
  22552. // Synchronized
  22553. Camera.prototype._isSynchronized = function () {
  22554. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22555. };
  22556. Camera.prototype._isSynchronizedViewMatrix = function () {
  22557. if (!_super.prototype._isSynchronized.call(this))
  22558. return false;
  22559. return this._cache.position.equals(this.position)
  22560. && this._cache.upVector.equals(this.upVector)
  22561. && this.isSynchronizedWithParent();
  22562. };
  22563. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22564. var check = this._cache.mode === this.mode
  22565. && this._cache.minZ === this.minZ
  22566. && this._cache.maxZ === this.maxZ;
  22567. if (!check) {
  22568. return false;
  22569. }
  22570. var engine = this.getEngine();
  22571. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22572. check = this._cache.fov === this.fov
  22573. && this._cache.fovMode === this.fovMode
  22574. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22575. }
  22576. else {
  22577. check = this._cache.orthoLeft === this.orthoLeft
  22578. && this._cache.orthoRight === this.orthoRight
  22579. && this._cache.orthoBottom === this.orthoBottom
  22580. && this._cache.orthoTop === this.orthoTop
  22581. && this._cache.renderWidth === engine.getRenderWidth()
  22582. && this._cache.renderHeight === engine.getRenderHeight();
  22583. }
  22584. return check;
  22585. };
  22586. // Controls
  22587. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22588. };
  22589. Camera.prototype.detachControl = function (element) {
  22590. };
  22591. Camera.prototype.update = function () {
  22592. this._checkInputs();
  22593. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22594. this._updateRigCameras();
  22595. }
  22596. };
  22597. Camera.prototype._checkInputs = function () {
  22598. this.onAfterCheckInputsObservable.notifyObservers(this);
  22599. };
  22600. Object.defineProperty(Camera.prototype, "rigCameras", {
  22601. get: function () {
  22602. return this._rigCameras;
  22603. },
  22604. enumerable: true,
  22605. configurable: true
  22606. });
  22607. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22608. get: function () {
  22609. return this._rigPostProcess;
  22610. },
  22611. enumerable: true,
  22612. configurable: true
  22613. });
  22614. /**
  22615. * Internal, gets the first post proces.
  22616. * @returns the first post process to be run on this camera.
  22617. */
  22618. Camera.prototype._getFirstPostProcess = function () {
  22619. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22620. if (this._postProcesses[ppIndex] !== null) {
  22621. return this._postProcesses[ppIndex];
  22622. }
  22623. }
  22624. return null;
  22625. };
  22626. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22627. // invalidate framebuffer
  22628. var firstPostProcess = this._getFirstPostProcess();
  22629. if (firstPostProcess) {
  22630. firstPostProcess.markTextureDirty();
  22631. }
  22632. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22633. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22634. var cam = this._rigCameras[i];
  22635. var rigPostProcess = cam._rigPostProcess;
  22636. // for VR rig, there does not have to be a post process
  22637. if (rigPostProcess) {
  22638. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22639. if (isPass) {
  22640. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22641. cam.isIntermediate = this._postProcesses.length === 0;
  22642. }
  22643. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22644. rigPostProcess.markTextureDirty();
  22645. }
  22646. else {
  22647. cam._postProcesses = this._postProcesses.slice(0);
  22648. }
  22649. }
  22650. };
  22651. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22652. if (insertAt === void 0) { insertAt = null; }
  22653. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22654. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22655. return 0;
  22656. }
  22657. if (insertAt == null || insertAt < 0) {
  22658. this._postProcesses.push(postProcess);
  22659. }
  22660. else if (this._postProcesses[insertAt] === null) {
  22661. this._postProcesses[insertAt] = postProcess;
  22662. }
  22663. else {
  22664. this._postProcesses.splice(insertAt, 0, postProcess);
  22665. }
  22666. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22667. return this._postProcesses.indexOf(postProcess);
  22668. };
  22669. Camera.prototype.detachPostProcess = function (postProcess) {
  22670. var idx = this._postProcesses.indexOf(postProcess);
  22671. if (idx !== -1) {
  22672. this._postProcesses[idx] = null;
  22673. }
  22674. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22675. };
  22676. Camera.prototype.getWorldMatrix = function () {
  22677. if (this._isSynchronizedViewMatrix()) {
  22678. return this._worldMatrix;
  22679. }
  22680. // Getting the the view matrix will also compute the world matrix.
  22681. this.getViewMatrix();
  22682. return this._worldMatrix;
  22683. };
  22684. Camera.prototype._getViewMatrix = function () {
  22685. return BABYLON.Matrix.Identity();
  22686. };
  22687. Camera.prototype.getViewMatrix = function (force) {
  22688. if (!force && this._isSynchronizedViewMatrix()) {
  22689. return this._computedViewMatrix;
  22690. }
  22691. this.updateCache();
  22692. this._computedViewMatrix = this._getViewMatrix();
  22693. this._currentRenderId = this.getScene().getRenderId();
  22694. this._childRenderId = this._currentRenderId;
  22695. this._refreshFrustumPlanes = true;
  22696. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22697. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22698. }
  22699. this.onViewMatrixChangedObservable.notifyObservers(this);
  22700. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22701. return this._computedViewMatrix;
  22702. };
  22703. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22704. this._doNotComputeProjectionMatrix = true;
  22705. if (projection !== undefined) {
  22706. this._projectionMatrix = projection;
  22707. }
  22708. };
  22709. ;
  22710. Camera.prototype.unfreezeProjectionMatrix = function () {
  22711. this._doNotComputeProjectionMatrix = false;
  22712. };
  22713. ;
  22714. Camera.prototype.getProjectionMatrix = function (force) {
  22715. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22716. return this._projectionMatrix;
  22717. }
  22718. // Cache
  22719. this._cache.mode = this.mode;
  22720. this._cache.minZ = this.minZ;
  22721. this._cache.maxZ = this.maxZ;
  22722. // Matrix
  22723. this._refreshFrustumPlanes = true;
  22724. var engine = this.getEngine();
  22725. var scene = this.getScene();
  22726. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22727. this._cache.fov = this.fov;
  22728. this._cache.fovMode = this.fovMode;
  22729. this._cache.aspectRatio = engine.getAspectRatio(this);
  22730. if (this.minZ <= 0) {
  22731. this.minZ = 0.1;
  22732. }
  22733. if (scene.useRightHandedSystem) {
  22734. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22735. }
  22736. else {
  22737. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22738. }
  22739. }
  22740. else {
  22741. var halfWidth = engine.getRenderWidth() / 2.0;
  22742. var halfHeight = engine.getRenderHeight() / 2.0;
  22743. if (scene.useRightHandedSystem) {
  22744. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22745. }
  22746. else {
  22747. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22748. }
  22749. this._cache.orthoLeft = this.orthoLeft;
  22750. this._cache.orthoRight = this.orthoRight;
  22751. this._cache.orthoBottom = this.orthoBottom;
  22752. this._cache.orthoTop = this.orthoTop;
  22753. this._cache.renderWidth = engine.getRenderWidth();
  22754. this._cache.renderHeight = engine.getRenderHeight();
  22755. }
  22756. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22757. return this._projectionMatrix;
  22758. };
  22759. Camera.prototype.getTranformationMatrix = function () {
  22760. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22761. return this._transformMatrix;
  22762. };
  22763. Camera.prototype.updateFrustumPlanes = function () {
  22764. if (!this._refreshFrustumPlanes) {
  22765. return;
  22766. }
  22767. this.getTranformationMatrix();
  22768. if (!this._frustumPlanes) {
  22769. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22770. }
  22771. else {
  22772. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22773. }
  22774. this._refreshFrustumPlanes = false;
  22775. };
  22776. Camera.prototype.isInFrustum = function (target) {
  22777. this.updateFrustumPlanes();
  22778. return target.isInFrustum(this._frustumPlanes);
  22779. };
  22780. Camera.prototype.isCompletelyInFrustum = function (target) {
  22781. this.updateFrustumPlanes();
  22782. return target.isCompletelyInFrustum(this._frustumPlanes);
  22783. };
  22784. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22785. if (length === void 0) { length = 100; }
  22786. if (!transform) {
  22787. transform = this.getWorldMatrix();
  22788. }
  22789. if (!origin) {
  22790. origin = this.position;
  22791. }
  22792. var forward = new BABYLON.Vector3(0, 0, 1);
  22793. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22794. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22795. return new BABYLON.Ray(origin, direction, length);
  22796. };
  22797. /**
  22798. * Releases resources associated with this node.
  22799. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22800. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22801. */
  22802. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22803. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22804. // Observables
  22805. this.onViewMatrixChangedObservable.clear();
  22806. this.onProjectionMatrixChangedObservable.clear();
  22807. this.onAfterCheckInputsObservable.clear();
  22808. this.onRestoreStateObservable.clear();
  22809. // Inputs
  22810. if (this.inputs) {
  22811. this.inputs.clear();
  22812. }
  22813. // Animations
  22814. this.getScene().stopAnimation(this);
  22815. // Remove from scene
  22816. this.getScene().removeCamera(this);
  22817. while (this._rigCameras.length > 0) {
  22818. var camera = this._rigCameras.pop();
  22819. if (camera) {
  22820. camera.dispose();
  22821. }
  22822. }
  22823. // Postprocesses
  22824. if (this._rigPostProcess) {
  22825. this._rigPostProcess.dispose(this);
  22826. this._rigPostProcess = null;
  22827. this._postProcesses = [];
  22828. }
  22829. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22830. this._rigPostProcess = null;
  22831. this._postProcesses = [];
  22832. }
  22833. else {
  22834. var i = this._postProcesses.length;
  22835. while (--i >= 0) {
  22836. var postProcess = this._postProcesses[i];
  22837. if (postProcess) {
  22838. postProcess.dispose(this);
  22839. }
  22840. }
  22841. }
  22842. // Render targets
  22843. var i = this.customRenderTargets.length;
  22844. while (--i >= 0) {
  22845. this.customRenderTargets[i].dispose();
  22846. }
  22847. this.customRenderTargets = [];
  22848. // Active Meshes
  22849. this._activeMeshes.dispose();
  22850. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22851. };
  22852. Object.defineProperty(Camera.prototype, "leftCamera", {
  22853. // ---- Camera rigs section ----
  22854. get: function () {
  22855. if (this._rigCameras.length < 1) {
  22856. return null;
  22857. }
  22858. return this._rigCameras[0];
  22859. },
  22860. enumerable: true,
  22861. configurable: true
  22862. });
  22863. Object.defineProperty(Camera.prototype, "rightCamera", {
  22864. get: function () {
  22865. if (this._rigCameras.length < 2) {
  22866. return null;
  22867. }
  22868. return this._rigCameras[1];
  22869. },
  22870. enumerable: true,
  22871. configurable: true
  22872. });
  22873. Camera.prototype.getLeftTarget = function () {
  22874. if (this._rigCameras.length < 1) {
  22875. return null;
  22876. }
  22877. return this._rigCameras[0].getTarget();
  22878. };
  22879. Camera.prototype.getRightTarget = function () {
  22880. if (this._rigCameras.length < 2) {
  22881. return null;
  22882. }
  22883. return this._rigCameras[1].getTarget();
  22884. };
  22885. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22886. if (this.cameraRigMode === mode) {
  22887. return;
  22888. }
  22889. while (this._rigCameras.length > 0) {
  22890. var camera = this._rigCameras.pop();
  22891. if (camera) {
  22892. camera.dispose();
  22893. }
  22894. }
  22895. this.cameraRigMode = mode;
  22896. this._cameraRigParams = {};
  22897. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22898. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22899. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22900. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22901. // create the rig cameras, unless none
  22902. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22903. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22904. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22905. if (leftCamera && rightCamera) {
  22906. this._rigCameras.push(leftCamera);
  22907. this._rigCameras.push(rightCamera);
  22908. }
  22909. }
  22910. switch (this.cameraRigMode) {
  22911. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22912. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22913. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22914. break;
  22915. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22916. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22917. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22918. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22919. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22920. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22921. break;
  22922. case Camera.RIG_MODE_VR:
  22923. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22924. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22925. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22926. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22927. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22928. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22929. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22930. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22931. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22932. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22933. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22934. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22935. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22936. if (metrics.compensateDistortion) {
  22937. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22938. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22939. }
  22940. break;
  22941. case Camera.RIG_MODE_WEBVR:
  22942. if (rigParams.vrDisplay) {
  22943. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22944. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22945. //Left eye
  22946. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22947. this._rigCameras[0].setCameraRigParameter("left", true);
  22948. //leaving this for future reference
  22949. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22950. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22951. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22952. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22953. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22954. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22955. this._rigCameras[0].parent = this;
  22956. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22957. //Right eye
  22958. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22959. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22960. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22961. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22962. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22963. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22964. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22965. this._rigCameras[1].parent = this;
  22966. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22967. if (Camera.UseAlternateWebVRRendering) {
  22968. this._rigCameras[1]._skipRendering = true;
  22969. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22970. }
  22971. }
  22972. break;
  22973. }
  22974. this._cascadePostProcessesToRigCams();
  22975. this.update();
  22976. };
  22977. Camera.prototype._getVRProjectionMatrix = function () {
  22978. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22979. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22980. return this._projectionMatrix;
  22981. };
  22982. Camera.prototype._updateCameraRotationMatrix = function () {
  22983. //Here for WebVR
  22984. };
  22985. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22986. //Here for WebVR
  22987. };
  22988. /**
  22989. * This function MUST be overwritten by the different WebVR cameras available.
  22990. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22991. */
  22992. Camera.prototype._getWebVRProjectionMatrix = function () {
  22993. return BABYLON.Matrix.Identity();
  22994. };
  22995. /**
  22996. * This function MUST be overwritten by the different WebVR cameras available.
  22997. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22998. */
  22999. Camera.prototype._getWebVRViewMatrix = function () {
  23000. return BABYLON.Matrix.Identity();
  23001. };
  23002. Camera.prototype.setCameraRigParameter = function (name, value) {
  23003. if (!this._cameraRigParams) {
  23004. this._cameraRigParams = {};
  23005. }
  23006. this._cameraRigParams[name] = value;
  23007. //provisionnally:
  23008. if (name === "interaxialDistance") {
  23009. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23010. }
  23011. };
  23012. /**
  23013. * needs to be overridden by children so sub has required properties to be copied
  23014. */
  23015. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23016. return null;
  23017. };
  23018. /**
  23019. * May need to be overridden by children
  23020. */
  23021. Camera.prototype._updateRigCameras = function () {
  23022. for (var i = 0; i < this._rigCameras.length; i++) {
  23023. this._rigCameras[i].minZ = this.minZ;
  23024. this._rigCameras[i].maxZ = this.maxZ;
  23025. this._rigCameras[i].fov = this.fov;
  23026. }
  23027. // only update viewport when ANAGLYPH
  23028. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23029. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23030. }
  23031. };
  23032. Camera.prototype._setupInputs = function () {
  23033. };
  23034. Camera.prototype.serialize = function () {
  23035. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23036. // Type
  23037. serializationObject.type = this.getClassName();
  23038. // Parent
  23039. if (this.parent) {
  23040. serializationObject.parentId = this.parent.id;
  23041. }
  23042. if (this.inputs) {
  23043. this.inputs.serialize(serializationObject);
  23044. }
  23045. // Animations
  23046. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23047. serializationObject.ranges = this.serializeAnimationRanges();
  23048. return serializationObject;
  23049. };
  23050. Camera.prototype.clone = function (name) {
  23051. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23052. };
  23053. Camera.prototype.getDirection = function (localAxis) {
  23054. var result = BABYLON.Vector3.Zero();
  23055. this.getDirectionToRef(localAxis, result);
  23056. return result;
  23057. };
  23058. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23059. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23060. };
  23061. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23062. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23063. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23064. switch (type) {
  23065. case "ArcRotateCamera":
  23066. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23067. case "DeviceOrientationCamera":
  23068. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23069. case "FollowCamera":
  23070. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23071. case "ArcFollowCamera":
  23072. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23073. case "GamepadCamera":
  23074. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23075. case "TouchCamera":
  23076. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23077. case "VirtualJoysticksCamera":
  23078. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23079. case "WebVRFreeCamera":
  23080. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23081. case "WebVRGamepadCamera":
  23082. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23083. case "VRDeviceOrientationFreeCamera":
  23084. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23085. case "VRDeviceOrientationGamepadCamera":
  23086. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23087. case "AnaglyphArcRotateCamera":
  23088. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23089. case "AnaglyphFreeCamera":
  23090. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23091. case "AnaglyphGamepadCamera":
  23092. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23093. case "AnaglyphUniversalCamera":
  23094. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23095. case "StereoscopicArcRotateCamera":
  23096. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23097. case "StereoscopicFreeCamera":
  23098. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23099. case "StereoscopicGamepadCamera":
  23100. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23101. case "StereoscopicUniversalCamera":
  23102. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23103. case "FreeCamera": // Forcing Universal here
  23104. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23105. default: // Universal Camera is the default value
  23106. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23107. }
  23108. };
  23109. Camera.prototype.computeWorldMatrix = function () {
  23110. return this.getWorldMatrix();
  23111. };
  23112. Camera.Parse = function (parsedCamera, scene) {
  23113. var type = parsedCamera.type;
  23114. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23115. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23116. // Parent
  23117. if (parsedCamera.parentId) {
  23118. camera._waitingParentId = parsedCamera.parentId;
  23119. }
  23120. //If camera has an input manager, let it parse inputs settings
  23121. if (camera.inputs) {
  23122. camera.inputs.parse(parsedCamera);
  23123. camera._setupInputs();
  23124. }
  23125. if (camera.setPosition) { // need to force position
  23126. camera.position.copyFromFloats(0, 0, 0);
  23127. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23128. }
  23129. // Target
  23130. if (parsedCamera.target) {
  23131. if (camera.setTarget) {
  23132. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23133. }
  23134. }
  23135. // Apply 3d rig, when found
  23136. if (parsedCamera.cameraRigMode) {
  23137. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23138. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23139. }
  23140. // Animations
  23141. if (parsedCamera.animations) {
  23142. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23143. var parsedAnimation = parsedCamera.animations[animationIndex];
  23144. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23145. }
  23146. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23147. }
  23148. if (parsedCamera.autoAnimate) {
  23149. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23150. }
  23151. return camera;
  23152. };
  23153. // Statics
  23154. Camera._PERSPECTIVE_CAMERA = 0;
  23155. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23156. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23157. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23158. Camera._RIG_MODE_NONE = 0;
  23159. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23160. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23161. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23162. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23163. Camera._RIG_MODE_VR = 20;
  23164. Camera._RIG_MODE_WEBVR = 21;
  23165. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23166. Camera.UseAlternateWebVRRendering = false;
  23167. __decorate([
  23168. BABYLON.serializeAsVector3()
  23169. ], Camera.prototype, "position", void 0);
  23170. __decorate([
  23171. BABYLON.serializeAsVector3()
  23172. ], Camera.prototype, "upVector", void 0);
  23173. __decorate([
  23174. BABYLON.serialize()
  23175. ], Camera.prototype, "orthoLeft", void 0);
  23176. __decorate([
  23177. BABYLON.serialize()
  23178. ], Camera.prototype, "orthoRight", void 0);
  23179. __decorate([
  23180. BABYLON.serialize()
  23181. ], Camera.prototype, "orthoBottom", void 0);
  23182. __decorate([
  23183. BABYLON.serialize()
  23184. ], Camera.prototype, "orthoTop", void 0);
  23185. __decorate([
  23186. BABYLON.serialize()
  23187. ], Camera.prototype, "fov", void 0);
  23188. __decorate([
  23189. BABYLON.serialize()
  23190. ], Camera.prototype, "minZ", void 0);
  23191. __decorate([
  23192. BABYLON.serialize()
  23193. ], Camera.prototype, "maxZ", void 0);
  23194. __decorate([
  23195. BABYLON.serialize()
  23196. ], Camera.prototype, "inertia", void 0);
  23197. __decorate([
  23198. BABYLON.serialize()
  23199. ], Camera.prototype, "mode", void 0);
  23200. __decorate([
  23201. BABYLON.serialize()
  23202. ], Camera.prototype, "layerMask", void 0);
  23203. __decorate([
  23204. BABYLON.serialize()
  23205. ], Camera.prototype, "fovMode", void 0);
  23206. __decorate([
  23207. BABYLON.serialize()
  23208. ], Camera.prototype, "cameraRigMode", void 0);
  23209. __decorate([
  23210. BABYLON.serialize()
  23211. ], Camera.prototype, "interaxialDistance", void 0);
  23212. __decorate([
  23213. BABYLON.serialize()
  23214. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23215. return Camera;
  23216. }(BABYLON.Node));
  23217. BABYLON.Camera = Camera;
  23218. })(BABYLON || (BABYLON = {}));
  23219. //# sourceMappingURL=babylon.camera.js.map
  23220. var BABYLON;
  23221. (function (BABYLON) {
  23222. var RenderingManager = /** @class */ (function () {
  23223. function RenderingManager(scene) {
  23224. this._renderingGroups = new Array();
  23225. this._autoClearDepthStencil = {};
  23226. this._customOpaqueSortCompareFn = {};
  23227. this._customAlphaTestSortCompareFn = {};
  23228. this._customTransparentSortCompareFn = {};
  23229. this._renderinGroupInfo = null;
  23230. this._scene = scene;
  23231. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23232. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23233. }
  23234. }
  23235. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23236. if (depth === void 0) { depth = true; }
  23237. if (stencil === void 0) { stencil = true; }
  23238. if (this._depthStencilBufferAlreadyCleaned) {
  23239. return;
  23240. }
  23241. this._scene.getEngine().clear(null, false, depth, stencil);
  23242. this._depthStencilBufferAlreadyCleaned = true;
  23243. };
  23244. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23245. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23246. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23247. var info = null;
  23248. if (observable) {
  23249. if (!this._renderinGroupInfo) {
  23250. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23251. }
  23252. info = this._renderinGroupInfo;
  23253. info.scene = this._scene;
  23254. info.camera = this._scene.activeCamera;
  23255. }
  23256. // Dispatch sprites
  23257. if (renderSprites) {
  23258. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23259. var manager = this._scene.spriteManagers[index];
  23260. this.dispatchSprites(manager);
  23261. }
  23262. }
  23263. // Render
  23264. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23265. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23266. var renderingGroup = this._renderingGroups[index];
  23267. if (!renderingGroup && !observable)
  23268. continue;
  23269. var renderingGroupMask = 0;
  23270. // Fire PRECLEAR stage
  23271. if (observable && info) {
  23272. renderingGroupMask = Math.pow(2, index);
  23273. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23274. info.renderingGroupId = index;
  23275. observable.notifyObservers(info, renderingGroupMask);
  23276. }
  23277. // Clear depth/stencil if needed
  23278. if (RenderingManager.AUTOCLEAR) {
  23279. var autoClear = this._autoClearDepthStencil[index];
  23280. if (autoClear && autoClear.autoClear) {
  23281. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23282. }
  23283. }
  23284. if (observable && info) {
  23285. // Fire PREOPAQUE stage
  23286. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23287. observable.notifyObservers(info, renderingGroupMask);
  23288. // Fire PRETRANSPARENT stage
  23289. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23290. observable.notifyObservers(info, renderingGroupMask);
  23291. }
  23292. if (renderingGroup)
  23293. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23294. // Fire POSTTRANSPARENT stage
  23295. if (observable && info) {
  23296. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23297. observable.notifyObservers(info, renderingGroupMask);
  23298. }
  23299. }
  23300. };
  23301. RenderingManager.prototype.reset = function () {
  23302. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23303. var renderingGroup = this._renderingGroups[index];
  23304. if (renderingGroup) {
  23305. renderingGroup.prepare();
  23306. }
  23307. }
  23308. };
  23309. RenderingManager.prototype.dispose = function () {
  23310. this.freeRenderingGroups();
  23311. this._renderingGroups.length = 0;
  23312. };
  23313. /**
  23314. * Clear the info related to rendering groups preventing retention points during dispose.
  23315. */
  23316. RenderingManager.prototype.freeRenderingGroups = function () {
  23317. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23318. var renderingGroup = this._renderingGroups[index];
  23319. if (renderingGroup) {
  23320. renderingGroup.dispose();
  23321. }
  23322. }
  23323. };
  23324. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23325. if (this._renderingGroups[renderingGroupId] === undefined) {
  23326. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23327. }
  23328. };
  23329. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23330. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23331. this._prepareRenderingGroup(renderingGroupId);
  23332. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23333. };
  23334. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23335. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23336. this._prepareRenderingGroup(renderingGroupId);
  23337. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23338. };
  23339. /**
  23340. * @param subMesh The submesh to dispatch
  23341. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23342. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23343. */
  23344. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23345. if (mesh === undefined) {
  23346. mesh = subMesh.getMesh();
  23347. }
  23348. var renderingGroupId = mesh.renderingGroupId || 0;
  23349. this._prepareRenderingGroup(renderingGroupId);
  23350. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23351. };
  23352. /**
  23353. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23354. * This allowed control for front to back rendering or reversly depending of the special needs.
  23355. *
  23356. * @param renderingGroupId The rendering group id corresponding to its index
  23357. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23358. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23359. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23360. */
  23361. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23362. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23363. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23364. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23365. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23366. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23367. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23368. if (this._renderingGroups[renderingGroupId]) {
  23369. var group = this._renderingGroups[renderingGroupId];
  23370. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23371. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23372. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23373. }
  23374. };
  23375. /**
  23376. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23377. *
  23378. * @param renderingGroupId The rendering group id corresponding to its index
  23379. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23380. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23381. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23382. */
  23383. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23384. if (depth === void 0) { depth = true; }
  23385. if (stencil === void 0) { stencil = true; }
  23386. this._autoClearDepthStencil[renderingGroupId] = {
  23387. autoClear: autoClearDepthStencil,
  23388. depth: depth,
  23389. stencil: stencil
  23390. };
  23391. };
  23392. /**
  23393. * The max id used for rendering groups (not included)
  23394. */
  23395. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23396. /**
  23397. * The min id used for rendering groups (included)
  23398. */
  23399. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23400. /**
  23401. * Used to globally prevent autoclearing scenes.
  23402. */
  23403. RenderingManager.AUTOCLEAR = true;
  23404. return RenderingManager;
  23405. }());
  23406. BABYLON.RenderingManager = RenderingManager;
  23407. })(BABYLON || (BABYLON = {}));
  23408. //# sourceMappingURL=babylon.renderingManager.js.map
  23409. var BABYLON;
  23410. (function (BABYLON) {
  23411. var RenderingGroup = /** @class */ (function () {
  23412. /**
  23413. * Creates a new rendering group.
  23414. * @param index The rendering group index
  23415. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23416. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23417. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23418. */
  23419. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23420. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23421. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23422. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23423. this.index = index;
  23424. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23425. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23426. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23427. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23428. this._particleSystems = new BABYLON.SmartArray(256);
  23429. this._spriteManagers = new BABYLON.SmartArray(256);
  23430. this._edgesRenderers = new BABYLON.SmartArray(16);
  23431. this._scene = scene;
  23432. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23433. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23434. this.transparentSortCompareFn = transparentSortCompareFn;
  23435. }
  23436. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23437. /**
  23438. * Set the opaque sort comparison function.
  23439. * If null the sub meshes will be render in the order they were created
  23440. */
  23441. set: function (value) {
  23442. this._opaqueSortCompareFn = value;
  23443. if (value) {
  23444. this._renderOpaque = this.renderOpaqueSorted;
  23445. }
  23446. else {
  23447. this._renderOpaque = RenderingGroup.renderUnsorted;
  23448. }
  23449. },
  23450. enumerable: true,
  23451. configurable: true
  23452. });
  23453. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23454. /**
  23455. * Set the alpha test sort comparison function.
  23456. * If null the sub meshes will be render in the order they were created
  23457. */
  23458. set: function (value) {
  23459. this._alphaTestSortCompareFn = value;
  23460. if (value) {
  23461. this._renderAlphaTest = this.renderAlphaTestSorted;
  23462. }
  23463. else {
  23464. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23465. }
  23466. },
  23467. enumerable: true,
  23468. configurable: true
  23469. });
  23470. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23471. /**
  23472. * Set the transparent sort comparison function.
  23473. * If null the sub meshes will be render in the order they were created
  23474. */
  23475. set: function (value) {
  23476. if (value) {
  23477. this._transparentSortCompareFn = value;
  23478. }
  23479. else {
  23480. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23481. }
  23482. this._renderTransparent = this.renderTransparentSorted;
  23483. },
  23484. enumerable: true,
  23485. configurable: true
  23486. });
  23487. /**
  23488. * Render all the sub meshes contained in the group.
  23489. * @param customRenderFunction Used to override the default render behaviour of the group.
  23490. * @returns true if rendered some submeshes.
  23491. */
  23492. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23493. if (customRenderFunction) {
  23494. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23495. return;
  23496. }
  23497. var engine = this._scene.getEngine();
  23498. // Depth only
  23499. if (this._depthOnlySubMeshes.length !== 0) {
  23500. engine.setColorWrite(false);
  23501. this._renderAlphaTest(this._depthOnlySubMeshes);
  23502. engine.setColorWrite(true);
  23503. }
  23504. // Opaque
  23505. if (this._opaqueSubMeshes.length !== 0) {
  23506. this._renderOpaque(this._opaqueSubMeshes);
  23507. }
  23508. // Alpha test
  23509. if (this._alphaTestSubMeshes.length !== 0) {
  23510. this._renderAlphaTest(this._alphaTestSubMeshes);
  23511. }
  23512. var stencilState = engine.getStencilBuffer();
  23513. engine.setStencilBuffer(false);
  23514. // Sprites
  23515. if (renderSprites) {
  23516. this._renderSprites();
  23517. }
  23518. // Particles
  23519. if (renderParticles) {
  23520. this._renderParticles(activeMeshes);
  23521. }
  23522. if (this.onBeforeTransparentRendering) {
  23523. this.onBeforeTransparentRendering();
  23524. }
  23525. // Transparent
  23526. if (this._transparentSubMeshes.length !== 0) {
  23527. this._renderTransparent(this._transparentSubMeshes);
  23528. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23529. }
  23530. // Set back stencil to false in case it changes before the edge renderer.
  23531. engine.setStencilBuffer(false);
  23532. // Edges
  23533. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23534. this._edgesRenderers.data[edgesRendererIndex].render();
  23535. }
  23536. // Restore Stencil state.
  23537. engine.setStencilBuffer(stencilState);
  23538. };
  23539. /**
  23540. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23541. * @param subMeshes The submeshes to render
  23542. */
  23543. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23544. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23545. };
  23546. /**
  23547. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23548. * @param subMeshes The submeshes to render
  23549. */
  23550. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23551. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23552. };
  23553. /**
  23554. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23555. * @param subMeshes The submeshes to render
  23556. */
  23557. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23558. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23559. };
  23560. /**
  23561. * Renders the submeshes in a specified order.
  23562. * @param subMeshes The submeshes to sort before render
  23563. * @param sortCompareFn The comparison function use to sort
  23564. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23565. * @param transparent Specifies to activate blending if true
  23566. */
  23567. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23568. var subIndex = 0;
  23569. var subMesh;
  23570. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23571. for (; subIndex < subMeshes.length; subIndex++) {
  23572. subMesh = subMeshes.data[subIndex];
  23573. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23574. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23575. }
  23576. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23577. if (sortCompareFn) {
  23578. sortedArray.sort(sortCompareFn);
  23579. }
  23580. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23581. subMesh = sortedArray[subIndex];
  23582. if (transparent) {
  23583. var material = subMesh.getMaterial();
  23584. if (material && material.needDepthPrePass) {
  23585. var engine = material.getScene().getEngine();
  23586. engine.setColorWrite(false);
  23587. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23588. subMesh.render(false);
  23589. engine.setColorWrite(true);
  23590. }
  23591. }
  23592. subMesh.render(transparent);
  23593. }
  23594. };
  23595. /**
  23596. * Renders the submeshes in the order they were dispatched (no sort applied).
  23597. * @param subMeshes The submeshes to render
  23598. */
  23599. RenderingGroup.renderUnsorted = function (subMeshes) {
  23600. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23601. var submesh = subMeshes.data[subIndex];
  23602. submesh.render(false);
  23603. }
  23604. };
  23605. /**
  23606. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23607. * are rendered back to front if in the same alpha index.
  23608. *
  23609. * @param a The first submesh
  23610. * @param b The second submesh
  23611. * @returns The result of the comparison
  23612. */
  23613. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23614. // Alpha index first
  23615. if (a._alphaIndex > b._alphaIndex) {
  23616. return 1;
  23617. }
  23618. if (a._alphaIndex < b._alphaIndex) {
  23619. return -1;
  23620. }
  23621. // Then distance to camera
  23622. return RenderingGroup.backToFrontSortCompare(a, b);
  23623. };
  23624. /**
  23625. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23626. * are rendered back to front.
  23627. *
  23628. * @param a The first submesh
  23629. * @param b The second submesh
  23630. * @returns The result of the comparison
  23631. */
  23632. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23633. // Then distance to camera
  23634. if (a._distanceToCamera < b._distanceToCamera) {
  23635. return 1;
  23636. }
  23637. if (a._distanceToCamera > b._distanceToCamera) {
  23638. return -1;
  23639. }
  23640. return 0;
  23641. };
  23642. /**
  23643. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23644. * are rendered front to back (prevent overdraw).
  23645. *
  23646. * @param a The first submesh
  23647. * @param b The second submesh
  23648. * @returns The result of the comparison
  23649. */
  23650. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23651. // Then distance to camera
  23652. if (a._distanceToCamera < b._distanceToCamera) {
  23653. return -1;
  23654. }
  23655. if (a._distanceToCamera > b._distanceToCamera) {
  23656. return 1;
  23657. }
  23658. return 0;
  23659. };
  23660. /**
  23661. * Resets the different lists of submeshes to prepare a new frame.
  23662. */
  23663. RenderingGroup.prototype.prepare = function () {
  23664. this._opaqueSubMeshes.reset();
  23665. this._transparentSubMeshes.reset();
  23666. this._alphaTestSubMeshes.reset();
  23667. this._depthOnlySubMeshes.reset();
  23668. this._particleSystems.reset();
  23669. this._spriteManagers.reset();
  23670. this._edgesRenderers.reset();
  23671. };
  23672. RenderingGroup.prototype.dispose = function () {
  23673. this._opaqueSubMeshes.dispose();
  23674. this._transparentSubMeshes.dispose();
  23675. this._alphaTestSubMeshes.dispose();
  23676. this._depthOnlySubMeshes.dispose();
  23677. this._particleSystems.dispose();
  23678. this._spriteManagers.dispose();
  23679. this._edgesRenderers.dispose();
  23680. };
  23681. /**
  23682. * Inserts the submesh in its correct queue depending on its material.
  23683. * @param subMesh The submesh to dispatch
  23684. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23685. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23686. */
  23687. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23688. // Get mesh and materials if not provided
  23689. if (mesh === undefined) {
  23690. mesh = subMesh.getMesh();
  23691. }
  23692. if (material === undefined) {
  23693. material = subMesh.getMaterial();
  23694. }
  23695. if (material === null || material === undefined) {
  23696. return;
  23697. }
  23698. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23699. this._transparentSubMeshes.push(subMesh);
  23700. }
  23701. else if (material.needAlphaTesting()) { // Alpha test
  23702. if (material.needDepthPrePass) {
  23703. this._depthOnlySubMeshes.push(subMesh);
  23704. }
  23705. this._alphaTestSubMeshes.push(subMesh);
  23706. }
  23707. else {
  23708. if (material.needDepthPrePass) {
  23709. this._depthOnlySubMeshes.push(subMesh);
  23710. }
  23711. this._opaqueSubMeshes.push(subMesh); // Opaque
  23712. }
  23713. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23714. this._edgesRenderers.push(mesh._edgesRenderer);
  23715. }
  23716. };
  23717. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23718. this._spriteManagers.push(spriteManager);
  23719. };
  23720. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23721. this._particleSystems.push(particleSystem);
  23722. };
  23723. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23724. if (this._particleSystems.length === 0) {
  23725. return;
  23726. }
  23727. // Particles
  23728. var activeCamera = this._scene.activeCamera;
  23729. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23730. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23731. var particleSystem = this._particleSystems.data[particleIndex];
  23732. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23733. continue;
  23734. }
  23735. var emitter = particleSystem.emitter;
  23736. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23737. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23738. }
  23739. }
  23740. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23741. };
  23742. RenderingGroup.prototype._renderSprites = function () {
  23743. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23744. return;
  23745. }
  23746. // Sprites
  23747. var activeCamera = this._scene.activeCamera;
  23748. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23749. for (var id = 0; id < this._spriteManagers.length; id++) {
  23750. var spriteManager = this._spriteManagers.data[id];
  23751. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23752. spriteManager.render();
  23753. }
  23754. }
  23755. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23756. };
  23757. return RenderingGroup;
  23758. }());
  23759. BABYLON.RenderingGroup = RenderingGroup;
  23760. })(BABYLON || (BABYLON = {}));
  23761. //# sourceMappingURL=babylon.renderingGroup.js.map
  23762. var BABYLON;
  23763. (function (BABYLON) {
  23764. /** @hidden */
  23765. var ClickInfo = /** @class */ (function () {
  23766. function ClickInfo() {
  23767. this._singleClick = false;
  23768. this._doubleClick = false;
  23769. this._hasSwiped = false;
  23770. this._ignore = false;
  23771. }
  23772. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23773. get: function () {
  23774. return this._singleClick;
  23775. },
  23776. set: function (b) {
  23777. this._singleClick = b;
  23778. },
  23779. enumerable: true,
  23780. configurable: true
  23781. });
  23782. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23783. get: function () {
  23784. return this._doubleClick;
  23785. },
  23786. set: function (b) {
  23787. this._doubleClick = b;
  23788. },
  23789. enumerable: true,
  23790. configurable: true
  23791. });
  23792. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23793. get: function () {
  23794. return this._hasSwiped;
  23795. },
  23796. set: function (b) {
  23797. this._hasSwiped = b;
  23798. },
  23799. enumerable: true,
  23800. configurable: true
  23801. });
  23802. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23803. get: function () {
  23804. return this._ignore;
  23805. },
  23806. set: function (b) {
  23807. this._ignore = b;
  23808. },
  23809. enumerable: true,
  23810. configurable: true
  23811. });
  23812. return ClickInfo;
  23813. }());
  23814. /**
  23815. * This class is used by the onRenderingGroupObservable
  23816. */
  23817. var RenderingGroupInfo = /** @class */ (function () {
  23818. function RenderingGroupInfo() {
  23819. }
  23820. /**
  23821. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23822. * This stage will be fired no matter what
  23823. */
  23824. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23825. /**
  23826. * Called before opaque object are rendered.
  23827. * This stage will be fired only if there's 3D Opaque content to render
  23828. */
  23829. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23830. /**
  23831. * Called after the opaque objects are rendered and before the transparent ones
  23832. * This stage will be fired only if there's 3D transparent content to render
  23833. */
  23834. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23835. /**
  23836. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23837. * This stage will be fired no matter what
  23838. */
  23839. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23840. return RenderingGroupInfo;
  23841. }());
  23842. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23843. /**
  23844. * Represents a scene to be rendered by the engine.
  23845. * @see http://doc.babylonjs.com/features/scene
  23846. */
  23847. var Scene = /** @class */ (function () {
  23848. /**
  23849. * Creates a new Scene
  23850. * @param engine defines the engine to use to render this scene
  23851. */
  23852. function Scene(engine) {
  23853. // Members
  23854. /**
  23855. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23856. */
  23857. this.autoClear = true;
  23858. /**
  23859. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23860. */
  23861. this.autoClearDepthAndStencil = true;
  23862. /**
  23863. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23864. */
  23865. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23866. /**
  23867. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23868. */
  23869. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23870. this._forceWireframe = false;
  23871. this._forcePointsCloud = false;
  23872. /**
  23873. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23874. */
  23875. this.forceShowBoundingBoxes = false;
  23876. /**
  23877. * Gets or sets a boolean indicating if animations are enabled
  23878. */
  23879. this.animationsEnabled = true;
  23880. this._animationPropertiesOverride = null;
  23881. /**
  23882. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23883. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23884. */
  23885. this.useConstantAnimationDeltaTime = false;
  23886. /**
  23887. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23888. * Please note that it requires to run a ray cast through the scene on every frame
  23889. */
  23890. this.constantlyUpdateMeshUnderPointer = false;
  23891. /**
  23892. * Defines the HTML cursor to use when hovering over interactive elements
  23893. */
  23894. this.hoverCursor = "pointer";
  23895. /**
  23896. * Defines the HTML default cursor to use (empty by default)
  23897. */
  23898. this.defaultCursor = "";
  23899. /**
  23900. * This is used to call preventDefault() on pointer down
  23901. * in order to block unwanted artifacts like system double clicks
  23902. */
  23903. this.preventDefaultOnPointerDown = true;
  23904. // Metadata
  23905. /**
  23906. * Gets or sets user defined metadata
  23907. */
  23908. this.metadata = null;
  23909. /**
  23910. * Use this array to add regular expressions used to disable offline support for specific urls
  23911. */
  23912. this.disableOfflineSupportExceptionRules = new Array();
  23913. /**
  23914. * An event triggered when the scene is disposed.
  23915. */
  23916. this.onDisposeObservable = new BABYLON.Observable();
  23917. this._onDisposeObserver = null;
  23918. /**
  23919. * An event triggered before rendering the scene (right after animations and physics)
  23920. */
  23921. this.onBeforeRenderObservable = new BABYLON.Observable();
  23922. this._onBeforeRenderObserver = null;
  23923. /**
  23924. * An event triggered after rendering the scene
  23925. */
  23926. this.onAfterRenderObservable = new BABYLON.Observable();
  23927. this._onAfterRenderObserver = null;
  23928. /**
  23929. * An event triggered before animating the scene
  23930. */
  23931. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23932. /**
  23933. * An event triggered after animations processing
  23934. */
  23935. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23936. /**
  23937. * An event triggered before draw calls are ready to be sent
  23938. */
  23939. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23940. /**
  23941. * An event triggered after draw calls have been sent
  23942. */
  23943. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23944. /**
  23945. * An event triggered when physic simulation is about to be run
  23946. */
  23947. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23948. /**
  23949. * An event triggered when physic simulation has been done
  23950. */
  23951. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23952. /**
  23953. * An event triggered when the scene is ready
  23954. */
  23955. this.onReadyObservable = new BABYLON.Observable();
  23956. /**
  23957. * An event triggered before rendering a camera
  23958. */
  23959. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23960. this._onBeforeCameraRenderObserver = null;
  23961. /**
  23962. * An event triggered after rendering a camera
  23963. */
  23964. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23965. this._onAfterCameraRenderObserver = null;
  23966. /**
  23967. * An event triggered when active meshes evaluation is about to start
  23968. */
  23969. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23970. /**
  23971. * An event triggered when active meshes evaluation is done
  23972. */
  23973. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23974. /**
  23975. * An event triggered when particles rendering is about to start
  23976. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23977. */
  23978. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23979. /**
  23980. * An event triggered when particles rendering is done
  23981. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23982. */
  23983. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23984. /**
  23985. * An event triggered when sprites rendering is about to start
  23986. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23987. */
  23988. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23989. /**
  23990. * An event triggered when sprites rendering is done
  23991. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23992. */
  23993. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23994. /**
  23995. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23996. */
  23997. this.onDataLoadedObservable = new BABYLON.Observable();
  23998. /**
  23999. * An event triggered when a camera is created
  24000. */
  24001. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24002. /**
  24003. * An event triggered when a camera is removed
  24004. */
  24005. this.onCameraRemovedObservable = new BABYLON.Observable();
  24006. /**
  24007. * An event triggered when a light is created
  24008. */
  24009. this.onNewLightAddedObservable = new BABYLON.Observable();
  24010. /**
  24011. * An event triggered when a light is removed
  24012. */
  24013. this.onLightRemovedObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered when a geometry is created
  24016. */
  24017. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered when a geometry is removed
  24020. */
  24021. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24022. /**
  24023. * An event triggered when a transform node is created
  24024. */
  24025. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24026. /**
  24027. * An event triggered when a transform node is removed
  24028. */
  24029. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24030. /**
  24031. * An event triggered when a mesh is created
  24032. */
  24033. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24034. /**
  24035. * An event triggered when a mesh is removed
  24036. */
  24037. this.onMeshRemovedObservable = new BABYLON.Observable();
  24038. /**
  24039. * An event triggered when render targets are about to be rendered
  24040. * Can happen multiple times per frame.
  24041. */
  24042. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24043. /**
  24044. * An event triggered when render targets were rendered.
  24045. * Can happen multiple times per frame.
  24046. */
  24047. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24048. /**
  24049. * An event triggered before calculating deterministic simulation step
  24050. */
  24051. this.onBeforeStepObservable = new BABYLON.Observable();
  24052. /**
  24053. * An event triggered after calculating deterministic simulation step
  24054. */
  24055. this.onAfterStepObservable = new BABYLON.Observable();
  24056. /**
  24057. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24058. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24059. * 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)
  24060. */
  24061. this.onRenderingGroupObservable = new BABYLON.Observable();
  24062. // Animations
  24063. /**
  24064. * Gets a list of Animations associated with the scene
  24065. */
  24066. this.animations = [];
  24067. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24068. /**
  24069. * 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).
  24070. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24071. */
  24072. this.onPrePointerObservable = new BABYLON.Observable();
  24073. /**
  24074. * Observable event triggered each time an input event is received from the rendering canvas
  24075. */
  24076. this.onPointerObservable = new BABYLON.Observable();
  24077. this._meshPickProceed = false;
  24078. this._currentPickResult = null;
  24079. this._previousPickResult = null;
  24080. this._totalPointersPressed = 0;
  24081. this._doubleClickOccured = false;
  24082. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24083. this.cameraToUseForPointers = null;
  24084. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24085. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24086. this._startingPointerTime = 0;
  24087. this._previousStartingPointerTime = 0;
  24088. this._pointerCaptures = {};
  24089. // Deterministic lockstep
  24090. this._timeAccumulator = 0;
  24091. this._currentStepId = 0;
  24092. this._currentInternalStep = 0;
  24093. // Keyboard
  24094. /**
  24095. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24096. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24097. */
  24098. this.onPreKeyboardObservable = new BABYLON.Observable();
  24099. /**
  24100. * Observable event triggered each time an keyboard event is received from the hosting window
  24101. */
  24102. this.onKeyboardObservable = new BABYLON.Observable();
  24103. // Coordinates system
  24104. this._useRightHandedSystem = false;
  24105. // Fog
  24106. this._fogEnabled = true;
  24107. this._fogMode = Scene.FOGMODE_NONE;
  24108. /**
  24109. * Gets or sets the fog color to use
  24110. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24111. */
  24112. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24113. /**
  24114. * Gets or sets the fog density to use
  24115. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24116. */
  24117. this.fogDensity = 0.1;
  24118. /**
  24119. * Gets or sets the fog start distance to use
  24120. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24121. */
  24122. this.fogStart = 0;
  24123. /**
  24124. * Gets or sets the fog end distance to use
  24125. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24126. */
  24127. this.fogEnd = 1000.0;
  24128. // Lights
  24129. this._shadowsEnabled = true;
  24130. this._lightsEnabled = true;
  24131. /**
  24132. * All of the lights added to this scene
  24133. * @see http://doc.babylonjs.com/babylon101/lights
  24134. */
  24135. this.lights = new Array();
  24136. // Cameras
  24137. /** All of the cameras added to this scene.
  24138. * @see http://doc.babylonjs.com/babylon101/cameras
  24139. */
  24140. this.cameras = new Array();
  24141. /** All of the active cameras added to this scene. */
  24142. this.activeCameras = new Array();
  24143. // Meshes
  24144. /**
  24145. * All of the tranform nodes added to this scene
  24146. * @see http://doc.babylonjs.com/how_to/transformnode
  24147. */
  24148. this.transformNodes = new Array();
  24149. /**
  24150. * All of the (abstract) meshes added to this scene
  24151. */
  24152. this.meshes = new Array();
  24153. /**
  24154. * All of the animation groups added to this scene
  24155. * @see http://doc.babylonjs.com/how_to/group
  24156. */
  24157. this.animationGroups = new Array();
  24158. // Geometries
  24159. this._geometries = new Array();
  24160. /**
  24161. * All of the materials added to this scene
  24162. * @see http://doc.babylonjs.com/babylon101/materials
  24163. */
  24164. this.materials = new Array();
  24165. /**
  24166. * All of the multi-materials added to this scene
  24167. * @see http://doc.babylonjs.com/how_to/multi_materials
  24168. */
  24169. this.multiMaterials = new Array();
  24170. // Textures
  24171. this._texturesEnabled = true;
  24172. /**
  24173. * All of the textures added to this scene
  24174. */
  24175. this.textures = new Array();
  24176. // Particles
  24177. /**
  24178. * Gets or sets a boolean indicating if particles are enabled on this scene
  24179. */
  24180. this.particlesEnabled = true;
  24181. /**
  24182. * All of the particle systems added to this scene
  24183. * @see http://doc.babylonjs.com/babylon101/particles
  24184. */
  24185. this.particleSystems = new Array();
  24186. // Sprites
  24187. /**
  24188. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24189. */
  24190. this.spritesEnabled = true;
  24191. /**
  24192. * All of the sprite managers added to this scene
  24193. * @see http://doc.babylonjs.com/babylon101/sprites
  24194. */
  24195. this.spriteManagers = new Array();
  24196. /**
  24197. * The list of layers (background and foreground) of the scene
  24198. */
  24199. this.layers = new Array();
  24200. /**
  24201. * The list of effect layers (highlights/glow) added to the scene
  24202. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24203. * @see http://doc.babylonjs.com/how_to/glow_layer
  24204. */
  24205. this.effectLayers = new Array();
  24206. // Skeletons
  24207. this._skeletonsEnabled = true;
  24208. /**
  24209. * The list of skeletons added to the scene
  24210. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24211. */
  24212. this.skeletons = new Array();
  24213. // Morph targets
  24214. /**
  24215. * The list of morph target managers added to the scene
  24216. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24217. */
  24218. this.morphTargetManagers = new Array();
  24219. // Lens flares
  24220. /**
  24221. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24222. */
  24223. this.lensFlaresEnabled = true;
  24224. /**
  24225. * The list of lens flare system added to the scene
  24226. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24227. */
  24228. this.lensFlareSystems = new Array();
  24229. // Collisions
  24230. /**
  24231. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24232. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24233. */
  24234. this.collisionsEnabled = true;
  24235. /**
  24236. * Defines the gravity applied to this scene (used only for collisions)
  24237. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24238. */
  24239. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24240. // Postprocesses
  24241. /**
  24242. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24243. */
  24244. this.postProcessesEnabled = true;
  24245. /**
  24246. * The list of postprocesses added to the scene
  24247. */
  24248. this.postProcesses = new Array();
  24249. // Customs render targets
  24250. /**
  24251. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24252. */
  24253. this.renderTargetsEnabled = true;
  24254. /**
  24255. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24256. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24257. */
  24258. this.dumpNextRenderTargets = false;
  24259. /**
  24260. * The list of user defined render targets added to the scene
  24261. */
  24262. this.customRenderTargets = new Array();
  24263. /**
  24264. * Gets the list of meshes imported to the scene through SceneLoader
  24265. */
  24266. this.importedMeshesFiles = new Array();
  24267. // Probes
  24268. /**
  24269. * Gets or sets a boolean indicating if probes are enabled on this scene
  24270. */
  24271. this.probesEnabled = true;
  24272. /**
  24273. * The list of reflection probes added to the scene
  24274. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24275. */
  24276. this.reflectionProbes = new Array();
  24277. /** @hidden */
  24278. this._actionManagers = new Array();
  24279. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24280. // Procedural textures
  24281. /**
  24282. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24283. */
  24284. this.proceduralTexturesEnabled = true;
  24285. /**
  24286. * The list of procedural textures added to the scene
  24287. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24288. */
  24289. this.proceduralTextures = new Array();
  24290. /**
  24291. * The list of sound tracks added to the scene
  24292. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24293. */
  24294. this.soundTracks = new Array();
  24295. this._audioEnabled = true;
  24296. this._headphone = false;
  24297. // Performance counters
  24298. this._totalVertices = new BABYLON.PerfCounter();
  24299. /** @hidden */
  24300. this._activeIndices = new BABYLON.PerfCounter();
  24301. /** @hidden */
  24302. this._activeParticles = new BABYLON.PerfCounter();
  24303. /** @hidden */
  24304. this._activeBones = new BABYLON.PerfCounter();
  24305. this._animationTime = 0;
  24306. /**
  24307. * Gets or sets a general scale for animation speed
  24308. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24309. */
  24310. this.animationTimeScale = 1;
  24311. this._renderId = 0;
  24312. this._executeWhenReadyTimeoutId = -1;
  24313. this._intermediateRendering = false;
  24314. this._viewUpdateFlag = -1;
  24315. this._projectionUpdateFlag = -1;
  24316. this._alternateViewUpdateFlag = -1;
  24317. this._alternateProjectionUpdateFlag = -1;
  24318. /** @hidden */
  24319. this._toBeDisposed = new BABYLON.SmartArray(256);
  24320. this._activeRequests = new Array();
  24321. this._pendingData = new Array();
  24322. this._isDisposed = false;
  24323. /**
  24324. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24325. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24326. */
  24327. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24328. this._activeMeshes = new BABYLON.SmartArray(256);
  24329. this._processedMaterials = new BABYLON.SmartArray(256);
  24330. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24331. /** @hidden */
  24332. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24333. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24334. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24335. /** @hidden */
  24336. this._activeAnimatables = new Array();
  24337. this._transformMatrix = BABYLON.Matrix.Zero();
  24338. this._useAlternateCameraConfiguration = false;
  24339. this._alternateRendering = false;
  24340. /**
  24341. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24342. * This is useful if there are more lights that the maximum simulteanous authorized
  24343. */
  24344. this.requireLightSorting = false;
  24345. this._depthRenderer = {};
  24346. this._activeMeshesFrozen = false;
  24347. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24348. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24349. this._engine.scenes.push(this);
  24350. this._uid = null;
  24351. this._renderingManager = new BABYLON.RenderingManager(this);
  24352. if (BABYLON.PostProcessManager) {
  24353. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24354. }
  24355. if (BABYLON.OutlineRenderer) {
  24356. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24357. }
  24358. if (BABYLON.Tools.IsWindowObjectExist()) {
  24359. this.attachControl();
  24360. }
  24361. //simplification queue
  24362. if (BABYLON.SimplificationQueue) {
  24363. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24364. }
  24365. //collision coordinator initialization. For now legacy per default.
  24366. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24367. // Uniform Buffer
  24368. this._createUbo();
  24369. // Default Image processing definition
  24370. if (BABYLON.ImageProcessingConfiguration) {
  24371. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24372. }
  24373. }
  24374. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24375. /** The fog is deactivated */
  24376. get: function () {
  24377. return Scene._FOGMODE_NONE;
  24378. },
  24379. enumerable: true,
  24380. configurable: true
  24381. });
  24382. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24383. /** The fog density is following an exponential function */
  24384. get: function () {
  24385. return Scene._FOGMODE_EXP;
  24386. },
  24387. enumerable: true,
  24388. configurable: true
  24389. });
  24390. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24391. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24392. get: function () {
  24393. return Scene._FOGMODE_EXP2;
  24394. },
  24395. enumerable: true,
  24396. configurable: true
  24397. });
  24398. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24399. /** The fog density is following a linear function. */
  24400. get: function () {
  24401. return Scene._FOGMODE_LINEAR;
  24402. },
  24403. enumerable: true,
  24404. configurable: true
  24405. });
  24406. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24407. /**
  24408. * Texture used in all pbr material as the reflection texture.
  24409. * As in the majority of the scene they are the same (exception for multi room and so on),
  24410. * this is easier to reference from here than from all the materials.
  24411. */
  24412. get: function () {
  24413. return this._environmentTexture;
  24414. },
  24415. /**
  24416. * Texture used in all pbr material as the reflection texture.
  24417. * As in the majority of the scene they are the same (exception for multi room and so on),
  24418. * this is easier to set here than in all the materials.
  24419. */
  24420. set: function (value) {
  24421. if (this._environmentTexture === value) {
  24422. return;
  24423. }
  24424. this._environmentTexture = value;
  24425. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24426. },
  24427. enumerable: true,
  24428. configurable: true
  24429. });
  24430. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24431. /**
  24432. * Default image processing configuration used either in the rendering
  24433. * Forward main pass or through the imageProcessingPostProcess if present.
  24434. * As in the majority of the scene they are the same (exception for multi camera),
  24435. * this is easier to reference from here than from all the materials and post process.
  24436. *
  24437. * No setter as we it is a shared configuration, you can set the values instead.
  24438. */
  24439. get: function () {
  24440. return this._imageProcessingConfiguration;
  24441. },
  24442. enumerable: true,
  24443. configurable: true
  24444. });
  24445. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24446. get: function () {
  24447. return this._forceWireframe;
  24448. },
  24449. /**
  24450. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24451. */
  24452. set: function (value) {
  24453. if (this._forceWireframe === value) {
  24454. return;
  24455. }
  24456. this._forceWireframe = value;
  24457. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24458. },
  24459. enumerable: true,
  24460. configurable: true
  24461. });
  24462. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24463. get: function () {
  24464. return this._forcePointsCloud;
  24465. },
  24466. /**
  24467. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24468. */
  24469. set: function (value) {
  24470. if (this._forcePointsCloud === value) {
  24471. return;
  24472. }
  24473. this._forcePointsCloud = value;
  24474. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24475. },
  24476. enumerable: true,
  24477. configurable: true
  24478. });
  24479. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24480. /**
  24481. * Gets or sets the animation properties override
  24482. */
  24483. get: function () {
  24484. return this._animationPropertiesOverride;
  24485. },
  24486. set: function (value) {
  24487. this._animationPropertiesOverride = value;
  24488. },
  24489. enumerable: true,
  24490. configurable: true
  24491. });
  24492. Object.defineProperty(Scene.prototype, "onDispose", {
  24493. /** Sets a function to be executed when this scene is disposed. */
  24494. set: function (callback) {
  24495. if (this._onDisposeObserver) {
  24496. this.onDisposeObservable.remove(this._onDisposeObserver);
  24497. }
  24498. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24499. },
  24500. enumerable: true,
  24501. configurable: true
  24502. });
  24503. Object.defineProperty(Scene.prototype, "beforeRender", {
  24504. /** Sets a function to be executed before rendering this scene */
  24505. set: function (callback) {
  24506. if (this._onBeforeRenderObserver) {
  24507. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24508. }
  24509. if (callback) {
  24510. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24511. }
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "afterRender", {
  24517. /** Sets a function to be executed after rendering this scene */
  24518. set: function (callback) {
  24519. if (this._onAfterRenderObserver) {
  24520. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24521. }
  24522. if (callback) {
  24523. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24524. }
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24530. /** Sets a function to be executed before rendering a camera*/
  24531. set: function (callback) {
  24532. if (this._onBeforeCameraRenderObserver) {
  24533. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24534. }
  24535. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24541. /** Sets a function to be executed after rendering a camera*/
  24542. set: function (callback) {
  24543. if (this._onAfterCameraRenderObserver) {
  24544. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24545. }
  24546. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24547. },
  24548. enumerable: true,
  24549. configurable: true
  24550. });
  24551. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24552. /**
  24553. * Gets the gamepad manager associated with the scene
  24554. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24555. */
  24556. get: function () {
  24557. if (!this._gamepadManager) {
  24558. this._gamepadManager = new BABYLON.GamepadManager(this);
  24559. }
  24560. return this._gamepadManager;
  24561. },
  24562. enumerable: true,
  24563. configurable: true
  24564. });
  24565. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24566. /**
  24567. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24568. */
  24569. get: function () {
  24570. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24571. },
  24572. enumerable: true,
  24573. configurable: true
  24574. });
  24575. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24576. get: function () {
  24577. return this._useRightHandedSystem;
  24578. },
  24579. /**
  24580. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24581. */
  24582. set: function (value) {
  24583. if (this._useRightHandedSystem === value) {
  24584. return;
  24585. }
  24586. this._useRightHandedSystem = value;
  24587. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. /**
  24593. * Sets the step Id used by deterministic lock step
  24594. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24595. * @param newStepId defines the step Id
  24596. */
  24597. Scene.prototype.setStepId = function (newStepId) {
  24598. this._currentStepId = newStepId;
  24599. };
  24600. ;
  24601. /**
  24602. * Gets the step Id used by deterministic lock step
  24603. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24604. * @returns the step Id
  24605. */
  24606. Scene.prototype.getStepId = function () {
  24607. return this._currentStepId;
  24608. };
  24609. ;
  24610. /**
  24611. * Gets the internal step used by deterministic lock step
  24612. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24613. * @returns the internal step
  24614. */
  24615. Scene.prototype.getInternalStep = function () {
  24616. return this._currentInternalStep;
  24617. };
  24618. ;
  24619. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24620. get: function () {
  24621. return this._fogEnabled;
  24622. },
  24623. /**
  24624. * Gets or sets a boolean indicating if fog is enabled on this scene
  24625. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24626. */
  24627. set: function (value) {
  24628. if (this._fogEnabled === value) {
  24629. return;
  24630. }
  24631. this._fogEnabled = value;
  24632. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24633. },
  24634. enumerable: true,
  24635. configurable: true
  24636. });
  24637. Object.defineProperty(Scene.prototype, "fogMode", {
  24638. get: function () {
  24639. return this._fogMode;
  24640. },
  24641. /**
  24642. * Gets or sets the fog mode to use
  24643. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24644. */
  24645. set: function (value) {
  24646. if (this._fogMode === value) {
  24647. return;
  24648. }
  24649. this._fogMode = value;
  24650. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24656. get: function () {
  24657. return this._shadowsEnabled;
  24658. },
  24659. /**
  24660. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24661. */
  24662. set: function (value) {
  24663. if (this._shadowsEnabled === value) {
  24664. return;
  24665. }
  24666. this._shadowsEnabled = value;
  24667. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24673. get: function () {
  24674. return this._lightsEnabled;
  24675. },
  24676. /**
  24677. * Gets or sets a boolean indicating if lights are enabled on this scene
  24678. */
  24679. set: function (value) {
  24680. if (this._lightsEnabled === value) {
  24681. return;
  24682. }
  24683. this._lightsEnabled = value;
  24684. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24685. },
  24686. enumerable: true,
  24687. configurable: true
  24688. });
  24689. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24690. /** The default material used on meshes when no material is affected */
  24691. get: function () {
  24692. if (!this._defaultMaterial) {
  24693. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24694. }
  24695. return this._defaultMaterial;
  24696. },
  24697. /** The default material used on meshes when no material is affected */
  24698. set: function (value) {
  24699. this._defaultMaterial = value;
  24700. },
  24701. enumerable: true,
  24702. configurable: true
  24703. });
  24704. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24705. get: function () {
  24706. return this._texturesEnabled;
  24707. },
  24708. /**
  24709. * Gets or sets a boolean indicating if textures are enabled on this scene
  24710. */
  24711. set: function (value) {
  24712. if (this._texturesEnabled === value) {
  24713. return;
  24714. }
  24715. this._texturesEnabled = value;
  24716. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24717. },
  24718. enumerable: true,
  24719. configurable: true
  24720. });
  24721. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24722. get: function () {
  24723. return this._skeletonsEnabled;
  24724. },
  24725. /**
  24726. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24727. */
  24728. set: function (value) {
  24729. if (this._skeletonsEnabled === value) {
  24730. return;
  24731. }
  24732. this._skeletonsEnabled = value;
  24733. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24739. /**
  24740. * Gets the postprocess render pipeline manager
  24741. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24742. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24743. */
  24744. get: function () {
  24745. if (!this._postProcessRenderPipelineManager) {
  24746. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24747. }
  24748. return this._postProcessRenderPipelineManager;
  24749. },
  24750. enumerable: true,
  24751. configurable: true
  24752. });
  24753. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24754. /**
  24755. * Gets the main soundtrack associated with the scene
  24756. */
  24757. get: function () {
  24758. if (!this._mainSoundTrack) {
  24759. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24760. }
  24761. return this._mainSoundTrack;
  24762. },
  24763. enumerable: true,
  24764. configurable: true
  24765. });
  24766. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24767. /** @hidden */
  24768. get: function () {
  24769. return this._alternateRendering;
  24770. },
  24771. enumerable: true,
  24772. configurable: true
  24773. });
  24774. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24775. /**
  24776. * Gets the list of frustum planes (built from the active camera)
  24777. */
  24778. get: function () {
  24779. return this._frustumPlanes;
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24785. /**
  24786. * Gets the current geometry buffer associated to the scene.
  24787. */
  24788. get: function () {
  24789. return this._geometryBufferRenderer;
  24790. },
  24791. /**
  24792. * Sets the current geometry buffer for the scene.
  24793. */
  24794. set: function (geometryBufferRenderer) {
  24795. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24796. this._geometryBufferRenderer = geometryBufferRenderer;
  24797. }
  24798. },
  24799. enumerable: true,
  24800. configurable: true
  24801. });
  24802. Object.defineProperty(Scene.prototype, "debugLayer", {
  24803. /**
  24804. * Gets the debug layer (aka Inspector) associated with the scene
  24805. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24806. */
  24807. get: function () {
  24808. if (!this._debugLayer) {
  24809. this._debugLayer = new BABYLON.DebugLayer(this);
  24810. }
  24811. return this._debugLayer;
  24812. },
  24813. enumerable: true,
  24814. configurable: true
  24815. });
  24816. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24817. /**
  24818. * Gets a boolean indicating if collisions are processed on a web worker
  24819. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24820. */
  24821. get: function () {
  24822. return this._workerCollisions;
  24823. },
  24824. set: function (enabled) {
  24825. if (!BABYLON.CollisionCoordinatorLegacy) {
  24826. return;
  24827. }
  24828. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24829. this._workerCollisions = enabled;
  24830. if (this.collisionCoordinator) {
  24831. this.collisionCoordinator.destroy();
  24832. }
  24833. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24834. this.collisionCoordinator.init(this);
  24835. },
  24836. enumerable: true,
  24837. configurable: true
  24838. });
  24839. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24840. /**
  24841. * Gets the octree used to boost mesh selection (picking)
  24842. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24843. */
  24844. get: function () {
  24845. return this._selectionOctree;
  24846. },
  24847. enumerable: true,
  24848. configurable: true
  24849. });
  24850. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24851. /**
  24852. * Gets the mesh that is currently under the pointer
  24853. */
  24854. get: function () {
  24855. return this._pointerOverMesh;
  24856. },
  24857. enumerable: true,
  24858. configurable: true
  24859. });
  24860. Object.defineProperty(Scene.prototype, "pointerX", {
  24861. /**
  24862. * Gets the current on-screen X position of the pointer
  24863. */
  24864. get: function () {
  24865. return this._pointerX;
  24866. },
  24867. enumerable: true,
  24868. configurable: true
  24869. });
  24870. Object.defineProperty(Scene.prototype, "pointerY", {
  24871. /**
  24872. * Gets the current on-screen Y position of the pointer
  24873. */
  24874. get: function () {
  24875. return this._pointerY;
  24876. },
  24877. enumerable: true,
  24878. configurable: true
  24879. });
  24880. /**
  24881. * Gets the cached material (ie. the latest rendered one)
  24882. * @returns the cached material
  24883. */
  24884. Scene.prototype.getCachedMaterial = function () {
  24885. return this._cachedMaterial;
  24886. };
  24887. /**
  24888. * Gets the cached effect (ie. the latest rendered one)
  24889. * @returns the cached effect
  24890. */
  24891. Scene.prototype.getCachedEffect = function () {
  24892. return this._cachedEffect;
  24893. };
  24894. /**
  24895. * Gets the cached visibility state (ie. the latest rendered one)
  24896. * @returns the cached visibility state
  24897. */
  24898. Scene.prototype.getCachedVisibility = function () {
  24899. return this._cachedVisibility;
  24900. };
  24901. /**
  24902. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24903. * @param material defines the current material
  24904. * @param effect defines the current effect
  24905. * @param visibility defines the current visibility state
  24906. * @returns true if one parameter is not cached
  24907. */
  24908. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24909. if (visibility === void 0) { visibility = 1; }
  24910. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24911. };
  24912. /**
  24913. * Gets the bounding box renderer associated with the scene
  24914. * @returns a BoundingBoxRenderer
  24915. */
  24916. Scene.prototype.getBoundingBoxRenderer = function () {
  24917. if (!this._boundingBoxRenderer) {
  24918. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24919. }
  24920. return this._boundingBoxRenderer;
  24921. };
  24922. /**
  24923. * Gets the outline renderer associated with the scene
  24924. * @returns a OutlineRenderer
  24925. */
  24926. Scene.prototype.getOutlineRenderer = function () {
  24927. return this._outlineRenderer;
  24928. };
  24929. /**
  24930. * Gets the engine associated with the scene
  24931. * @returns an Engine
  24932. */
  24933. Scene.prototype.getEngine = function () {
  24934. return this._engine;
  24935. };
  24936. /**
  24937. * Gets the total number of vertices rendered per frame
  24938. * @returns the total number of vertices rendered per frame
  24939. */
  24940. Scene.prototype.getTotalVertices = function () {
  24941. return this._totalVertices.current;
  24942. };
  24943. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24944. /**
  24945. * Gets the performance counter for total vertices
  24946. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24947. */
  24948. get: function () {
  24949. return this._totalVertices;
  24950. },
  24951. enumerable: true,
  24952. configurable: true
  24953. });
  24954. /**
  24955. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24956. * @returns the total number of active indices rendered per frame
  24957. */
  24958. Scene.prototype.getActiveIndices = function () {
  24959. return this._activeIndices.current;
  24960. };
  24961. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24962. /**
  24963. * Gets the performance counter for active indices
  24964. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24965. */
  24966. get: function () {
  24967. return this._activeIndices;
  24968. },
  24969. enumerable: true,
  24970. configurable: true
  24971. });
  24972. /**
  24973. * Gets the total number of active particles rendered per frame
  24974. * @returns the total number of active particles rendered per frame
  24975. */
  24976. Scene.prototype.getActiveParticles = function () {
  24977. return this._activeParticles.current;
  24978. };
  24979. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24980. /**
  24981. * Gets the performance counter for active particles
  24982. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24983. */
  24984. get: function () {
  24985. return this._activeParticles;
  24986. },
  24987. enumerable: true,
  24988. configurable: true
  24989. });
  24990. /**
  24991. * Gets the total number of active bones rendered per frame
  24992. * @returns the total number of active bones rendered per frame
  24993. */
  24994. Scene.prototype.getActiveBones = function () {
  24995. return this._activeBones.current;
  24996. };
  24997. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24998. /**
  24999. * Gets the performance counter for active bones
  25000. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25001. */
  25002. get: function () {
  25003. return this._activeBones;
  25004. },
  25005. enumerable: true,
  25006. configurable: true
  25007. });
  25008. /** @hidden */
  25009. Scene.prototype.getInterFramePerfCounter = function () {
  25010. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25011. return 0;
  25012. };
  25013. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25014. /** @hidden */
  25015. get: function () {
  25016. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25017. return null;
  25018. },
  25019. enumerable: true,
  25020. configurable: true
  25021. });
  25022. /** @hidden */
  25023. Scene.prototype.getLastFrameDuration = function () {
  25024. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25025. return 0;
  25026. };
  25027. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25028. /** @hidden */
  25029. get: function () {
  25030. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25031. return null;
  25032. },
  25033. enumerable: true,
  25034. configurable: true
  25035. });
  25036. /** @hidden */
  25037. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25038. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25039. return 0;
  25040. };
  25041. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25042. /** @hidden */
  25043. get: function () {
  25044. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25045. return null;
  25046. },
  25047. enumerable: true,
  25048. configurable: true
  25049. });
  25050. /**
  25051. * Gets the array of active meshes
  25052. * @returns an array of AbstractMesh
  25053. */
  25054. Scene.prototype.getActiveMeshes = function () {
  25055. return this._activeMeshes;
  25056. };
  25057. /** @hidden */
  25058. Scene.prototype.getRenderTargetsDuration = function () {
  25059. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25060. return 0;
  25061. };
  25062. /** @hidden */
  25063. Scene.prototype.getRenderDuration = function () {
  25064. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25065. return 0;
  25066. };
  25067. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25068. /** @hidden */
  25069. get: function () {
  25070. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25071. return null;
  25072. },
  25073. enumerable: true,
  25074. configurable: true
  25075. });
  25076. /** @hidden */
  25077. Scene.prototype.getParticlesDuration = function () {
  25078. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25079. return 0;
  25080. };
  25081. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25082. /** @hidden */
  25083. get: function () {
  25084. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25085. return null;
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. /** @hidden */
  25091. Scene.prototype.getSpritesDuration = function () {
  25092. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25093. return 0;
  25094. };
  25095. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25096. /** @hidden */
  25097. get: function () {
  25098. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25099. return null;
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. /**
  25105. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25106. * @returns a number
  25107. */
  25108. Scene.prototype.getAnimationRatio = function () {
  25109. return this._animationRatio;
  25110. };
  25111. /**
  25112. * Gets an unique Id for the current frame
  25113. * @returns a number
  25114. */
  25115. Scene.prototype.getRenderId = function () {
  25116. return this._renderId;
  25117. };
  25118. /** Call this function if you want to manually increment the render Id*/
  25119. Scene.prototype.incrementRenderId = function () {
  25120. this._renderId++;
  25121. };
  25122. Scene.prototype._updatePointerPosition = function (evt) {
  25123. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25124. if (!canvasRect) {
  25125. return;
  25126. }
  25127. this._pointerX = evt.clientX - canvasRect.left;
  25128. this._pointerY = evt.clientY - canvasRect.top;
  25129. this._unTranslatedPointerX = this._pointerX;
  25130. this._unTranslatedPointerY = this._pointerY;
  25131. };
  25132. Scene.prototype._createUbo = function () {
  25133. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25134. this._sceneUbo.addUniform("viewProjection", 16);
  25135. this._sceneUbo.addUniform("view", 16);
  25136. };
  25137. Scene.prototype._createAlternateUbo = function () {
  25138. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25139. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25140. this._alternateSceneUbo.addUniform("view", 16);
  25141. };
  25142. // Pointers handling
  25143. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25144. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25145. if (result) {
  25146. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25147. }
  25148. return result;
  25149. };
  25150. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25151. if (pointerInfo.pickInfo) {
  25152. if (!pointerInfo.pickInfo.ray) {
  25153. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25154. }
  25155. }
  25156. };
  25157. /**
  25158. * Use this method to simulate a pointer move on a mesh
  25159. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25160. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25161. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25162. * @returns the current scene
  25163. */
  25164. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25165. var evt = new PointerEvent("pointermove", pointerEventInit);
  25166. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25167. return this;
  25168. }
  25169. return this._processPointerMove(pickResult, evt);
  25170. };
  25171. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25172. var canvas = this._engine.getRenderingCanvas();
  25173. if (!canvas) {
  25174. return this;
  25175. }
  25176. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25177. this.setPointerOverSprite(null);
  25178. this.setPointerOverMesh(pickResult.pickedMesh);
  25179. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25180. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25181. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25182. }
  25183. else {
  25184. canvas.style.cursor = this.hoverCursor;
  25185. }
  25186. }
  25187. else {
  25188. canvas.style.cursor = this.defaultCursor;
  25189. }
  25190. }
  25191. else {
  25192. this.setPointerOverMesh(null);
  25193. // Sprites
  25194. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25195. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25196. this.setPointerOverSprite(pickResult.pickedSprite);
  25197. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25198. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25199. }
  25200. else {
  25201. canvas.style.cursor = this.hoverCursor;
  25202. }
  25203. }
  25204. else {
  25205. this.setPointerOverSprite(null);
  25206. // Restore pointer
  25207. canvas.style.cursor = this.defaultCursor;
  25208. }
  25209. }
  25210. if (pickResult) {
  25211. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25212. if (this.onPointerMove) {
  25213. this.onPointerMove(evt, pickResult, type);
  25214. }
  25215. if (this.onPointerObservable.hasObservers()) {
  25216. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25217. this._setRayOnPointerInfo(pi);
  25218. this.onPointerObservable.notifyObservers(pi, type);
  25219. }
  25220. }
  25221. return this;
  25222. };
  25223. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25224. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25225. if (pickResult) {
  25226. pi.ray = pickResult.ray;
  25227. }
  25228. this.onPrePointerObservable.notifyObservers(pi, type);
  25229. if (pi.skipOnPointerObservable) {
  25230. return true;
  25231. }
  25232. else {
  25233. return false;
  25234. }
  25235. };
  25236. /**
  25237. * Use this method to simulate a pointer down on a mesh
  25238. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25239. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25240. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25241. * @returns the current scene
  25242. */
  25243. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25244. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25245. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25246. return this;
  25247. }
  25248. return this._processPointerDown(pickResult, evt);
  25249. };
  25250. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25251. var _this = this;
  25252. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25253. this._pickedDownMesh = pickResult.pickedMesh;
  25254. var actionManager = pickResult.pickedMesh.actionManager;
  25255. if (actionManager) {
  25256. if (actionManager.hasPickTriggers) {
  25257. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25258. switch (evt.button) {
  25259. case 0:
  25260. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25261. break;
  25262. case 1:
  25263. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25264. break;
  25265. case 2:
  25266. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25267. break;
  25268. }
  25269. }
  25270. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25271. window.setTimeout(function () {
  25272. 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);
  25273. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25274. if (_this._totalPointersPressed !== 0 &&
  25275. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25276. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25277. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25278. _this._startingPointerTime = 0;
  25279. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25280. }
  25281. }
  25282. }, Scene.LongPressDelay);
  25283. }
  25284. }
  25285. }
  25286. if (pickResult) {
  25287. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25288. if (this.onPointerDown) {
  25289. this.onPointerDown(evt, pickResult, type);
  25290. }
  25291. if (this.onPointerObservable.hasObservers()) {
  25292. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25293. this._setRayOnPointerInfo(pi);
  25294. this.onPointerObservable.notifyObservers(pi, type);
  25295. }
  25296. }
  25297. return this;
  25298. };
  25299. /**
  25300. * Use this method to simulate a pointer up on a mesh
  25301. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25302. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25303. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25304. * @returns the current scene
  25305. */
  25306. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25307. var evt = new PointerEvent("pointerup", pointerEventInit);
  25308. var clickInfo = new ClickInfo();
  25309. clickInfo.singleClick = true;
  25310. clickInfo.ignore = true;
  25311. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25312. return this;
  25313. }
  25314. return this._processPointerUp(pickResult, evt, clickInfo);
  25315. };
  25316. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25317. if (pickResult && pickResult && pickResult.pickedMesh) {
  25318. this._pickedUpMesh = pickResult.pickedMesh;
  25319. if (this._pickedDownMesh === this._pickedUpMesh) {
  25320. if (this.onPointerPick) {
  25321. this.onPointerPick(evt, pickResult);
  25322. }
  25323. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25324. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25325. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25326. this._setRayOnPointerInfo(pi);
  25327. this.onPointerObservable.notifyObservers(pi, type_1);
  25328. }
  25329. }
  25330. if (pickResult.pickedMesh.actionManager) {
  25331. if (clickInfo.ignore) {
  25332. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25333. }
  25334. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25335. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25336. }
  25337. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25338. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25339. }
  25340. }
  25341. }
  25342. if (this._pickedDownMesh &&
  25343. this._pickedDownMesh.actionManager &&
  25344. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25345. this._pickedDownMesh !== this._pickedUpMesh) {
  25346. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25347. }
  25348. var type = BABYLON.PointerEventTypes.POINTERUP;
  25349. if (this.onPointerObservable.hasObservers()) {
  25350. if (!clickInfo.ignore) {
  25351. if (!clickInfo.hasSwiped) {
  25352. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25353. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25354. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25355. this._setRayOnPointerInfo(pi);
  25356. this.onPointerObservable.notifyObservers(pi, type_2);
  25357. }
  25358. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25359. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25360. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25361. this._setRayOnPointerInfo(pi);
  25362. this.onPointerObservable.notifyObservers(pi, type_3);
  25363. }
  25364. }
  25365. }
  25366. else {
  25367. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25368. this._setRayOnPointerInfo(pi);
  25369. this.onPointerObservable.notifyObservers(pi, type);
  25370. }
  25371. }
  25372. if (this.onPointerUp) {
  25373. this.onPointerUp(evt, pickResult, type);
  25374. }
  25375. return this;
  25376. };
  25377. /**
  25378. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25379. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25380. * @returns true if the pointer was captured
  25381. */
  25382. Scene.prototype.isPointerCaptured = function (pointerId) {
  25383. if (pointerId === void 0) { pointerId = 0; }
  25384. return this._pointerCaptures[pointerId];
  25385. };
  25386. /**
  25387. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25388. * @param attachUp defines if you want to attach events to pointerup
  25389. * @param attachDown defines if you want to attach events to pointerdown
  25390. * @param attachMove defines if you want to attach events to pointermove
  25391. */
  25392. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25393. var _this = this;
  25394. if (attachUp === void 0) { attachUp = true; }
  25395. if (attachDown === void 0) { attachDown = true; }
  25396. if (attachMove === void 0) { attachMove = true; }
  25397. this._initActionManager = function (act, clickInfo) {
  25398. if (!_this._meshPickProceed) {
  25399. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25400. _this._currentPickResult = pickResult;
  25401. if (pickResult) {
  25402. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25403. }
  25404. _this._meshPickProceed = true;
  25405. }
  25406. return act;
  25407. };
  25408. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25409. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25410. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25411. btn !== _this._previousButtonPressed) {
  25412. _this._doubleClickOccured = false;
  25413. clickInfo.singleClick = true;
  25414. clickInfo.ignore = false;
  25415. cb(clickInfo, _this._currentPickResult);
  25416. }
  25417. };
  25418. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25419. var clickInfo = new ClickInfo();
  25420. _this._currentPickResult = null;
  25421. var act = null;
  25422. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25423. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25424. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25425. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25426. act = _this._initActionManager(act, clickInfo);
  25427. if (act)
  25428. checkPicking = act.hasPickTriggers;
  25429. }
  25430. if (checkPicking) {
  25431. var btn = evt.button;
  25432. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25433. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25434. if (!clickInfo.hasSwiped) {
  25435. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25436. if (!checkSingleClickImmediately) {
  25437. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25438. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25439. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25440. act = _this._initActionManager(act, clickInfo);
  25441. if (act)
  25442. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25443. }
  25444. }
  25445. if (checkSingleClickImmediately) {
  25446. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25447. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25448. btn !== _this._previousButtonPressed) {
  25449. clickInfo.singleClick = true;
  25450. cb(clickInfo, _this._currentPickResult);
  25451. }
  25452. }
  25453. // at least one double click is required to be check and exclusive double click is enabled
  25454. else {
  25455. // wait that no double click has been raised during the double click delay
  25456. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25457. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25458. }
  25459. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25460. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25461. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25462. act = _this._initActionManager(act, clickInfo);
  25463. if (act)
  25464. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25465. }
  25466. if (checkDoubleClick) {
  25467. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25468. if (btn === _this._previousButtonPressed &&
  25469. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25470. !_this._doubleClickOccured) {
  25471. // pointer has not moved for 2 clicks, it's a double click
  25472. if (!clickInfo.hasSwiped &&
  25473. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25474. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25475. _this._previousStartingPointerTime = 0;
  25476. _this._doubleClickOccured = true;
  25477. clickInfo.doubleClick = true;
  25478. clickInfo.ignore = false;
  25479. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25480. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25481. }
  25482. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25483. cb(clickInfo, _this._currentPickResult);
  25484. }
  25485. // if the two successive clicks are too far, it's just two simple clicks
  25486. else {
  25487. _this._doubleClickOccured = false;
  25488. _this._previousStartingPointerTime = _this._startingPointerTime;
  25489. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25490. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25491. _this._previousButtonPressed = btn;
  25492. if (Scene.ExclusiveDoubleClickMode) {
  25493. if (_this._previousDelayedSimpleClickTimeout) {
  25494. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25495. }
  25496. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25497. cb(clickInfo, _this._previousPickResult);
  25498. }
  25499. else {
  25500. cb(clickInfo, _this._currentPickResult);
  25501. }
  25502. }
  25503. }
  25504. // just the first click of the double has been raised
  25505. else {
  25506. _this._doubleClickOccured = false;
  25507. _this._previousStartingPointerTime = _this._startingPointerTime;
  25508. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25509. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25510. _this._previousButtonPressed = btn;
  25511. }
  25512. }
  25513. }
  25514. }
  25515. clickInfo.ignore = true;
  25516. cb(clickInfo, _this._currentPickResult);
  25517. };
  25518. this._spritePredicate = function (sprite) {
  25519. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25520. };
  25521. this._onPointerMove = function (evt) {
  25522. _this._updatePointerPosition(evt);
  25523. // PreObservable support
  25524. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25525. return;
  25526. }
  25527. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25528. return;
  25529. }
  25530. if (!_this.pointerMovePredicate) {
  25531. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25532. }
  25533. // Meshes
  25534. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25535. _this._processPointerMove(pickResult, evt);
  25536. };
  25537. this._onPointerDown = function (evt) {
  25538. _this._totalPointersPressed++;
  25539. _this._pickedDownMesh = null;
  25540. _this._meshPickProceed = false;
  25541. _this._updatePointerPosition(evt);
  25542. if (_this.preventDefaultOnPointerDown && canvas) {
  25543. evt.preventDefault();
  25544. canvas.focus();
  25545. }
  25546. // PreObservable support
  25547. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25548. return;
  25549. }
  25550. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25551. return;
  25552. }
  25553. _this._pointerCaptures[evt.pointerId] = true;
  25554. _this._startingPointerPosition.x = _this._pointerX;
  25555. _this._startingPointerPosition.y = _this._pointerY;
  25556. _this._startingPointerTime = Date.now();
  25557. if (!_this.pointerDownPredicate) {
  25558. _this.pointerDownPredicate = function (mesh) {
  25559. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25560. };
  25561. }
  25562. // Meshes
  25563. _this._pickedDownMesh = null;
  25564. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25565. _this._processPointerDown(pickResult, evt);
  25566. // Sprites
  25567. _this._pickedDownSprite = null;
  25568. if (_this.spriteManagers.length > 0) {
  25569. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25570. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25571. if (pickResult.pickedSprite.actionManager) {
  25572. _this._pickedDownSprite = pickResult.pickedSprite;
  25573. switch (evt.button) {
  25574. case 0:
  25575. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25576. break;
  25577. case 1:
  25578. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25579. break;
  25580. case 2:
  25581. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25582. break;
  25583. }
  25584. if (pickResult.pickedSprite.actionManager) {
  25585. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25586. }
  25587. }
  25588. }
  25589. }
  25590. };
  25591. this._onPointerUp = function (evt) {
  25592. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25593. return; // So we need to test it the pointer down was pressed before.
  25594. }
  25595. _this._totalPointersPressed--;
  25596. _this._pickedUpMesh = null;
  25597. _this._meshPickProceed = false;
  25598. _this._updatePointerPosition(evt);
  25599. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25600. // PreObservable support
  25601. if (_this.onPrePointerObservable.hasObservers()) {
  25602. if (!clickInfo.ignore) {
  25603. if (!clickInfo.hasSwiped) {
  25604. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25605. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25606. return;
  25607. }
  25608. }
  25609. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25610. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25611. return;
  25612. }
  25613. }
  25614. }
  25615. }
  25616. else {
  25617. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25618. return;
  25619. }
  25620. }
  25621. }
  25622. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25623. return;
  25624. }
  25625. _this._pointerCaptures[evt.pointerId] = false;
  25626. if (!_this.pointerUpPredicate) {
  25627. _this.pointerUpPredicate = function (mesh) {
  25628. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25629. };
  25630. }
  25631. // Meshes
  25632. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25633. _this._initActionManager(null, clickInfo);
  25634. }
  25635. if (!pickResult) {
  25636. pickResult = _this._currentPickResult;
  25637. }
  25638. _this._processPointerUp(pickResult, evt, clickInfo);
  25639. // Sprites
  25640. if (!clickInfo.ignore) {
  25641. if (_this.spriteManagers.length > 0) {
  25642. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25643. if (spritePickResult) {
  25644. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25645. if (spritePickResult.pickedSprite.actionManager) {
  25646. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25647. if (spritePickResult.pickedSprite.actionManager) {
  25648. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25649. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25650. }
  25651. }
  25652. }
  25653. }
  25654. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25655. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25656. }
  25657. }
  25658. }
  25659. }
  25660. _this._previousPickResult = _this._currentPickResult;
  25661. });
  25662. };
  25663. this._onKeyDown = function (evt) {
  25664. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25665. if (_this.onPreKeyboardObservable.hasObservers()) {
  25666. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25667. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25668. if (pi.skipOnPointerObservable) {
  25669. return;
  25670. }
  25671. }
  25672. if (_this.onKeyboardObservable.hasObservers()) {
  25673. var pi = new BABYLON.KeyboardInfo(type, evt);
  25674. _this.onKeyboardObservable.notifyObservers(pi, type);
  25675. }
  25676. if (_this.actionManager) {
  25677. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25678. }
  25679. };
  25680. this._onKeyUp = function (evt) {
  25681. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25682. if (_this.onPreKeyboardObservable.hasObservers()) {
  25683. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25684. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25685. if (pi.skipOnPointerObservable) {
  25686. return;
  25687. }
  25688. }
  25689. if (_this.onKeyboardObservable.hasObservers()) {
  25690. var pi = new BABYLON.KeyboardInfo(type, evt);
  25691. _this.onKeyboardObservable.notifyObservers(pi, type);
  25692. }
  25693. if (_this.actionManager) {
  25694. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25695. }
  25696. };
  25697. var engine = this.getEngine();
  25698. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25699. if (!canvas) {
  25700. return;
  25701. }
  25702. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25703. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25704. });
  25705. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25706. if (!canvas) {
  25707. return;
  25708. }
  25709. canvas.removeEventListener("keydown", _this._onKeyDown);
  25710. canvas.removeEventListener("keyup", _this._onKeyUp);
  25711. });
  25712. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25713. var canvas = this._engine.getRenderingCanvas();
  25714. if (!canvas) {
  25715. return;
  25716. }
  25717. if (attachMove) {
  25718. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25719. // Wheel
  25720. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25721. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25722. }
  25723. if (attachDown) {
  25724. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25725. }
  25726. if (attachUp) {
  25727. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25728. }
  25729. canvas.tabIndex = 1;
  25730. };
  25731. /** Detaches all event handlers*/
  25732. Scene.prototype.detachControl = function () {
  25733. var engine = this.getEngine();
  25734. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25735. var canvas = engine.getRenderingCanvas();
  25736. if (!canvas) {
  25737. return;
  25738. }
  25739. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25740. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25741. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25742. if (this._onCanvasBlurObserver) {
  25743. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25744. }
  25745. if (this._onCanvasFocusObserver) {
  25746. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25747. }
  25748. // Wheel
  25749. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25750. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25751. // Keyboard
  25752. canvas.removeEventListener("keydown", this._onKeyDown);
  25753. canvas.removeEventListener("keyup", this._onKeyUp);
  25754. // Observables
  25755. this.onKeyboardObservable.clear();
  25756. this.onPreKeyboardObservable.clear();
  25757. this.onPointerObservable.clear();
  25758. this.onPrePointerObservable.clear();
  25759. };
  25760. /**
  25761. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25762. * Delay loaded resources are not taking in account
  25763. * @return true if all required resources are ready
  25764. */
  25765. Scene.prototype.isReady = function () {
  25766. if (this._isDisposed) {
  25767. return false;
  25768. }
  25769. if (this._pendingData.length > 0) {
  25770. return false;
  25771. }
  25772. var index;
  25773. var engine = this.getEngine();
  25774. // Geometries
  25775. for (index = 0; index < this._geometries.length; index++) {
  25776. var geometry = this._geometries[index];
  25777. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25778. return false;
  25779. }
  25780. }
  25781. // Meshes
  25782. for (index = 0; index < this.meshes.length; index++) {
  25783. var mesh = this.meshes[index];
  25784. if (!mesh.isEnabled()) {
  25785. continue;
  25786. }
  25787. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25788. continue;
  25789. }
  25790. if (!mesh.isReady(true)) {
  25791. return false;
  25792. }
  25793. // Effect layers
  25794. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25795. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25796. var layer = _a[_i];
  25797. if (!layer.hasMesh(mesh)) {
  25798. continue;
  25799. }
  25800. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25801. var subMesh = _c[_b];
  25802. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25803. return false;
  25804. }
  25805. }
  25806. }
  25807. }
  25808. // Post-processes
  25809. if (this.activeCameras && this.activeCameras.length > 0) {
  25810. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25811. var camera = _e[_d];
  25812. if (!camera.isReady(true)) {
  25813. return false;
  25814. }
  25815. }
  25816. }
  25817. else if (this.activeCamera) {
  25818. if (!this.activeCamera.isReady(true)) {
  25819. return false;
  25820. }
  25821. }
  25822. // Particles
  25823. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25824. var particleSystem = _g[_f];
  25825. if (!particleSystem.isReady()) {
  25826. return false;
  25827. }
  25828. }
  25829. return true;
  25830. };
  25831. /** Resets all cached information relative to material (including effect and visibility) */
  25832. Scene.prototype.resetCachedMaterial = function () {
  25833. this._cachedMaterial = null;
  25834. this._cachedEffect = null;
  25835. this._cachedVisibility = null;
  25836. };
  25837. /**
  25838. * Registers a function to be called before every frame render
  25839. * @param func defines the function to register
  25840. */
  25841. Scene.prototype.registerBeforeRender = function (func) {
  25842. this.onBeforeRenderObservable.add(func);
  25843. };
  25844. /**
  25845. * Unregisters a function called before every frame render
  25846. * @param func defines the function to unregister
  25847. */
  25848. Scene.prototype.unregisterBeforeRender = function (func) {
  25849. this.onBeforeRenderObservable.removeCallback(func);
  25850. };
  25851. /**
  25852. * Registers a function to be called after every frame render
  25853. * @param func defines the function to register
  25854. */
  25855. Scene.prototype.registerAfterRender = function (func) {
  25856. this.onAfterRenderObservable.add(func);
  25857. };
  25858. /**
  25859. * Unregisters a function called after every frame render
  25860. * @param func defines the function to unregister
  25861. */
  25862. Scene.prototype.unregisterAfterRender = function (func) {
  25863. this.onAfterRenderObservable.removeCallback(func);
  25864. };
  25865. Scene.prototype._executeOnceBeforeRender = function (func) {
  25866. var _this = this;
  25867. var execFunc = function () {
  25868. func();
  25869. setTimeout(function () {
  25870. _this.unregisterBeforeRender(execFunc);
  25871. });
  25872. };
  25873. this.registerBeforeRender(execFunc);
  25874. };
  25875. /**
  25876. * The provided function will run before render once and will be disposed afterwards.
  25877. * A timeout delay can be provided so that the function will be executed in N ms.
  25878. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25879. * @param func The function to be executed.
  25880. * @param timeout optional delay in ms
  25881. */
  25882. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25883. var _this = this;
  25884. if (timeout !== undefined) {
  25885. setTimeout(function () {
  25886. _this._executeOnceBeforeRender(func);
  25887. }, timeout);
  25888. }
  25889. else {
  25890. this._executeOnceBeforeRender(func);
  25891. }
  25892. };
  25893. /** @hidden */
  25894. Scene.prototype._addPendingData = function (data) {
  25895. this._pendingData.push(data);
  25896. };
  25897. /** @hidden */
  25898. Scene.prototype._removePendingData = function (data) {
  25899. var wasLoading = this.isLoading;
  25900. var index = this._pendingData.indexOf(data);
  25901. if (index !== -1) {
  25902. this._pendingData.splice(index, 1);
  25903. }
  25904. if (wasLoading && !this.isLoading) {
  25905. this.onDataLoadedObservable.notifyObservers(this);
  25906. }
  25907. };
  25908. /**
  25909. * Returns the number of items waiting to be loaded
  25910. * @returns the number of items waiting to be loaded
  25911. */
  25912. Scene.prototype.getWaitingItemsCount = function () {
  25913. return this._pendingData.length;
  25914. };
  25915. Object.defineProperty(Scene.prototype, "isLoading", {
  25916. /**
  25917. * Returns a boolean indicating if the scene is still loading data
  25918. */
  25919. get: function () {
  25920. return this._pendingData.length > 0;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. /**
  25926. * Registers a function to be executed when the scene is ready
  25927. * @param {Function} func - the function to be executed
  25928. */
  25929. Scene.prototype.executeWhenReady = function (func) {
  25930. var _this = this;
  25931. this.onReadyObservable.add(func);
  25932. if (this._executeWhenReadyTimeoutId !== -1) {
  25933. return;
  25934. }
  25935. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25936. _this._checkIsReady();
  25937. }, 150);
  25938. };
  25939. /**
  25940. * Returns a promise that resolves when the scene is ready
  25941. * @returns A promise that resolves when the scene is ready
  25942. */
  25943. Scene.prototype.whenReadyAsync = function () {
  25944. var _this = this;
  25945. return new Promise(function (resolve) {
  25946. _this.executeWhenReady(function () {
  25947. resolve();
  25948. });
  25949. });
  25950. };
  25951. /** @hidden */
  25952. Scene.prototype._checkIsReady = function () {
  25953. var _this = this;
  25954. if (this.isReady()) {
  25955. this.onReadyObservable.notifyObservers(this);
  25956. this.onReadyObservable.clear();
  25957. this._executeWhenReadyTimeoutId = -1;
  25958. return;
  25959. }
  25960. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25961. _this._checkIsReady();
  25962. }, 150);
  25963. };
  25964. // Animations
  25965. /**
  25966. * Will start the animation sequence of a given target
  25967. * @param target defines the target
  25968. * @param from defines from which frame should animation start
  25969. * @param to defines until which frame should animation run.
  25970. * @param weight defines the weight to apply to the animation (1.0 by default)
  25971. * @param loop defines if the animation loops
  25972. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25973. * @param onAnimationEnd defines the function to be executed when the animation ends
  25974. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25975. * @returns the animatable object created for this animation
  25976. */
  25977. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25978. if (weight === void 0) { weight = 1.0; }
  25979. if (speedRatio === void 0) { speedRatio = 1.0; }
  25980. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25981. returnedAnimatable.weight = weight;
  25982. return returnedAnimatable;
  25983. };
  25984. /**
  25985. * Will start the animation sequence of a given target
  25986. * @param target defines the target
  25987. * @param from defines from which frame should animation start
  25988. * @param to defines until which frame should animation run.
  25989. * @param loop defines if the animation loops
  25990. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25991. * @param onAnimationEnd defines the function to be executed when the animation ends
  25992. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25993. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25994. * @returns the animatable object created for this animation
  25995. */
  25996. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25997. if (speedRatio === void 0) { speedRatio = 1.0; }
  25998. if (stopCurrent === void 0) { stopCurrent = true; }
  25999. if (from > to && speedRatio > 0) {
  26000. speedRatio *= -1;
  26001. }
  26002. if (stopCurrent) {
  26003. this.stopAnimation(target);
  26004. }
  26005. if (!animatable) {
  26006. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26007. }
  26008. // Local animations
  26009. if (target.animations) {
  26010. animatable.appendAnimations(target, target.animations);
  26011. }
  26012. // Children animations
  26013. if (target.getAnimatables) {
  26014. var animatables = target.getAnimatables();
  26015. for (var index = 0; index < animatables.length; index++) {
  26016. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26017. }
  26018. }
  26019. animatable.reset();
  26020. return animatable;
  26021. };
  26022. /**
  26023. * Begin a new animation on a given node
  26024. * @param target defines the target where the animation will take place
  26025. * @param animations defines the list of animations to start
  26026. * @param from defines the initial value
  26027. * @param to defines the final value
  26028. * @param loop defines if you want animation to loop (off by default)
  26029. * @param speedRatio defines the speed ratio to apply to all animations
  26030. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26031. * @returns the list of created animatables
  26032. */
  26033. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26034. if (speedRatio === undefined) {
  26035. speedRatio = 1.0;
  26036. }
  26037. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26038. return animatable;
  26039. };
  26040. /**
  26041. * Begin a new animation on a given node and its hierarchy
  26042. * @param target defines the root node where the animation will take place
  26043. * @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.
  26044. * @param animations defines the list of animations to start
  26045. * @param from defines the initial value
  26046. * @param to defines the final value
  26047. * @param loop defines if you want animation to loop (off by default)
  26048. * @param speedRatio defines the speed ratio to apply to all animations
  26049. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26050. * @returns the list of animatables created for all nodes
  26051. */
  26052. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26053. var children = target.getDescendants(directDescendantsOnly);
  26054. var result = [];
  26055. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26056. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26057. var child = children_1[_i];
  26058. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26059. }
  26060. return result;
  26061. };
  26062. /**
  26063. * Gets the animatable associated with a specific target
  26064. * @param target defines the target of the animatable
  26065. * @returns the required animatable if found
  26066. */
  26067. Scene.prototype.getAnimatableByTarget = function (target) {
  26068. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26069. if (this._activeAnimatables[index].target === target) {
  26070. return this._activeAnimatables[index];
  26071. }
  26072. }
  26073. return null;
  26074. };
  26075. /**
  26076. * Gets all animatables associated with a given target
  26077. * @param target defines the target to look animatables for
  26078. * @returns an array of Animatables
  26079. */
  26080. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26081. var result = [];
  26082. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26083. if (this._activeAnimatables[index].target === target) {
  26084. result.push(this._activeAnimatables[index]);
  26085. }
  26086. }
  26087. return result;
  26088. };
  26089. Object.defineProperty(Scene.prototype, "animatables", {
  26090. /**
  26091. * Gets all animatable attached to the scene
  26092. */
  26093. get: function () {
  26094. return this._activeAnimatables;
  26095. },
  26096. enumerable: true,
  26097. configurable: true
  26098. });
  26099. /**
  26100. * Will stop the animation of the given target
  26101. * @param target - the target
  26102. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26103. */
  26104. Scene.prototype.stopAnimation = function (target, animationName) {
  26105. var animatables = this.getAllAnimatablesByTarget(target);
  26106. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26107. var animatable = animatables_1[_i];
  26108. animatable.stop(animationName);
  26109. }
  26110. };
  26111. /**
  26112. * Stops and removes all animations that have been applied to the scene
  26113. */
  26114. Scene.prototype.stopAllAnimations = function () {
  26115. if (this._activeAnimatables) {
  26116. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26117. this._activeAnimatables[i].stop();
  26118. }
  26119. this._activeAnimatables = [];
  26120. }
  26121. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26122. var group = _a[_i];
  26123. group.stop();
  26124. }
  26125. };
  26126. Scene.prototype._animate = function () {
  26127. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26128. return;
  26129. }
  26130. // Getting time
  26131. var now = BABYLON.Tools.Now;
  26132. if (!this._animationTimeLast) {
  26133. if (this._pendingData.length > 0) {
  26134. return;
  26135. }
  26136. this._animationTimeLast = now;
  26137. }
  26138. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26139. this._animationTime += deltaTime;
  26140. this._animationTimeLast = now;
  26141. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26142. this._activeAnimatables[index]._animate(this._animationTime);
  26143. }
  26144. // Late animation bindings
  26145. this._processLateAnimationBindings();
  26146. };
  26147. /** @hidden */
  26148. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26149. var target = runtimeAnimation.target;
  26150. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26151. if (!target._lateAnimationHolders) {
  26152. target._lateAnimationHolders = {};
  26153. }
  26154. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26155. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26156. totalWeight: 0,
  26157. animations: [],
  26158. originalValue: originalValue
  26159. };
  26160. }
  26161. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26162. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26163. };
  26164. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26165. var normalizer = 1.0;
  26166. var finalPosition = BABYLON.Tmp.Vector3[0];
  26167. var finalScaling = BABYLON.Tmp.Vector3[1];
  26168. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26169. var startIndex = 0;
  26170. var originalAnimation = holder.animations[0];
  26171. var originalValue = holder.originalValue;
  26172. var scale = 1;
  26173. if (holder.totalWeight < 1.0) {
  26174. // We need to mix the original value in
  26175. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26176. scale = 1.0 - holder.totalWeight;
  26177. }
  26178. else {
  26179. startIndex = 1;
  26180. // We need to normalize the weights
  26181. normalizer = holder.totalWeight;
  26182. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26183. scale = originalAnimation.weight / normalizer;
  26184. if (scale == 1) {
  26185. return originalAnimation.currentValue;
  26186. }
  26187. }
  26188. finalScaling.scaleInPlace(scale);
  26189. finalPosition.scaleInPlace(scale);
  26190. finalQuaternion.scaleInPlace(scale);
  26191. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26192. var runtimeAnimation = holder.animations[animIndex];
  26193. var scale = runtimeAnimation.weight / normalizer;
  26194. var currentPosition = BABYLON.Tmp.Vector3[2];
  26195. var currentScaling = BABYLON.Tmp.Vector3[3];
  26196. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26197. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26198. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26199. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26200. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26201. }
  26202. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26203. return originalAnimation._workValue;
  26204. };
  26205. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26206. var originalAnimation = holder.animations[0];
  26207. var originalValue = holder.originalValue;
  26208. if (holder.animations.length === 1) {
  26209. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26210. }
  26211. var normalizer = 1.0;
  26212. var quaternions;
  26213. var weights;
  26214. if (holder.totalWeight < 1.0) {
  26215. var scale = 1.0 - holder.totalWeight;
  26216. quaternions = [];
  26217. weights = [];
  26218. quaternions.push(originalValue);
  26219. weights.push(scale);
  26220. }
  26221. else {
  26222. if (holder.animations.length === 2) { // Slerp as soon as we can
  26223. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26224. }
  26225. quaternions = [];
  26226. weights = [];
  26227. normalizer = holder.totalWeight;
  26228. }
  26229. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26230. var runtimeAnimation = holder.animations[animIndex];
  26231. quaternions.push(runtimeAnimation.currentValue);
  26232. weights.push(runtimeAnimation.weight / normalizer);
  26233. }
  26234. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26235. var cumulativeAmount = 0;
  26236. var cumulativeQuaternion = null;
  26237. for (var index = 0; index < quaternions.length;) {
  26238. if (!cumulativeQuaternion) {
  26239. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26240. cumulativeAmount = weights[index] + weights[index + 1];
  26241. index += 2;
  26242. continue;
  26243. }
  26244. cumulativeAmount += weights[index];
  26245. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26246. index++;
  26247. }
  26248. return cumulativeQuaternion;
  26249. };
  26250. Scene.prototype._processLateAnimationBindings = function () {
  26251. if (!this._registeredForLateAnimationBindings.length) {
  26252. return;
  26253. }
  26254. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26255. var target = this._registeredForLateAnimationBindings.data[index];
  26256. for (var path in target._lateAnimationHolders) {
  26257. var holder = target._lateAnimationHolders[path];
  26258. var originalAnimation = holder.animations[0];
  26259. var originalValue = holder.originalValue;
  26260. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26261. var finalValue = void 0;
  26262. if (matrixDecomposeMode) {
  26263. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26264. }
  26265. else {
  26266. var quaternionMode = originalValue.w !== undefined;
  26267. if (quaternionMode) {
  26268. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26269. }
  26270. else {
  26271. var startIndex = 0;
  26272. var normalizer = 1.0;
  26273. if (holder.totalWeight < 1.0) {
  26274. // We need to mix the original value in
  26275. if (originalValue.scale) {
  26276. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26277. }
  26278. else {
  26279. finalValue = originalValue * (1.0 - holder.totalWeight);
  26280. }
  26281. }
  26282. else {
  26283. // We need to normalize the weights
  26284. normalizer = holder.totalWeight;
  26285. var scale_1 = originalAnimation.weight / normalizer;
  26286. if (scale_1 !== 1) {
  26287. if (originalAnimation.currentValue.scale) {
  26288. finalValue = originalAnimation.currentValue.scale(scale_1);
  26289. }
  26290. else {
  26291. finalValue = originalAnimation.currentValue * scale_1;
  26292. }
  26293. }
  26294. else {
  26295. finalValue = originalAnimation.currentValue;
  26296. }
  26297. startIndex = 1;
  26298. }
  26299. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26300. var runtimeAnimation = holder.animations[animIndex];
  26301. var scale = runtimeAnimation.weight / normalizer;
  26302. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26303. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26304. }
  26305. else {
  26306. finalValue += runtimeAnimation.currentValue * scale;
  26307. }
  26308. }
  26309. }
  26310. }
  26311. target[path] = finalValue;
  26312. }
  26313. target._lateAnimationHolders = {};
  26314. }
  26315. this._registeredForLateAnimationBindings.reset();
  26316. };
  26317. // Matrix
  26318. /** @hidden */
  26319. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26320. this._useAlternateCameraConfiguration = active;
  26321. };
  26322. /**
  26323. * Gets the current view matrix
  26324. * @returns a Matrix
  26325. */
  26326. Scene.prototype.getViewMatrix = function () {
  26327. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26328. };
  26329. /**
  26330. * Gets the current projection matrix
  26331. * @returns a Matrix
  26332. */
  26333. Scene.prototype.getProjectionMatrix = function () {
  26334. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26335. };
  26336. /**
  26337. * Gets the current transform matrix
  26338. * @returns a Matrix made of View * Projection
  26339. */
  26340. Scene.prototype.getTransformMatrix = function () {
  26341. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26342. };
  26343. /**
  26344. * Sets the current transform matrix
  26345. * @param view defines the View matrix to use
  26346. * @param projection defines the Projection matrix to use
  26347. */
  26348. Scene.prototype.setTransformMatrix = function (view, projection) {
  26349. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26350. return;
  26351. }
  26352. this._viewUpdateFlag = view.updateFlag;
  26353. this._projectionUpdateFlag = projection.updateFlag;
  26354. this._viewMatrix = view;
  26355. this._projectionMatrix = projection;
  26356. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26357. // Update frustum
  26358. if (!this._frustumPlanes) {
  26359. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26360. }
  26361. else {
  26362. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26363. }
  26364. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26365. var otherCamera = this.activeCamera._alternateCamera;
  26366. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26367. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26368. }
  26369. if (this._sceneUbo.useUbo) {
  26370. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26371. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26372. this._sceneUbo.update();
  26373. }
  26374. };
  26375. /** @hidden */
  26376. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26377. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26378. return;
  26379. }
  26380. this._alternateViewUpdateFlag = view.updateFlag;
  26381. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26382. this._alternateViewMatrix = view;
  26383. this._alternateProjectionMatrix = projection;
  26384. if (!this._alternateTransformMatrix) {
  26385. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26386. }
  26387. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26388. if (!this._alternateSceneUbo) {
  26389. this._createAlternateUbo();
  26390. }
  26391. if (this._alternateSceneUbo.useUbo) {
  26392. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26393. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26394. this._alternateSceneUbo.update();
  26395. }
  26396. };
  26397. /**
  26398. * Gets the uniform buffer used to store scene data
  26399. * @returns a UniformBuffer
  26400. */
  26401. Scene.prototype.getSceneUniformBuffer = function () {
  26402. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26403. };
  26404. /**
  26405. * Gets an unique (relatively to the current scene) Id
  26406. * @returns an unique number for the scene
  26407. */
  26408. Scene.prototype.getUniqueId = function () {
  26409. var result = Scene._uniqueIdCounter;
  26410. Scene._uniqueIdCounter++;
  26411. return result;
  26412. };
  26413. /**
  26414. * Add a mesh to the list of scene's meshes
  26415. * @param newMesh defines the mesh to add
  26416. * @param recursive if all child meshes should also be added to the scene
  26417. */
  26418. Scene.prototype.addMesh = function (newMesh, recursive) {
  26419. var _this = this;
  26420. if (recursive === void 0) { recursive = false; }
  26421. this.meshes.push(newMesh);
  26422. //notify the collision coordinator
  26423. if (this.collisionCoordinator) {
  26424. this.collisionCoordinator.onMeshAdded(newMesh);
  26425. }
  26426. newMesh._resyncLightSources();
  26427. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26428. if (recursive) {
  26429. newMesh.getChildMeshes().forEach(function (m) {
  26430. _this.addMesh(m);
  26431. });
  26432. }
  26433. };
  26434. /**
  26435. * Remove a mesh for the list of scene's meshes
  26436. * @param toRemove defines the mesh to remove
  26437. * @param recursive if all child meshes should also be removed from the scene
  26438. * @returns the index where the mesh was in the mesh list
  26439. */
  26440. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26441. var _this = this;
  26442. if (recursive === void 0) { recursive = false; }
  26443. var index = this.meshes.indexOf(toRemove);
  26444. if (index !== -1) {
  26445. // Remove from the scene if mesh found
  26446. this.meshes.splice(index, 1);
  26447. }
  26448. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26449. if (recursive) {
  26450. toRemove.getChildMeshes().forEach(function (m) {
  26451. _this.removeMesh(m);
  26452. });
  26453. }
  26454. return index;
  26455. };
  26456. /**
  26457. * Add a transform node to the list of scene's transform nodes
  26458. * @param newTransformNode defines the transform node to add
  26459. */
  26460. Scene.prototype.addTransformNode = function (newTransformNode) {
  26461. this.transformNodes.push(newTransformNode);
  26462. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26463. };
  26464. /**
  26465. * Remove a transform node for the list of scene's transform nodes
  26466. * @param toRemove defines the transform node to remove
  26467. * @returns the index where the transform node was in the transform node list
  26468. */
  26469. Scene.prototype.removeTransformNode = function (toRemove) {
  26470. var index = this.transformNodes.indexOf(toRemove);
  26471. if (index !== -1) {
  26472. // Remove from the scene if found
  26473. this.transformNodes.splice(index, 1);
  26474. }
  26475. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26476. return index;
  26477. };
  26478. /**
  26479. * Remove a skeleton for the list of scene's skeletons
  26480. * @param toRemove defines the skeleton to remove
  26481. * @returns the index where the skeleton was in the skeleton list
  26482. */
  26483. Scene.prototype.removeSkeleton = function (toRemove) {
  26484. var index = this.skeletons.indexOf(toRemove);
  26485. if (index !== -1) {
  26486. // Remove from the scene if found
  26487. this.skeletons.splice(index, 1);
  26488. }
  26489. return index;
  26490. };
  26491. /**
  26492. * Remove a morph target for the list of scene's morph targets
  26493. * @param toRemove defines the morph target to remove
  26494. * @returns the index where the morph target was in the morph target list
  26495. */
  26496. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26497. var index = this.morphTargetManagers.indexOf(toRemove);
  26498. if (index !== -1) {
  26499. // Remove from the scene if found
  26500. this.morphTargetManagers.splice(index, 1);
  26501. }
  26502. return index;
  26503. };
  26504. /**
  26505. * Remove a light for the list of scene's lights
  26506. * @param toRemove defines the light to remove
  26507. * @returns the index where the light was in the light list
  26508. */
  26509. Scene.prototype.removeLight = function (toRemove) {
  26510. var index = this.lights.indexOf(toRemove);
  26511. if (index !== -1) {
  26512. // Remove from meshes
  26513. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26514. var mesh = _a[_i];
  26515. mesh._removeLightSource(toRemove);
  26516. }
  26517. // Remove from the scene if mesh found
  26518. this.lights.splice(index, 1);
  26519. this.sortLightsByPriority();
  26520. }
  26521. this.onLightRemovedObservable.notifyObservers(toRemove);
  26522. return index;
  26523. };
  26524. /**
  26525. * Remove a camera for the list of scene's cameras
  26526. * @param toRemove defines the camera to remove
  26527. * @returns the index where the camera was in the camera list
  26528. */
  26529. Scene.prototype.removeCamera = function (toRemove) {
  26530. var index = this.cameras.indexOf(toRemove);
  26531. if (index !== -1) {
  26532. // Remove from the scene if mesh found
  26533. this.cameras.splice(index, 1);
  26534. }
  26535. // Remove from activeCameras
  26536. var index2 = this.activeCameras.indexOf(toRemove);
  26537. if (index2 !== -1) {
  26538. // Remove from the scene if mesh found
  26539. this.activeCameras.splice(index2, 1);
  26540. }
  26541. // Reset the activeCamera
  26542. if (this.activeCamera === toRemove) {
  26543. if (this.cameras.length > 0) {
  26544. this.activeCamera = this.cameras[0];
  26545. }
  26546. else {
  26547. this.activeCamera = null;
  26548. }
  26549. }
  26550. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26551. return index;
  26552. };
  26553. /**
  26554. * Remove a particle system for the list of scene's particle systems
  26555. * @param toRemove defines the particle system to remove
  26556. * @returns the index where the particle system was in the particle system list
  26557. */
  26558. Scene.prototype.removeParticleSystem = function (toRemove) {
  26559. var index = this.particleSystems.indexOf(toRemove);
  26560. if (index !== -1) {
  26561. this.particleSystems.splice(index, 1);
  26562. }
  26563. return index;
  26564. };
  26565. /**
  26566. * Remove a animation for the list of scene's animations
  26567. * @param toRemove defines the animation to remove
  26568. * @returns the index where the animation was in the animation list
  26569. */
  26570. Scene.prototype.removeAnimation = function (toRemove) {
  26571. var index = this.animations.indexOf(toRemove);
  26572. if (index !== -1) {
  26573. this.animations.splice(index, 1);
  26574. }
  26575. return index;
  26576. };
  26577. /**
  26578. * Removes the given animation group from this scene.
  26579. * @param toRemove The animation group to remove
  26580. * @returns The index of the removed animation group
  26581. */
  26582. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26583. var index = this.animationGroups.indexOf(toRemove);
  26584. if (index !== -1) {
  26585. this.animationGroups.splice(index, 1);
  26586. }
  26587. return index;
  26588. };
  26589. /**
  26590. * Removes the given multi-material from this scene.
  26591. * @param toRemove The multi-material to remove
  26592. * @returns The index of the removed multi-material
  26593. */
  26594. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26595. var index = this.multiMaterials.indexOf(toRemove);
  26596. if (index !== -1) {
  26597. this.multiMaterials.splice(index, 1);
  26598. }
  26599. return index;
  26600. };
  26601. /**
  26602. * Removes the given material from this scene.
  26603. * @param toRemove The material to remove
  26604. * @returns The index of the removed material
  26605. */
  26606. Scene.prototype.removeMaterial = function (toRemove) {
  26607. var index = this.materials.indexOf(toRemove);
  26608. if (index !== -1) {
  26609. this.materials.splice(index, 1);
  26610. }
  26611. return index;
  26612. };
  26613. /**
  26614. * Removes the given lens flare system from this scene.
  26615. * @param toRemove The lens flare system to remove
  26616. * @returns The index of the removed lens flare system
  26617. */
  26618. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26619. var index = this.lensFlareSystems.indexOf(toRemove);
  26620. if (index !== -1) {
  26621. this.lensFlareSystems.splice(index, 1);
  26622. }
  26623. return index;
  26624. };
  26625. /**
  26626. * Removes the given action manager from this scene.
  26627. * @param toRemove The action manager to remove
  26628. * @returns The index of the removed action manager
  26629. */
  26630. Scene.prototype.removeActionManager = function (toRemove) {
  26631. var index = this._actionManagers.indexOf(toRemove);
  26632. if (index !== -1) {
  26633. this._actionManagers.splice(index, 1);
  26634. }
  26635. return index;
  26636. };
  26637. /**
  26638. * Removes the given effect layer from this scene.
  26639. * @param toRemove defines the effect layer to remove
  26640. * @returns the index of the removed effect layer
  26641. */
  26642. Scene.prototype.removeEffectLayer = function (toRemove) {
  26643. var index = this.effectLayers.indexOf(toRemove);
  26644. if (index !== -1) {
  26645. this.effectLayers.splice(index, 1);
  26646. }
  26647. return index;
  26648. };
  26649. /**
  26650. * Removes the given texture from this scene.
  26651. * @param toRemove The texture to remove
  26652. * @returns The index of the removed texture
  26653. */
  26654. Scene.prototype.removeTexture = function (toRemove) {
  26655. var index = this.textures.indexOf(toRemove);
  26656. if (index !== -1) {
  26657. this.textures.splice(index, 1);
  26658. }
  26659. return index;
  26660. };
  26661. /**
  26662. * Adds the given light to this scene
  26663. * @param newLight The light to add
  26664. */
  26665. Scene.prototype.addLight = function (newLight) {
  26666. this.lights.push(newLight);
  26667. this.sortLightsByPriority();
  26668. // Add light to all meshes (To support if the light is removed and then readded)
  26669. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26670. var mesh = _a[_i];
  26671. if (mesh._lightSources.indexOf(newLight) === -1) {
  26672. mesh._lightSources.push(newLight);
  26673. mesh._resyncLightSources();
  26674. }
  26675. }
  26676. this.onNewLightAddedObservable.notifyObservers(newLight);
  26677. };
  26678. /**
  26679. * Sorts the list list based on light priorities
  26680. */
  26681. Scene.prototype.sortLightsByPriority = function () {
  26682. if (this.requireLightSorting) {
  26683. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26684. }
  26685. };
  26686. /**
  26687. * Adds the given camera to this scene
  26688. * @param newCamera The camera to add
  26689. */
  26690. Scene.prototype.addCamera = function (newCamera) {
  26691. this.cameras.push(newCamera);
  26692. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26693. };
  26694. /**
  26695. * Adds the given skeleton to this scene
  26696. * @param newSkeleton The skeleton to add
  26697. */
  26698. Scene.prototype.addSkeleton = function (newSkeleton) {
  26699. this.skeletons.push(newSkeleton);
  26700. };
  26701. /**
  26702. * Adds the given particle system to this scene
  26703. * @param newParticleSystem The particle system to add
  26704. */
  26705. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26706. this.particleSystems.push(newParticleSystem);
  26707. };
  26708. /**
  26709. * Adds the given animation to this scene
  26710. * @param newAnimation The animation to add
  26711. */
  26712. Scene.prototype.addAnimation = function (newAnimation) {
  26713. this.animations.push(newAnimation);
  26714. };
  26715. /**
  26716. * Adds the given animation group to this scene.
  26717. * @param newAnimationGroup The animation group to add
  26718. */
  26719. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26720. this.animationGroups.push(newAnimationGroup);
  26721. };
  26722. /**
  26723. * Adds the given multi-material to this scene
  26724. * @param newMultiMaterial The multi-material to add
  26725. */
  26726. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26727. this.multiMaterials.push(newMultiMaterial);
  26728. };
  26729. /**
  26730. * Adds the given material to this scene
  26731. * @param newMaterial The material to add
  26732. */
  26733. Scene.prototype.addMaterial = function (newMaterial) {
  26734. this.materials.push(newMaterial);
  26735. };
  26736. /**
  26737. * Adds the given morph target to this scene
  26738. * @param newMorphTargetManager The morph target to add
  26739. */
  26740. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26741. this.morphTargetManagers.push(newMorphTargetManager);
  26742. };
  26743. /**
  26744. * Adds the given geometry to this scene
  26745. * @param newGeometry The geometry to add
  26746. */
  26747. Scene.prototype.addGeometry = function (newGeometry) {
  26748. this._geometries.push(newGeometry);
  26749. };
  26750. /**
  26751. * Adds the given lens flare system to this scene
  26752. * @param newLensFlareSystem The lens flare system to add
  26753. */
  26754. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26755. this.lensFlareSystems.push(newLensFlareSystem);
  26756. };
  26757. /**
  26758. * Adds the given effect layer to this scene
  26759. * @param newEffectLayer defines the effect layer to add
  26760. */
  26761. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26762. this.effectLayers.push(newEffectLayer);
  26763. };
  26764. /**
  26765. * Adds the given action manager to this scene
  26766. * @param newActionManager The action manager to add
  26767. */
  26768. Scene.prototype.addActionManager = function (newActionManager) {
  26769. this._actionManagers.push(newActionManager);
  26770. };
  26771. /**
  26772. * Adds the given texture to this scene.
  26773. * @param newTexture The texture to add
  26774. */
  26775. Scene.prototype.addTexture = function (newTexture) {
  26776. this.textures.push(newTexture);
  26777. };
  26778. /**
  26779. * Switch active camera
  26780. * @param newCamera defines the new active camera
  26781. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26782. */
  26783. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26784. if (attachControl === void 0) { attachControl = true; }
  26785. var canvas = this._engine.getRenderingCanvas();
  26786. if (!canvas) {
  26787. return;
  26788. }
  26789. if (this.activeCamera) {
  26790. this.activeCamera.detachControl(canvas);
  26791. }
  26792. this.activeCamera = newCamera;
  26793. if (attachControl) {
  26794. newCamera.attachControl(canvas);
  26795. }
  26796. };
  26797. /**
  26798. * sets the active camera of the scene using its ID
  26799. * @param id defines the camera's ID
  26800. * @return the new active camera or null if none found.
  26801. */
  26802. Scene.prototype.setActiveCameraByID = function (id) {
  26803. var camera = this.getCameraByID(id);
  26804. if (camera) {
  26805. this.activeCamera = camera;
  26806. return camera;
  26807. }
  26808. return null;
  26809. };
  26810. /**
  26811. * sets the active camera of the scene using its name
  26812. * @param name defines the camera's name
  26813. * @returns the new active camera or null if none found.
  26814. */
  26815. Scene.prototype.setActiveCameraByName = function (name) {
  26816. var camera = this.getCameraByName(name);
  26817. if (camera) {
  26818. this.activeCamera = camera;
  26819. return camera;
  26820. }
  26821. return null;
  26822. };
  26823. /**
  26824. * get an animation group using its name
  26825. * @param name defines the material's name
  26826. * @return the animation group or null if none found.
  26827. */
  26828. Scene.prototype.getAnimationGroupByName = function (name) {
  26829. for (var index = 0; index < this.animationGroups.length; index++) {
  26830. if (this.animationGroups[index].name === name) {
  26831. return this.animationGroups[index];
  26832. }
  26833. }
  26834. return null;
  26835. };
  26836. /**
  26837. * get a material using its id
  26838. * @param id defines the material's ID
  26839. * @return the material or null if none found.
  26840. */
  26841. Scene.prototype.getMaterialByID = function (id) {
  26842. for (var index = 0; index < this.materials.length; index++) {
  26843. if (this.materials[index].id === id) {
  26844. return this.materials[index];
  26845. }
  26846. }
  26847. return null;
  26848. };
  26849. /**
  26850. * Gets a material using its name
  26851. * @param name defines the material's name
  26852. * @return the material or null if none found.
  26853. */
  26854. Scene.prototype.getMaterialByName = function (name) {
  26855. for (var index = 0; index < this.materials.length; index++) {
  26856. if (this.materials[index].name === name) {
  26857. return this.materials[index];
  26858. }
  26859. }
  26860. return null;
  26861. };
  26862. /**
  26863. * Gets a lens flare system using its name
  26864. * @param name defines the name to look for
  26865. * @returns the lens flare system or null if not found
  26866. */
  26867. Scene.prototype.getLensFlareSystemByName = function (name) {
  26868. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26869. if (this.lensFlareSystems[index].name === name) {
  26870. return this.lensFlareSystems[index];
  26871. }
  26872. }
  26873. return null;
  26874. };
  26875. /**
  26876. * Gets a lens flare system using its id
  26877. * @param id defines the id to look for
  26878. * @returns the lens flare system or null if not found
  26879. */
  26880. Scene.prototype.getLensFlareSystemByID = function (id) {
  26881. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26882. if (this.lensFlareSystems[index].id === id) {
  26883. return this.lensFlareSystems[index];
  26884. }
  26885. }
  26886. return null;
  26887. };
  26888. /**
  26889. * Gets a camera using its id
  26890. * @param id defines the id to look for
  26891. * @returns the camera or null if not found
  26892. */
  26893. Scene.prototype.getCameraByID = function (id) {
  26894. for (var index = 0; index < this.cameras.length; index++) {
  26895. if (this.cameras[index].id === id) {
  26896. return this.cameras[index];
  26897. }
  26898. }
  26899. return null;
  26900. };
  26901. /**
  26902. * Gets a camera using its unique id
  26903. * @param uniqueId defines the unique id to look for
  26904. * @returns the camera or null if not found
  26905. */
  26906. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26907. for (var index = 0; index < this.cameras.length; index++) {
  26908. if (this.cameras[index].uniqueId === uniqueId) {
  26909. return this.cameras[index];
  26910. }
  26911. }
  26912. return null;
  26913. };
  26914. /**
  26915. * Gets a camera using its name
  26916. * @param name defines the camera's name
  26917. * @return the camera or null if none found.
  26918. */
  26919. Scene.prototype.getCameraByName = function (name) {
  26920. for (var index = 0; index < this.cameras.length; index++) {
  26921. if (this.cameras[index].name === name) {
  26922. return this.cameras[index];
  26923. }
  26924. }
  26925. return null;
  26926. };
  26927. /**
  26928. * Gets a bone using its id
  26929. * @param id defines the bone's id
  26930. * @return the bone or null if not found
  26931. */
  26932. Scene.prototype.getBoneByID = function (id) {
  26933. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26934. var skeleton = this.skeletons[skeletonIndex];
  26935. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26936. if (skeleton.bones[boneIndex].id === id) {
  26937. return skeleton.bones[boneIndex];
  26938. }
  26939. }
  26940. }
  26941. return null;
  26942. };
  26943. /**
  26944. * Gets a bone using its id
  26945. * @param name defines the bone's name
  26946. * @return the bone or null if not found
  26947. */
  26948. Scene.prototype.getBoneByName = function (name) {
  26949. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26950. var skeleton = this.skeletons[skeletonIndex];
  26951. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26952. if (skeleton.bones[boneIndex].name === name) {
  26953. return skeleton.bones[boneIndex];
  26954. }
  26955. }
  26956. }
  26957. return null;
  26958. };
  26959. /**
  26960. * Gets a light node using its name
  26961. * @param name defines the the light's name
  26962. * @return the light or null if none found.
  26963. */
  26964. Scene.prototype.getLightByName = function (name) {
  26965. for (var index = 0; index < this.lights.length; index++) {
  26966. if (this.lights[index].name === name) {
  26967. return this.lights[index];
  26968. }
  26969. }
  26970. return null;
  26971. };
  26972. /**
  26973. * Gets a light node using its id
  26974. * @param id defines the light's id
  26975. * @return the light or null if none found.
  26976. */
  26977. Scene.prototype.getLightByID = function (id) {
  26978. for (var index = 0; index < this.lights.length; index++) {
  26979. if (this.lights[index].id === id) {
  26980. return this.lights[index];
  26981. }
  26982. }
  26983. return null;
  26984. };
  26985. /**
  26986. * Gets a light node using its scene-generated unique ID
  26987. * @param uniqueId defines the light's unique id
  26988. * @return the light or null if none found.
  26989. */
  26990. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26991. for (var index = 0; index < this.lights.length; index++) {
  26992. if (this.lights[index].uniqueId === uniqueId) {
  26993. return this.lights[index];
  26994. }
  26995. }
  26996. return null;
  26997. };
  26998. /**
  26999. * Gets a particle system by id
  27000. * @param id defines the particle system id
  27001. * @return the corresponding system or null if none found
  27002. */
  27003. Scene.prototype.getParticleSystemByID = function (id) {
  27004. for (var index = 0; index < this.particleSystems.length; index++) {
  27005. if (this.particleSystems[index].id === id) {
  27006. return this.particleSystems[index];
  27007. }
  27008. }
  27009. return null;
  27010. };
  27011. /**
  27012. * Gets a geometry using its ID
  27013. * @param id defines the geometry's id
  27014. * @return the geometry or null if none found.
  27015. */
  27016. Scene.prototype.getGeometryByID = function (id) {
  27017. for (var index = 0; index < this._geometries.length; index++) {
  27018. if (this._geometries[index].id === id) {
  27019. return this._geometries[index];
  27020. }
  27021. }
  27022. return null;
  27023. };
  27024. /**
  27025. * Add a new geometry to this scene
  27026. * @param geometry defines the geometry to be added to the scene.
  27027. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27028. * @return a boolean defining if the geometry was added or not
  27029. */
  27030. Scene.prototype.pushGeometry = function (geometry, force) {
  27031. if (!force && this.getGeometryByID(geometry.id)) {
  27032. return false;
  27033. }
  27034. this._geometries.push(geometry);
  27035. //notify the collision coordinator
  27036. if (this.collisionCoordinator) {
  27037. this.collisionCoordinator.onGeometryAdded(geometry);
  27038. }
  27039. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27040. return true;
  27041. };
  27042. /**
  27043. * Removes an existing geometry
  27044. * @param geometry defines the geometry to be removed from the scene
  27045. * @return a boolean defining if the geometry was removed or not
  27046. */
  27047. Scene.prototype.removeGeometry = function (geometry) {
  27048. var index = this._geometries.indexOf(geometry);
  27049. if (index > -1) {
  27050. this._geometries.splice(index, 1);
  27051. //notify the collision coordinator
  27052. if (this.collisionCoordinator) {
  27053. this.collisionCoordinator.onGeometryDeleted(geometry);
  27054. }
  27055. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27056. return true;
  27057. }
  27058. return false;
  27059. };
  27060. /**
  27061. * Gets the list of geometries attached to the scene
  27062. * @returns an array of Geometry
  27063. */
  27064. Scene.prototype.getGeometries = function () {
  27065. return this._geometries;
  27066. };
  27067. /**
  27068. * Gets the first added mesh found of a given ID
  27069. * @param id defines the id to search for
  27070. * @return the mesh found or null if not found at all
  27071. */
  27072. Scene.prototype.getMeshByID = function (id) {
  27073. for (var index = 0; index < this.meshes.length; index++) {
  27074. if (this.meshes[index].id === id) {
  27075. return this.meshes[index];
  27076. }
  27077. }
  27078. return null;
  27079. };
  27080. /**
  27081. * Gets a list of meshes using their id
  27082. * @param id defines the id to search for
  27083. * @returns a list of meshes
  27084. */
  27085. Scene.prototype.getMeshesByID = function (id) {
  27086. return this.meshes.filter(function (m) {
  27087. return m.id === id;
  27088. });
  27089. };
  27090. /**
  27091. * Gets the first added transform node found of a given ID
  27092. * @param id defines the id to search for
  27093. * @return the found transform node or null if not found at all.
  27094. */
  27095. Scene.prototype.getTransformNodeByID = function (id) {
  27096. for (var index = 0; index < this.transformNodes.length; index++) {
  27097. if (this.transformNodes[index].id === id) {
  27098. return this.transformNodes[index];
  27099. }
  27100. }
  27101. return null;
  27102. };
  27103. /**
  27104. * Gets a list of transform nodes using their id
  27105. * @param id defines the id to search for
  27106. * @returns a list of transform nodes
  27107. */
  27108. Scene.prototype.getTransformNodesByID = function (id) {
  27109. return this.transformNodes.filter(function (m) {
  27110. return m.id === id;
  27111. });
  27112. };
  27113. /**
  27114. * Gets a mesh with its auto-generated unique id
  27115. * @param uniqueId defines the unique id to search for
  27116. * @return the found mesh or null if not found at all.
  27117. */
  27118. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27119. for (var index = 0; index < this.meshes.length; index++) {
  27120. if (this.meshes[index].uniqueId === uniqueId) {
  27121. return this.meshes[index];
  27122. }
  27123. }
  27124. return null;
  27125. };
  27126. /**
  27127. * Gets a the last added mesh using a given id
  27128. * @param id defines the id to search for
  27129. * @return the found mesh or null if not found at all.
  27130. */
  27131. Scene.prototype.getLastMeshByID = function (id) {
  27132. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27133. if (this.meshes[index].id === id) {
  27134. return this.meshes[index];
  27135. }
  27136. }
  27137. return null;
  27138. };
  27139. /**
  27140. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27141. * @param id defines the id to search for
  27142. * @return the found node or null if not found at all
  27143. */
  27144. Scene.prototype.getLastEntryByID = function (id) {
  27145. var index;
  27146. for (index = this.meshes.length - 1; index >= 0; index--) {
  27147. if (this.meshes[index].id === id) {
  27148. return this.meshes[index];
  27149. }
  27150. }
  27151. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27152. if (this.transformNodes[index].id === id) {
  27153. return this.transformNodes[index];
  27154. }
  27155. }
  27156. for (index = this.cameras.length - 1; index >= 0; index--) {
  27157. if (this.cameras[index].id === id) {
  27158. return this.cameras[index];
  27159. }
  27160. }
  27161. for (index = this.lights.length - 1; index >= 0; index--) {
  27162. if (this.lights[index].id === id) {
  27163. return this.lights[index];
  27164. }
  27165. }
  27166. return null;
  27167. };
  27168. /**
  27169. * Gets a node (Mesh, Camera, Light) using a given id
  27170. * @param id defines the id to search for
  27171. * @return the found node or null if not found at all
  27172. */
  27173. Scene.prototype.getNodeByID = function (id) {
  27174. var mesh = this.getMeshByID(id);
  27175. if (mesh) {
  27176. return mesh;
  27177. }
  27178. var light = this.getLightByID(id);
  27179. if (light) {
  27180. return light;
  27181. }
  27182. var camera = this.getCameraByID(id);
  27183. if (camera) {
  27184. return camera;
  27185. }
  27186. var bone = this.getBoneByID(id);
  27187. return bone;
  27188. };
  27189. /**
  27190. * Gets a node (Mesh, Camera, Light) using a given name
  27191. * @param name defines the name to search for
  27192. * @return the found node or null if not found at all.
  27193. */
  27194. Scene.prototype.getNodeByName = function (name) {
  27195. var mesh = this.getMeshByName(name);
  27196. if (mesh) {
  27197. return mesh;
  27198. }
  27199. var light = this.getLightByName(name);
  27200. if (light) {
  27201. return light;
  27202. }
  27203. var camera = this.getCameraByName(name);
  27204. if (camera) {
  27205. return camera;
  27206. }
  27207. var bone = this.getBoneByName(name);
  27208. return bone;
  27209. };
  27210. /**
  27211. * Gets a mesh using a given name
  27212. * @param name defines the name to search for
  27213. * @return the found mesh or null if not found at all.
  27214. */
  27215. Scene.prototype.getMeshByName = function (name) {
  27216. for (var index = 0; index < this.meshes.length; index++) {
  27217. if (this.meshes[index].name === name) {
  27218. return this.meshes[index];
  27219. }
  27220. }
  27221. return null;
  27222. };
  27223. /**
  27224. * Gets a transform node using a given name
  27225. * @param name defines the name to search for
  27226. * @return the found transform node or null if not found at all.
  27227. */
  27228. Scene.prototype.getTransformNodeByName = function (name) {
  27229. for (var index = 0; index < this.transformNodes.length; index++) {
  27230. if (this.transformNodes[index].name === name) {
  27231. return this.transformNodes[index];
  27232. }
  27233. }
  27234. return null;
  27235. };
  27236. /**
  27237. * Gets a sound using a given name
  27238. * @param name defines the name to search for
  27239. * @return the found sound or null if not found at all.
  27240. */
  27241. Scene.prototype.getSoundByName = function (name) {
  27242. var index;
  27243. if (BABYLON.AudioEngine) {
  27244. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27245. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27246. return this.mainSoundTrack.soundCollection[index];
  27247. }
  27248. }
  27249. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27250. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27251. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27252. return this.soundTracks[sdIndex].soundCollection[index];
  27253. }
  27254. }
  27255. }
  27256. }
  27257. return null;
  27258. };
  27259. /**
  27260. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27261. * @param id defines the id to search for
  27262. * @return the found skeleton or null if not found at all.
  27263. */
  27264. Scene.prototype.getLastSkeletonByID = function (id) {
  27265. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27266. if (this.skeletons[index].id === id) {
  27267. return this.skeletons[index];
  27268. }
  27269. }
  27270. return null;
  27271. };
  27272. /**
  27273. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27274. * @param id defines the id to search for
  27275. * @return the found skeleton or null if not found at all.
  27276. */
  27277. Scene.prototype.getSkeletonById = function (id) {
  27278. for (var index = 0; index < this.skeletons.length; index++) {
  27279. if (this.skeletons[index].id === id) {
  27280. return this.skeletons[index];
  27281. }
  27282. }
  27283. return null;
  27284. };
  27285. /**
  27286. * Gets a skeleton using a given name
  27287. * @param name defines the name to search for
  27288. * @return the found skeleton or null if not found at all.
  27289. */
  27290. Scene.prototype.getSkeletonByName = function (name) {
  27291. for (var index = 0; index < this.skeletons.length; index++) {
  27292. if (this.skeletons[index].name === name) {
  27293. return this.skeletons[index];
  27294. }
  27295. }
  27296. return null;
  27297. };
  27298. /**
  27299. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27300. * @param id defines the id to search for
  27301. * @return the found morph target manager or null if not found at all.
  27302. */
  27303. Scene.prototype.getMorphTargetManagerById = function (id) {
  27304. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27305. if (this.morphTargetManagers[index].uniqueId === id) {
  27306. return this.morphTargetManagers[index];
  27307. }
  27308. }
  27309. return null;
  27310. };
  27311. /**
  27312. * Gets a boolean indicating if the given mesh is active
  27313. * @param mesh defines the mesh to look for
  27314. * @returns true if the mesh is in the active list
  27315. */
  27316. Scene.prototype.isActiveMesh = function (mesh) {
  27317. return (this._activeMeshes.indexOf(mesh) !== -1);
  27318. };
  27319. /**
  27320. * Return a the first highlight layer of the scene with a given name.
  27321. * @param name The name of the highlight layer to look for.
  27322. * @return The highlight layer if found otherwise null.
  27323. */
  27324. Scene.prototype.getHighlightLayerByName = function (name) {
  27325. for (var index = 0; index < this.effectLayers.length; index++) {
  27326. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27327. return this.effectLayers[index];
  27328. }
  27329. }
  27330. return null;
  27331. };
  27332. /**
  27333. * Return a the first highlight layer of the scene with a given name.
  27334. * @param name The name of the highlight layer to look for.
  27335. * @return The highlight layer if found otherwise null.
  27336. */
  27337. Scene.prototype.getGlowLayerByName = function (name) {
  27338. for (var index = 0; index < this.effectLayers.length; index++) {
  27339. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27340. return this.effectLayers[index];
  27341. }
  27342. }
  27343. return null;
  27344. };
  27345. Object.defineProperty(Scene.prototype, "uid", {
  27346. /**
  27347. * Return a unique id as a string which can serve as an identifier for the scene
  27348. */
  27349. get: function () {
  27350. if (!this._uid) {
  27351. this._uid = BABYLON.Tools.RandomId();
  27352. }
  27353. return this._uid;
  27354. },
  27355. enumerable: true,
  27356. configurable: true
  27357. });
  27358. /**
  27359. * Add an externaly attached data from its key.
  27360. * This method call will fail and return false, if such key already exists.
  27361. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27362. * @param key the unique key that identifies the data
  27363. * @param data the data object to associate to the key for this Engine instance
  27364. * @return true if no such key were already present and the data was added successfully, false otherwise
  27365. */
  27366. Scene.prototype.addExternalData = function (key, data) {
  27367. if (!this._externalData) {
  27368. this._externalData = new BABYLON.StringDictionary();
  27369. }
  27370. return this._externalData.add(key, data);
  27371. };
  27372. /**
  27373. * Get an externaly attached data from its key
  27374. * @param key the unique key that identifies the data
  27375. * @return the associated data, if present (can be null), or undefined if not present
  27376. */
  27377. Scene.prototype.getExternalData = function (key) {
  27378. if (!this._externalData) {
  27379. return null;
  27380. }
  27381. return this._externalData.get(key);
  27382. };
  27383. /**
  27384. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27385. * @param key the unique key that identifies the data
  27386. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27387. * @return the associated data, can be null if the factory returned null.
  27388. */
  27389. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27390. if (!this._externalData) {
  27391. this._externalData = new BABYLON.StringDictionary();
  27392. }
  27393. return this._externalData.getOrAddWithFactory(key, factory);
  27394. };
  27395. /**
  27396. * Remove an externaly attached data from the Engine instance
  27397. * @param key the unique key that identifies the data
  27398. * @return true if the data was successfully removed, false if it doesn't exist
  27399. */
  27400. Scene.prototype.removeExternalData = function (key) {
  27401. return this._externalData.remove(key);
  27402. };
  27403. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27404. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27405. if (mesh.showSubMeshesBoundingBox) {
  27406. var boundingInfo = subMesh.getBoundingInfo();
  27407. if (boundingInfo !== null && boundingInfo !== undefined) {
  27408. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27409. }
  27410. }
  27411. var material = subMesh.getMaterial();
  27412. if (material !== null && material !== undefined) {
  27413. // Render targets
  27414. if (material.getRenderTargetTextures !== undefined) {
  27415. if (this._processedMaterials.indexOf(material) === -1) {
  27416. this._processedMaterials.push(material);
  27417. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27418. }
  27419. }
  27420. // Dispatch
  27421. this._activeIndices.addCount(subMesh.indexCount, false);
  27422. this._renderingManager.dispatch(subMesh, mesh, material);
  27423. }
  27424. }
  27425. };
  27426. /**
  27427. * Clear the processed materials smart array preventing retention point in material dispose.
  27428. */
  27429. Scene.prototype.freeProcessedMaterials = function () {
  27430. this._processedMaterials.dispose();
  27431. };
  27432. /**
  27433. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27434. */
  27435. Scene.prototype.freeActiveMeshes = function () {
  27436. this._activeMeshes.dispose();
  27437. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27438. this.activeCamera._activeMeshes.dispose();
  27439. }
  27440. if (this.activeCameras) {
  27441. for (var i = 0; i < this.activeCameras.length; i++) {
  27442. var activeCamera = this.activeCameras[i];
  27443. if (activeCamera && activeCamera._activeMeshes) {
  27444. activeCamera._activeMeshes.dispose();
  27445. }
  27446. }
  27447. }
  27448. };
  27449. /**
  27450. * Clear the info related to rendering groups preventing retention points during dispose.
  27451. */
  27452. Scene.prototype.freeRenderingGroups = function () {
  27453. if (this._renderingManager) {
  27454. this._renderingManager.freeRenderingGroups();
  27455. }
  27456. if (this.textures) {
  27457. for (var i = 0; i < this.textures.length; i++) {
  27458. var texture = this.textures[i];
  27459. if (texture && texture.renderList) {
  27460. texture.freeRenderingGroups();
  27461. }
  27462. }
  27463. }
  27464. };
  27465. /** @hidden */
  27466. Scene.prototype._isInIntermediateRendering = function () {
  27467. return this._intermediateRendering;
  27468. };
  27469. /**
  27470. * Defines the current active mesh candidate provider
  27471. * @param provider defines the provider to use
  27472. */
  27473. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27474. this._activeMeshCandidateProvider = provider;
  27475. };
  27476. /**
  27477. * Gets the current active mesh candidate provider
  27478. * @returns the current active mesh candidate provider
  27479. */
  27480. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27481. return this._activeMeshCandidateProvider;
  27482. };
  27483. /**
  27484. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27485. * @returns the current scene
  27486. */
  27487. Scene.prototype.freezeActiveMeshes = function () {
  27488. if (!this.activeCamera) {
  27489. return this;
  27490. }
  27491. if (!this._frustumPlanes) {
  27492. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27493. }
  27494. this._evaluateActiveMeshes();
  27495. this._activeMeshesFrozen = true;
  27496. return this;
  27497. };
  27498. /**
  27499. * Use this function to restart evaluating active meshes on every frame
  27500. * @returns the current scene
  27501. */
  27502. Scene.prototype.unfreezeActiveMeshes = function () {
  27503. this._activeMeshesFrozen = false;
  27504. return this;
  27505. };
  27506. Scene.prototype._evaluateActiveMeshes = function () {
  27507. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27508. return;
  27509. }
  27510. if (!this.activeCamera) {
  27511. return;
  27512. }
  27513. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27514. this.activeCamera._activeMeshes.reset();
  27515. this._activeMeshes.reset();
  27516. this._renderingManager.reset();
  27517. this._processedMaterials.reset();
  27518. this._activeParticleSystems.reset();
  27519. this._activeSkeletons.reset();
  27520. this._softwareSkinnedMeshes.reset();
  27521. if (this._boundingBoxRenderer) {
  27522. this._boundingBoxRenderer.reset();
  27523. }
  27524. // Meshes
  27525. var meshes;
  27526. var len;
  27527. var checkIsEnabled = true;
  27528. // Determine mesh candidates
  27529. if (this._activeMeshCandidateProvider !== undefined) {
  27530. // Use _activeMeshCandidateProvider
  27531. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27532. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27533. if (meshes !== undefined) {
  27534. len = meshes.length;
  27535. }
  27536. else {
  27537. len = 0;
  27538. }
  27539. }
  27540. else if (this._selectionOctree !== undefined) {
  27541. // Octree
  27542. var selection = this._selectionOctree.select(this._frustumPlanes);
  27543. meshes = selection.data;
  27544. len = selection.length;
  27545. }
  27546. else {
  27547. // Full scene traversal
  27548. len = this.meshes.length;
  27549. meshes = this.meshes;
  27550. }
  27551. // Check each mesh
  27552. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27553. mesh = meshes[meshIndex];
  27554. if (mesh.isBlocked) {
  27555. continue;
  27556. }
  27557. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27558. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27559. continue;
  27560. }
  27561. mesh.computeWorldMatrix();
  27562. // Intersections
  27563. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27564. this._meshesForIntersections.pushNoDuplicate(mesh);
  27565. }
  27566. // Switch to current LOD
  27567. meshLOD = mesh.getLOD(this.activeCamera);
  27568. if (meshLOD === undefined || meshLOD === null) {
  27569. continue;
  27570. }
  27571. mesh._preActivate();
  27572. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27573. this._activeMeshes.push(mesh);
  27574. this.activeCamera._activeMeshes.push(mesh);
  27575. mesh._activate(this._renderId);
  27576. if (meshLOD !== mesh) {
  27577. meshLOD._activate(this._renderId);
  27578. }
  27579. this._activeMesh(mesh, meshLOD);
  27580. }
  27581. }
  27582. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27583. // Particle systems
  27584. if (this.particlesEnabled) {
  27585. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27586. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27587. var particleSystem = this.particleSystems[particleIndex];
  27588. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27589. continue;
  27590. }
  27591. var emitter = particleSystem.emitter;
  27592. if (!emitter.position || emitter.isEnabled()) {
  27593. this._activeParticleSystems.push(particleSystem);
  27594. particleSystem.animate();
  27595. this._renderingManager.dispatchParticles(particleSystem);
  27596. }
  27597. }
  27598. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27599. }
  27600. };
  27601. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27602. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27603. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27604. mesh.skeleton.prepare();
  27605. }
  27606. if (!mesh.computeBonesUsingShaders) {
  27607. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27608. }
  27609. }
  27610. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27611. var boundingInfo = sourceMesh.getBoundingInfo();
  27612. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27613. }
  27614. if (mesh !== undefined && mesh !== null
  27615. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27616. // Submeshes Octrees
  27617. var len;
  27618. var subMeshes;
  27619. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27620. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27621. len = intersections.length;
  27622. subMeshes = intersections.data;
  27623. }
  27624. else {
  27625. subMeshes = mesh.subMeshes;
  27626. len = subMeshes.length;
  27627. }
  27628. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27629. subMesh = subMeshes[subIndex];
  27630. this._evaluateSubMesh(subMesh, mesh);
  27631. }
  27632. }
  27633. };
  27634. /**
  27635. * Update the transform matrix to update from the current active camera
  27636. * @param force defines a boolean used to force the update even if cache is up to date
  27637. */
  27638. Scene.prototype.updateTransformMatrix = function (force) {
  27639. if (!this.activeCamera) {
  27640. return;
  27641. }
  27642. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27643. };
  27644. /**
  27645. * 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)
  27646. * @param alternateCamera defines the camera to use
  27647. */
  27648. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27649. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27650. };
  27651. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27652. if (camera && camera._skipRendering) {
  27653. return;
  27654. }
  27655. var engine = this._engine;
  27656. this.activeCamera = camera;
  27657. if (!this.activeCamera)
  27658. throw new Error("Active camera not set");
  27659. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27660. // Viewport
  27661. engine.setViewport(this.activeCamera.viewport);
  27662. // Camera
  27663. this.resetCachedMaterial();
  27664. this._renderId++;
  27665. this.updateTransformMatrix();
  27666. if (camera._alternateCamera) {
  27667. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27668. this._alternateRendering = true;
  27669. }
  27670. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27671. // Meshes
  27672. this._evaluateActiveMeshes();
  27673. // Software skinning
  27674. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27675. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27676. mesh.applySkeleton(mesh.skeleton);
  27677. }
  27678. // Render targets
  27679. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27680. var needsRestoreFrameBuffer = false;
  27681. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27682. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27683. }
  27684. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27685. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27686. }
  27687. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27688. this._intermediateRendering = true;
  27689. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27690. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27691. var renderTarget = this._renderTargets.data[renderIndex];
  27692. if (renderTarget._shouldRender()) {
  27693. this._renderId++;
  27694. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27695. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27696. }
  27697. }
  27698. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27699. this._intermediateRendering = false;
  27700. this._renderId++;
  27701. needsRestoreFrameBuffer = true; // Restore back buffer
  27702. }
  27703. // Render EffecttLayer Texture
  27704. var stencilState = this._engine.getStencilBuffer();
  27705. var renderEffects = false;
  27706. var needStencil = false;
  27707. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27708. this._intermediateRendering = true;
  27709. for (var i = 0; i < this.effectLayers.length; i++) {
  27710. var effectLayer = this.effectLayers[i];
  27711. if (effectLayer.shouldRender() &&
  27712. (!effectLayer.camera ||
  27713. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27714. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27715. renderEffects = true;
  27716. needStencil = needStencil || effectLayer.needStencil();
  27717. var renderTarget = effectLayer._mainTexture;
  27718. if (renderTarget._shouldRender()) {
  27719. this._renderId++;
  27720. renderTarget.render(false, false);
  27721. needsRestoreFrameBuffer = true;
  27722. }
  27723. }
  27724. }
  27725. this._intermediateRendering = false;
  27726. this._renderId++;
  27727. }
  27728. if (needsRestoreFrameBuffer) {
  27729. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27730. }
  27731. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27732. // Prepare Frame
  27733. if (this.postProcessManager) {
  27734. this.postProcessManager._prepareFrame();
  27735. }
  27736. // Backgrounds
  27737. var layerIndex;
  27738. var layer;
  27739. if (this.layers.length) {
  27740. engine.setDepthBuffer(false);
  27741. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27742. layer = this.layers[layerIndex];
  27743. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27744. layer.render();
  27745. }
  27746. }
  27747. engine.setDepthBuffer(true);
  27748. }
  27749. // Activate effect Layer stencil
  27750. if (needStencil) {
  27751. this._engine.setStencilBuffer(true);
  27752. }
  27753. // Render
  27754. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27755. this._renderingManager.render(null, null, true, true);
  27756. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27757. // Restore effect Layer stencil
  27758. if (needStencil) {
  27759. this._engine.setStencilBuffer(stencilState);
  27760. }
  27761. // Bounding boxes
  27762. if (this._boundingBoxRenderer) {
  27763. this._boundingBoxRenderer.render();
  27764. }
  27765. // Lens flares
  27766. if (this.lensFlaresEnabled) {
  27767. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27768. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27769. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27770. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27771. lensFlareSystem.render();
  27772. }
  27773. }
  27774. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27775. }
  27776. // Effect Layer
  27777. if (renderEffects) {
  27778. engine.setDepthBuffer(false);
  27779. for (var i = 0; i < this.effectLayers.length; i++) {
  27780. if (this.effectLayers[i].shouldRender()) {
  27781. this.effectLayers[i].render();
  27782. }
  27783. }
  27784. engine.setDepthBuffer(true);
  27785. }
  27786. // Foregrounds
  27787. if (this.layers.length) {
  27788. engine.setDepthBuffer(false);
  27789. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27790. layer = this.layers[layerIndex];
  27791. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27792. layer.render();
  27793. }
  27794. }
  27795. engine.setDepthBuffer(true);
  27796. }
  27797. // Finalize frame
  27798. if (this.postProcessManager) {
  27799. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27800. }
  27801. // Reset some special arrays
  27802. this._renderTargets.reset();
  27803. this._alternateRendering = false;
  27804. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27805. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27806. };
  27807. Scene.prototype._processSubCameras = function (camera) {
  27808. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27809. this._renderForCamera(camera);
  27810. return;
  27811. }
  27812. // rig cameras
  27813. for (var index = 0; index < camera._rigCameras.length; index++) {
  27814. this._renderForCamera(camera._rigCameras[index], camera);
  27815. }
  27816. this.activeCamera = camera;
  27817. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27818. };
  27819. Scene.prototype._checkIntersections = function () {
  27820. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27821. var sourceMesh = this._meshesForIntersections.data[index];
  27822. if (!sourceMesh.actionManager) {
  27823. continue;
  27824. }
  27825. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27826. var action = sourceMesh.actionManager.actions[actionIndex];
  27827. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27828. var parameters = action.getTriggerParameter();
  27829. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27830. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27831. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27832. if (areIntersecting && currentIntersectionInProgress === -1) {
  27833. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27834. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27835. sourceMesh._intersectionsInProgress.push(otherMesh);
  27836. }
  27837. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27838. sourceMesh._intersectionsInProgress.push(otherMesh);
  27839. }
  27840. }
  27841. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27842. //They intersected, and now they don't.
  27843. //is this trigger an exit trigger? execute an event.
  27844. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27845. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27846. }
  27847. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27848. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27849. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27850. return otherMesh === parameterMesh;
  27851. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27852. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27853. }
  27854. }
  27855. }
  27856. }
  27857. }
  27858. };
  27859. /**
  27860. * Render the scene
  27861. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27862. */
  27863. Scene.prototype.render = function (updateCameras) {
  27864. if (updateCameras === void 0) { updateCameras = true; }
  27865. if (this.isDisposed) {
  27866. return;
  27867. }
  27868. this._activeParticles.fetchNewFrame();
  27869. this._totalVertices.fetchNewFrame();
  27870. this._activeIndices.fetchNewFrame();
  27871. this._activeBones.fetchNewFrame();
  27872. this._meshesForIntersections.reset();
  27873. this.resetCachedMaterial();
  27874. this.onBeforeAnimationsObservable.notifyObservers(this);
  27875. // Actions
  27876. if (this.actionManager) {
  27877. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27878. }
  27879. //Simplification Queue
  27880. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27881. this.simplificationQueue.executeNext();
  27882. }
  27883. if (this._engine.isDeterministicLockStep()) {
  27884. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27885. var defaultFPS = (60.0 / 1000.0);
  27886. var defaultFrameTime = 1000 / 60; // frame time in MS
  27887. if (this._physicsEngine) {
  27888. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27889. }
  27890. var stepsTaken = 0;
  27891. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27892. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27893. internalSteps = Math.min(internalSteps, maxSubSteps);
  27894. do {
  27895. this.onBeforeStepObservable.notifyObservers(this);
  27896. // Animations
  27897. this._animationRatio = defaultFrameTime * defaultFPS;
  27898. this._animate();
  27899. this.onAfterAnimationsObservable.notifyObservers(this);
  27900. // Physics
  27901. if (this._physicsEngine) {
  27902. this.onBeforePhysicsObservable.notifyObservers(this);
  27903. this._physicsEngine._step(defaultFrameTime / 1000);
  27904. this.onAfterPhysicsObservable.notifyObservers(this);
  27905. }
  27906. this.onAfterStepObservable.notifyObservers(this);
  27907. this._currentStepId++;
  27908. stepsTaken++;
  27909. deltaTime -= defaultFrameTime;
  27910. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27911. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27912. }
  27913. else {
  27914. // Animations
  27915. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27916. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27917. this._animate();
  27918. this.onAfterAnimationsObservable.notifyObservers(this);
  27919. // Physics
  27920. if (this._physicsEngine) {
  27921. this.onBeforePhysicsObservable.notifyObservers(this);
  27922. this._physicsEngine._step(deltaTime / 1000.0);
  27923. this.onAfterPhysicsObservable.notifyObservers(this);
  27924. }
  27925. }
  27926. // update gamepad manager
  27927. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27928. this._gamepadManager._checkGamepadsStatus();
  27929. }
  27930. // Update Cameras
  27931. if (updateCameras) {
  27932. if (this.activeCameras.length > 0) {
  27933. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27934. var camera = this.activeCameras[cameraIndex];
  27935. camera.update();
  27936. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27937. // rig cameras
  27938. for (var index = 0; index < camera._rigCameras.length; index++) {
  27939. camera._rigCameras[index].update();
  27940. }
  27941. }
  27942. }
  27943. }
  27944. else if (this.activeCamera) {
  27945. this.activeCamera.update();
  27946. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27947. // rig cameras
  27948. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27949. this.activeCamera._rigCameras[index].update();
  27950. }
  27951. }
  27952. }
  27953. }
  27954. // Before render
  27955. this.onBeforeRenderObservable.notifyObservers(this);
  27956. // Customs render targets
  27957. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27958. var engine = this.getEngine();
  27959. var currentActiveCamera = this.activeCamera;
  27960. if (this.renderTargetsEnabled) {
  27961. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27962. this._intermediateRendering = true;
  27963. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27964. var renderTarget = this.customRenderTargets[customIndex];
  27965. if (renderTarget._shouldRender()) {
  27966. this._renderId++;
  27967. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27968. if (!this.activeCamera)
  27969. throw new Error("Active camera not set");
  27970. // Viewport
  27971. engine.setViewport(this.activeCamera.viewport);
  27972. // Camera
  27973. this.updateTransformMatrix();
  27974. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27975. }
  27976. }
  27977. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27978. this._intermediateRendering = false;
  27979. this._renderId++;
  27980. }
  27981. // Restore back buffer
  27982. if (this.customRenderTargets.length > 0) {
  27983. engine.restoreDefaultFramebuffer();
  27984. }
  27985. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27986. this.activeCamera = currentActiveCamera;
  27987. // Procedural textures
  27988. if (this.proceduralTexturesEnabled) {
  27989. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27990. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27991. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27992. if (proceduralTexture._shouldRender()) {
  27993. proceduralTexture.render();
  27994. }
  27995. }
  27996. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27997. }
  27998. // Clear
  27999. if (this.autoClearDepthAndStencil || this.autoClear) {
  28000. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28001. }
  28002. // Shadows
  28003. if (this.shadowsEnabled) {
  28004. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28005. var light = this.lights[lightIndex];
  28006. var shadowGenerator = light.getShadowGenerator();
  28007. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28008. var shadowMap = (shadowGenerator.getShadowMap());
  28009. if (this.textures.indexOf(shadowMap) !== -1) {
  28010. this._renderTargets.push(shadowMap);
  28011. }
  28012. }
  28013. }
  28014. }
  28015. // Depth renderer
  28016. for (var key in this._depthRenderer) {
  28017. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28018. }
  28019. // Geometry renderer
  28020. if (this._geometryBufferRenderer) {
  28021. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28022. }
  28023. // RenderPipeline
  28024. if (this._postProcessRenderPipelineManager) {
  28025. this._postProcessRenderPipelineManager.update();
  28026. }
  28027. // Multi-cameras?
  28028. if (this.activeCameras.length > 0) {
  28029. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28030. if (cameraIndex > 0) {
  28031. this._engine.clear(null, false, true, true);
  28032. }
  28033. this._processSubCameras(this.activeCameras[cameraIndex]);
  28034. }
  28035. }
  28036. else {
  28037. if (!this.activeCamera) {
  28038. throw new Error("No camera defined");
  28039. }
  28040. this._processSubCameras(this.activeCamera);
  28041. }
  28042. // Intersection checks
  28043. this._checkIntersections();
  28044. // Update the audio listener attached to the camera
  28045. if (BABYLON.AudioEngine) {
  28046. this._updateAudioParameters();
  28047. }
  28048. // After render
  28049. if (this.afterRender) {
  28050. this.afterRender();
  28051. }
  28052. this.onAfterRenderObservable.notifyObservers(this);
  28053. // Cleaning
  28054. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28055. var data = this._toBeDisposed.data[index];
  28056. if (data) {
  28057. data.dispose();
  28058. }
  28059. this._toBeDisposed[index] = null;
  28060. }
  28061. this._toBeDisposed.reset();
  28062. if (this.dumpNextRenderTargets) {
  28063. this.dumpNextRenderTargets = false;
  28064. }
  28065. this._activeBones.addCount(0, true);
  28066. this._activeIndices.addCount(0, true);
  28067. this._activeParticles.addCount(0, true);
  28068. };
  28069. Scene.prototype._updateAudioParameters = function () {
  28070. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28071. return;
  28072. }
  28073. var listeningCamera;
  28074. var audioEngine = BABYLON.Engine.audioEngine;
  28075. if (this.activeCameras.length > 0) {
  28076. listeningCamera = this.activeCameras[0];
  28077. }
  28078. else {
  28079. listeningCamera = this.activeCamera;
  28080. }
  28081. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28082. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28083. // for VR cameras
  28084. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28085. listeningCamera = listeningCamera.rigCameras[0];
  28086. }
  28087. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28088. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28089. cameraDirection.normalize();
  28090. // To avoid some errors on GearVR
  28091. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28092. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28093. }
  28094. var i;
  28095. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28096. var sound = this.mainSoundTrack.soundCollection[i];
  28097. if (sound.useCustomAttenuation) {
  28098. sound.updateDistanceFromListener();
  28099. }
  28100. }
  28101. for (i = 0; i < this.soundTracks.length; i++) {
  28102. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28103. sound = this.soundTracks[i].soundCollection[j];
  28104. if (sound.useCustomAttenuation) {
  28105. sound.updateDistanceFromListener();
  28106. }
  28107. }
  28108. }
  28109. }
  28110. };
  28111. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28112. // Audio
  28113. /**
  28114. * Gets or sets if audio support is enabled
  28115. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28116. */
  28117. get: function () {
  28118. return this._audioEnabled;
  28119. },
  28120. set: function (value) {
  28121. this._audioEnabled = value;
  28122. if (BABYLON.AudioEngine) {
  28123. if (this._audioEnabled) {
  28124. this._enableAudio();
  28125. }
  28126. else {
  28127. this._disableAudio();
  28128. }
  28129. }
  28130. },
  28131. enumerable: true,
  28132. configurable: true
  28133. });
  28134. Scene.prototype._disableAudio = function () {
  28135. var i;
  28136. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28137. this.mainSoundTrack.soundCollection[i].pause();
  28138. }
  28139. for (i = 0; i < this.soundTracks.length; i++) {
  28140. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28141. this.soundTracks[i].soundCollection[j].pause();
  28142. }
  28143. }
  28144. };
  28145. Scene.prototype._enableAudio = function () {
  28146. var i;
  28147. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28148. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28149. this.mainSoundTrack.soundCollection[i].play();
  28150. }
  28151. }
  28152. for (i = 0; i < this.soundTracks.length; i++) {
  28153. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28154. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28155. this.soundTracks[i].soundCollection[j].play();
  28156. }
  28157. }
  28158. }
  28159. };
  28160. Object.defineProperty(Scene.prototype, "headphone", {
  28161. /**
  28162. * Gets or sets if audio will be output to headphones
  28163. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28164. */
  28165. get: function () {
  28166. return this._headphone;
  28167. },
  28168. set: function (value) {
  28169. this._headphone = value;
  28170. if (BABYLON.AudioEngine) {
  28171. if (this._headphone) {
  28172. this._switchAudioModeForHeadphones();
  28173. }
  28174. else {
  28175. this._switchAudioModeForNormalSpeakers();
  28176. }
  28177. }
  28178. },
  28179. enumerable: true,
  28180. configurable: true
  28181. });
  28182. Scene.prototype._switchAudioModeForHeadphones = function () {
  28183. this.mainSoundTrack.switchPanningModelToHRTF();
  28184. for (var i = 0; i < this.soundTracks.length; i++) {
  28185. this.soundTracks[i].switchPanningModelToHRTF();
  28186. }
  28187. };
  28188. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28189. this.mainSoundTrack.switchPanningModelToEqualPower();
  28190. for (var i = 0; i < this.soundTracks.length; i++) {
  28191. this.soundTracks[i].switchPanningModelToEqualPower();
  28192. }
  28193. };
  28194. /**
  28195. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28196. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28197. * @returns the created depth renderer
  28198. */
  28199. Scene.prototype.enableDepthRenderer = function (camera) {
  28200. camera = camera || this.activeCamera;
  28201. if (!camera) {
  28202. throw "No camera available to enable depth renderer";
  28203. }
  28204. if (!this._depthRenderer[camera.id]) {
  28205. var textureType = 0;
  28206. if (this._engine.getCaps().textureHalfFloatRender) {
  28207. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28208. }
  28209. else if (this._engine.getCaps().textureFloatRender) {
  28210. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28211. }
  28212. else {
  28213. throw "Depth renderer does not support int texture type";
  28214. }
  28215. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28216. }
  28217. return this._depthRenderer[camera.id];
  28218. };
  28219. /**
  28220. * Disables a depth renderer for a given camera
  28221. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28222. */
  28223. Scene.prototype.disableDepthRenderer = function (camera) {
  28224. camera = camera || this.activeCamera;
  28225. if (!camera || !this._depthRenderer[camera.id]) {
  28226. return;
  28227. }
  28228. this._depthRenderer[camera.id].dispose();
  28229. delete this._depthRenderer[camera.id];
  28230. };
  28231. /**
  28232. * Enables a GeometryBufferRender and associates it with the scene
  28233. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28234. * @returns the GeometryBufferRenderer
  28235. */
  28236. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28237. if (ratio === void 0) { ratio = 1; }
  28238. if (this._geometryBufferRenderer) {
  28239. return this._geometryBufferRenderer;
  28240. }
  28241. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28242. if (!this._geometryBufferRenderer.isSupported) {
  28243. this._geometryBufferRenderer = null;
  28244. }
  28245. return this._geometryBufferRenderer;
  28246. };
  28247. /**
  28248. * Disables the GeometryBufferRender associated with the scene
  28249. */
  28250. Scene.prototype.disableGeometryBufferRenderer = function () {
  28251. if (!this._geometryBufferRenderer) {
  28252. return;
  28253. }
  28254. this._geometryBufferRenderer.dispose();
  28255. this._geometryBufferRenderer = null;
  28256. };
  28257. /**
  28258. * Freeze all materials
  28259. * A frozen material will not be updatable but should be faster to render
  28260. */
  28261. Scene.prototype.freezeMaterials = function () {
  28262. for (var i = 0; i < this.materials.length; i++) {
  28263. this.materials[i].freeze();
  28264. }
  28265. };
  28266. /**
  28267. * Unfreeze all materials
  28268. * A frozen material will not be updatable but should be faster to render
  28269. */
  28270. Scene.prototype.unfreezeMaterials = function () {
  28271. for (var i = 0; i < this.materials.length; i++) {
  28272. this.materials[i].unfreeze();
  28273. }
  28274. };
  28275. /**
  28276. * Releases all held ressources
  28277. */
  28278. Scene.prototype.dispose = function () {
  28279. this.beforeRender = null;
  28280. this.afterRender = null;
  28281. this.skeletons = [];
  28282. this.morphTargetManagers = [];
  28283. this.importedMeshesFiles = new Array();
  28284. this.stopAllAnimations();
  28285. this.resetCachedMaterial();
  28286. for (var key in this._depthRenderer) {
  28287. this._depthRenderer[key].dispose();
  28288. }
  28289. if (this._gamepadManager) {
  28290. this._gamepadManager.dispose();
  28291. this._gamepadManager = null;
  28292. }
  28293. // Smart arrays
  28294. if (this.activeCamera) {
  28295. this.activeCamera._activeMeshes.dispose();
  28296. this.activeCamera = null;
  28297. }
  28298. this._activeMeshes.dispose();
  28299. this._renderingManager.dispose();
  28300. this._processedMaterials.dispose();
  28301. this._activeParticleSystems.dispose();
  28302. this._activeSkeletons.dispose();
  28303. this._softwareSkinnedMeshes.dispose();
  28304. this._renderTargets.dispose();
  28305. this._registeredForLateAnimationBindings.dispose();
  28306. if (this._boundingBoxRenderer) {
  28307. this._boundingBoxRenderer.dispose();
  28308. }
  28309. this._meshesForIntersections.dispose();
  28310. this._toBeDisposed.dispose();
  28311. // Abort active requests
  28312. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28313. var request = _a[_i];
  28314. request.abort();
  28315. }
  28316. // Debug layer
  28317. if (this._debugLayer) {
  28318. this._debugLayer.hide();
  28319. }
  28320. // Events
  28321. this.onDisposeObservable.notifyObservers(this);
  28322. this.onDisposeObservable.clear();
  28323. this.onBeforeRenderObservable.clear();
  28324. this.onAfterRenderObservable.clear();
  28325. this.onBeforeRenderTargetsRenderObservable.clear();
  28326. this.onAfterRenderTargetsRenderObservable.clear();
  28327. this.onAfterStepObservable.clear();
  28328. this.onBeforeStepObservable.clear();
  28329. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28330. this.onAfterActiveMeshesEvaluationObservable.clear();
  28331. this.onBeforeParticlesRenderingObservable.clear();
  28332. this.onAfterParticlesRenderingObservable.clear();
  28333. this.onBeforeSpritesRenderingObservable.clear();
  28334. this.onAfterSpritesRenderingObservable.clear();
  28335. this.onBeforeDrawPhaseObservable.clear();
  28336. this.onAfterDrawPhaseObservable.clear();
  28337. this.onBeforePhysicsObservable.clear();
  28338. this.onAfterPhysicsObservable.clear();
  28339. this.onBeforeAnimationsObservable.clear();
  28340. this.onAfterAnimationsObservable.clear();
  28341. this.onDataLoadedObservable.clear();
  28342. this.detachControl();
  28343. // Release sounds & sounds tracks
  28344. if (BABYLON.AudioEngine) {
  28345. this.disposeSounds();
  28346. }
  28347. // VR Helper
  28348. if (this.VRHelper) {
  28349. this.VRHelper.dispose();
  28350. }
  28351. // Detach cameras
  28352. var canvas = this._engine.getRenderingCanvas();
  28353. if (canvas) {
  28354. var index;
  28355. for (index = 0; index < this.cameras.length; index++) {
  28356. this.cameras[index].detachControl(canvas);
  28357. }
  28358. }
  28359. // Release animation groups
  28360. while (this.animationGroups.length) {
  28361. this.animationGroups[0].dispose();
  28362. }
  28363. // Release lights
  28364. while (this.lights.length) {
  28365. this.lights[0].dispose();
  28366. }
  28367. // Release meshes
  28368. while (this.meshes.length) {
  28369. this.meshes[0].dispose(true);
  28370. }
  28371. while (this.transformNodes.length) {
  28372. this.removeTransformNode(this.transformNodes[0]);
  28373. }
  28374. // Release cameras
  28375. while (this.cameras.length) {
  28376. this.cameras[0].dispose();
  28377. }
  28378. // Release materials
  28379. if (this.defaultMaterial) {
  28380. this.defaultMaterial.dispose();
  28381. }
  28382. while (this.multiMaterials.length) {
  28383. this.multiMaterials[0].dispose();
  28384. }
  28385. while (this.materials.length) {
  28386. this.materials[0].dispose();
  28387. }
  28388. // Release particles
  28389. while (this.particleSystems.length) {
  28390. this.particleSystems[0].dispose();
  28391. }
  28392. // Release sprites
  28393. while (this.spriteManagers.length) {
  28394. this.spriteManagers[0].dispose();
  28395. }
  28396. // Release postProcesses
  28397. while (this.postProcesses.length) {
  28398. this.postProcesses[0].dispose();
  28399. }
  28400. // Release layers
  28401. while (this.layers.length) {
  28402. this.layers[0].dispose();
  28403. }
  28404. while (this.effectLayers.length) {
  28405. this.effectLayers[0].dispose();
  28406. }
  28407. // Release textures
  28408. while (this.textures.length) {
  28409. this.textures[0].dispose();
  28410. }
  28411. // Release UBO
  28412. this._sceneUbo.dispose();
  28413. if (this._alternateSceneUbo) {
  28414. this._alternateSceneUbo.dispose();
  28415. }
  28416. // Post-processes
  28417. this.postProcessManager.dispose();
  28418. if (this._postProcessRenderPipelineManager) {
  28419. this._postProcessRenderPipelineManager.dispose();
  28420. }
  28421. // Physics
  28422. if (this._physicsEngine) {
  28423. this.disablePhysicsEngine();
  28424. }
  28425. // Remove from engine
  28426. index = this._engine.scenes.indexOf(this);
  28427. if (index > -1) {
  28428. this._engine.scenes.splice(index, 1);
  28429. }
  28430. this._engine.wipeCaches(true);
  28431. this._isDisposed = true;
  28432. };
  28433. Object.defineProperty(Scene.prototype, "isDisposed", {
  28434. /**
  28435. * Gets if the scene is already disposed
  28436. */
  28437. get: function () {
  28438. return this._isDisposed;
  28439. },
  28440. enumerable: true,
  28441. configurable: true
  28442. });
  28443. /**
  28444. * Releases sounds & soundtracks
  28445. */
  28446. Scene.prototype.disposeSounds = function () {
  28447. if (!this._mainSoundTrack) {
  28448. return;
  28449. }
  28450. this.mainSoundTrack.dispose();
  28451. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28452. this.soundTracks[scIndex].dispose();
  28453. }
  28454. };
  28455. /**
  28456. * Call this function to reduce memory footprint of the scene.
  28457. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28458. */
  28459. Scene.prototype.clearCachedVertexData = function () {
  28460. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28461. var mesh = this.meshes[meshIndex];
  28462. var geometry = mesh.geometry;
  28463. if (geometry) {
  28464. geometry._indices = [];
  28465. for (var vbName in geometry._vertexBuffers) {
  28466. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28467. continue;
  28468. }
  28469. geometry._vertexBuffers[vbName]._buffer._data = null;
  28470. }
  28471. }
  28472. }
  28473. };
  28474. /**
  28475. * This function will remove the local cached buffer data from texture.
  28476. * It will save memory but will prevent the texture from being rebuilt
  28477. */
  28478. Scene.prototype.cleanCachedTextureBuffer = function () {
  28479. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28480. var baseTexture = _a[_i];
  28481. var buffer = baseTexture._buffer;
  28482. if (buffer) {
  28483. baseTexture._buffer = null;
  28484. }
  28485. }
  28486. };
  28487. // Octrees
  28488. /**
  28489. * Get the world extend vectors with an optional filter
  28490. *
  28491. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28492. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28493. */
  28494. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28495. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28496. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28497. filterPredicate = filterPredicate || (function () { return true; });
  28498. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28499. mesh.computeWorldMatrix(true);
  28500. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28501. return;
  28502. }
  28503. var boundingInfo = mesh.getBoundingInfo();
  28504. var minBox = boundingInfo.boundingBox.minimumWorld;
  28505. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28506. BABYLON.Tools.CheckExtends(minBox, min, max);
  28507. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28508. });
  28509. return {
  28510. min: min,
  28511. max: max
  28512. };
  28513. };
  28514. /**
  28515. * Creates or updates the octree used to boost selection (picking)
  28516. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28517. * @param maxCapacity defines the maximum capacity per leaf
  28518. * @param maxDepth defines the maximum depth of the octree
  28519. * @returns an octree of AbstractMesh
  28520. */
  28521. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28522. if (maxCapacity === void 0) { maxCapacity = 64; }
  28523. if (maxDepth === void 0) { maxDepth = 2; }
  28524. if (!this._selectionOctree) {
  28525. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28526. }
  28527. var worldExtends = this.getWorldExtends();
  28528. // Update octree
  28529. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28530. return this._selectionOctree;
  28531. };
  28532. // Picking
  28533. /**
  28534. * Creates a ray that can be used to pick in the scene
  28535. * @param x defines the x coordinate of the origin (on-screen)
  28536. * @param y defines the y coordinate of the origin (on-screen)
  28537. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28538. * @param camera defines the camera to use for the picking
  28539. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28540. * @returns a Ray
  28541. */
  28542. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28543. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28544. var result = BABYLON.Ray.Zero();
  28545. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28546. return result;
  28547. };
  28548. /**
  28549. * Creates a ray that can be used to pick in the scene
  28550. * @param x defines the x coordinate of the origin (on-screen)
  28551. * @param y defines the y coordinate of the origin (on-screen)
  28552. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28553. * @param result defines the ray where to store the picking ray
  28554. * @param camera defines the camera to use for the picking
  28555. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28556. * @returns the current scene
  28557. */
  28558. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28559. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28560. var engine = this._engine;
  28561. if (!camera) {
  28562. if (!this.activeCamera)
  28563. throw new Error("Active camera not set");
  28564. camera = this.activeCamera;
  28565. }
  28566. var cameraViewport = camera.viewport;
  28567. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28568. // Moving coordinates to local viewport world
  28569. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28570. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28571. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28572. return this;
  28573. };
  28574. /**
  28575. * Creates a ray that can be used to pick in the scene
  28576. * @param x defines the x coordinate of the origin (on-screen)
  28577. * @param y defines the y coordinate of the origin (on-screen)
  28578. * @param camera defines the camera to use for the picking
  28579. * @returns a Ray
  28580. */
  28581. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28582. var result = BABYLON.Ray.Zero();
  28583. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28584. return result;
  28585. };
  28586. /**
  28587. * Creates a ray that can be used to pick in the scene
  28588. * @param x defines the x coordinate of the origin (on-screen)
  28589. * @param y defines the y coordinate of the origin (on-screen)
  28590. * @param result defines the ray where to store the picking ray
  28591. * @param camera defines the camera to use for the picking
  28592. * @returns the current scene
  28593. */
  28594. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28595. if (!BABYLON.PickingInfo) {
  28596. return this;
  28597. }
  28598. var engine = this._engine;
  28599. if (!camera) {
  28600. if (!this.activeCamera)
  28601. throw new Error("Active camera not set");
  28602. camera = this.activeCamera;
  28603. }
  28604. var cameraViewport = camera.viewport;
  28605. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28606. var identity = BABYLON.Matrix.Identity();
  28607. // Moving coordinates to local viewport world
  28608. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28609. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28610. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28611. return this;
  28612. };
  28613. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28614. if (!BABYLON.PickingInfo) {
  28615. return null;
  28616. }
  28617. var pickingInfo = null;
  28618. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28619. var mesh = this.meshes[meshIndex];
  28620. if (predicate) {
  28621. if (!predicate(mesh)) {
  28622. continue;
  28623. }
  28624. }
  28625. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28626. continue;
  28627. }
  28628. var world = mesh.getWorldMatrix();
  28629. var ray = rayFunction(world);
  28630. var result = mesh.intersects(ray, fastCheck);
  28631. if (!result || !result.hit)
  28632. continue;
  28633. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28634. continue;
  28635. pickingInfo = result;
  28636. if (fastCheck) {
  28637. break;
  28638. }
  28639. }
  28640. return pickingInfo || new BABYLON.PickingInfo();
  28641. };
  28642. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28643. if (!BABYLON.PickingInfo) {
  28644. return null;
  28645. }
  28646. var pickingInfos = new Array();
  28647. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28648. var mesh = this.meshes[meshIndex];
  28649. if (predicate) {
  28650. if (!predicate(mesh)) {
  28651. continue;
  28652. }
  28653. }
  28654. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28655. continue;
  28656. }
  28657. var world = mesh.getWorldMatrix();
  28658. var ray = rayFunction(world);
  28659. var result = mesh.intersects(ray, false);
  28660. if (!result || !result.hit)
  28661. continue;
  28662. pickingInfos.push(result);
  28663. }
  28664. return pickingInfos;
  28665. };
  28666. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28667. if (!BABYLON.PickingInfo) {
  28668. return null;
  28669. }
  28670. var pickingInfo = null;
  28671. if (!camera) {
  28672. if (!this.activeCamera) {
  28673. return null;
  28674. }
  28675. camera = this.activeCamera;
  28676. }
  28677. if (this.spriteManagers.length > 0) {
  28678. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28679. var spriteManager = this.spriteManagers[spriteIndex];
  28680. if (!spriteManager.isPickable) {
  28681. continue;
  28682. }
  28683. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28684. if (!result || !result.hit)
  28685. continue;
  28686. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28687. continue;
  28688. pickingInfo = result;
  28689. if (fastCheck) {
  28690. break;
  28691. }
  28692. }
  28693. }
  28694. return pickingInfo || new BABYLON.PickingInfo();
  28695. };
  28696. /** Launch a ray to try to pick a mesh in the scene
  28697. * @param x position on screen
  28698. * @param y position on screen
  28699. * @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
  28700. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28701. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28702. * @returns a PickingInfo
  28703. */
  28704. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28705. var _this = this;
  28706. if (!BABYLON.PickingInfo) {
  28707. return null;
  28708. }
  28709. var result = this._internalPick(function (world) {
  28710. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28711. return _this._tempPickingRay;
  28712. }, predicate, fastCheck);
  28713. if (result) {
  28714. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28715. }
  28716. return result;
  28717. };
  28718. /** Launch a ray to try to pick a sprite in the scene
  28719. * @param x position on screen
  28720. * @param y position on screen
  28721. * @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
  28722. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28723. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28724. * @returns a PickingInfo
  28725. */
  28726. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28727. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28728. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28729. };
  28730. /** Use the given ray to pick a mesh in the scene
  28731. * @param ray The ray to use to pick meshes
  28732. * @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
  28733. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28734. * @returns a PickingInfo
  28735. */
  28736. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28737. var _this = this;
  28738. var result = this._internalPick(function (world) {
  28739. if (!_this._pickWithRayInverseMatrix) {
  28740. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28741. }
  28742. world.invertToRef(_this._pickWithRayInverseMatrix);
  28743. if (!_this._cachedRayForTransform) {
  28744. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28745. }
  28746. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28747. return _this._cachedRayForTransform;
  28748. }, predicate, fastCheck);
  28749. if (result) {
  28750. result.ray = ray;
  28751. }
  28752. return result;
  28753. };
  28754. /**
  28755. * Launch a ray to try to pick a mesh in the scene
  28756. * @param x X position on screen
  28757. * @param y Y position on screen
  28758. * @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
  28759. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28760. * @returns an array of PickingInfo
  28761. */
  28762. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28763. var _this = this;
  28764. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28765. };
  28766. /**
  28767. * Launch a ray to try to pick a mesh in the scene
  28768. * @param ray Ray to use
  28769. * @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
  28770. * @returns an array of PickingInfo
  28771. */
  28772. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28773. var _this = this;
  28774. return this._internalMultiPick(function (world) {
  28775. if (!_this._pickWithRayInverseMatrix) {
  28776. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28777. }
  28778. world.invertToRef(_this._pickWithRayInverseMatrix);
  28779. if (!_this._cachedRayForTransform) {
  28780. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28781. }
  28782. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28783. return _this._cachedRayForTransform;
  28784. }, predicate);
  28785. };
  28786. /**
  28787. * Force the value of meshUnderPointer
  28788. * @param mesh defines the mesh to use
  28789. */
  28790. Scene.prototype.setPointerOverMesh = function (mesh) {
  28791. if (this._pointerOverMesh === mesh) {
  28792. return;
  28793. }
  28794. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28795. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28796. }
  28797. this._pointerOverMesh = mesh;
  28798. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28799. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28800. }
  28801. };
  28802. /**
  28803. * Gets the mesh under the pointer
  28804. * @returns a Mesh or null if no mesh is under the pointer
  28805. */
  28806. Scene.prototype.getPointerOverMesh = function () {
  28807. return this._pointerOverMesh;
  28808. };
  28809. /**
  28810. * Force the sprite under the pointer
  28811. * @param sprite defines the sprite to use
  28812. */
  28813. Scene.prototype.setPointerOverSprite = function (sprite) {
  28814. if (this._pointerOverSprite === sprite) {
  28815. return;
  28816. }
  28817. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28818. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28819. }
  28820. this._pointerOverSprite = sprite;
  28821. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28822. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28823. }
  28824. };
  28825. /**
  28826. * Gets the sprite under the pointer
  28827. * @returns a Sprite or null if no sprite is under the pointer
  28828. */
  28829. Scene.prototype.getPointerOverSprite = function () {
  28830. return this._pointerOverSprite;
  28831. };
  28832. // Physics
  28833. /**
  28834. * Gets the current physics engine
  28835. * @returns a PhysicsEngine or null if none attached
  28836. */
  28837. Scene.prototype.getPhysicsEngine = function () {
  28838. return this._physicsEngine;
  28839. };
  28840. /**
  28841. * Enables physics to the current scene
  28842. * @param gravity defines the scene's gravity for the physics engine
  28843. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28844. * @return a boolean indicating if the physics engine was initialized
  28845. */
  28846. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28847. if (gravity === void 0) { gravity = null; }
  28848. if (this._physicsEngine) {
  28849. return true;
  28850. }
  28851. try {
  28852. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28853. return true;
  28854. }
  28855. catch (e) {
  28856. BABYLON.Tools.Error(e.message);
  28857. return false;
  28858. }
  28859. };
  28860. /**
  28861. * Disables and disposes the physics engine associated with the scene
  28862. */
  28863. Scene.prototype.disablePhysicsEngine = function () {
  28864. if (!this._physicsEngine) {
  28865. return;
  28866. }
  28867. this._physicsEngine.dispose();
  28868. this._physicsEngine = null;
  28869. };
  28870. /**
  28871. * Gets a boolean indicating if there is an active physics engine
  28872. * @returns a boolean indicating if there is an active physics engine
  28873. */
  28874. Scene.prototype.isPhysicsEnabled = function () {
  28875. return this._physicsEngine !== undefined;
  28876. };
  28877. /**
  28878. * Deletes a physics compound impostor
  28879. * @param compound defines the compound to delete
  28880. */
  28881. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28882. var mesh = compound.parts[0].mesh;
  28883. if (mesh.physicsImpostor) {
  28884. mesh.physicsImpostor.dispose( /*true*/);
  28885. mesh.physicsImpostor = null;
  28886. }
  28887. };
  28888. // Misc.
  28889. /** @hidden */
  28890. Scene.prototype._rebuildGeometries = function () {
  28891. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28892. var geometry = _a[_i];
  28893. geometry._rebuild();
  28894. }
  28895. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28896. var mesh = _c[_b];
  28897. mesh._rebuild();
  28898. }
  28899. if (this.postProcessManager) {
  28900. this.postProcessManager._rebuild();
  28901. }
  28902. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28903. var layer = _e[_d];
  28904. layer._rebuild();
  28905. }
  28906. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28907. var effectLayer = _g[_f];
  28908. effectLayer._rebuild();
  28909. }
  28910. if (this._boundingBoxRenderer) {
  28911. this._boundingBoxRenderer._rebuild();
  28912. }
  28913. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28914. var system = _j[_h];
  28915. system.rebuild();
  28916. }
  28917. if (this._postProcessRenderPipelineManager) {
  28918. this._postProcessRenderPipelineManager._rebuild();
  28919. }
  28920. };
  28921. /** @hidden */
  28922. Scene.prototype._rebuildTextures = function () {
  28923. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28924. var texture = _a[_i];
  28925. texture._rebuild();
  28926. }
  28927. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28928. };
  28929. /**
  28930. * Creates a default light for the scene.
  28931. * @param replace Whether to replace the existing lights in the scene.
  28932. */
  28933. Scene.prototype.createDefaultLight = function (replace) {
  28934. if (replace === void 0) { replace = false; }
  28935. // Dispose existing light in replace mode.
  28936. if (replace) {
  28937. if (this.lights) {
  28938. for (var i = 0; i < this.lights.length; i++) {
  28939. this.lights[i].dispose();
  28940. }
  28941. }
  28942. }
  28943. // Light
  28944. if (this.lights.length === 0) {
  28945. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28946. }
  28947. };
  28948. /**
  28949. * Creates a default camera for the scene.
  28950. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28951. * @param replace Whether to replace the existing active camera in the scene.
  28952. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28953. */
  28954. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28955. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28956. if (replace === void 0) { replace = false; }
  28957. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28958. // Dispose existing camera in replace mode.
  28959. if (replace) {
  28960. if (this.activeCamera) {
  28961. this.activeCamera.dispose();
  28962. this.activeCamera = null;
  28963. }
  28964. }
  28965. // Camera
  28966. if (!this.activeCamera) {
  28967. var worldExtends = this.getWorldExtends();
  28968. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28969. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28970. var camera;
  28971. var radius = worldSize.length() * 1.5;
  28972. // empty scene scenario!
  28973. if (!isFinite(radius)) {
  28974. radius = 1;
  28975. worldCenter.copyFromFloats(0, 0, 0);
  28976. }
  28977. if (createArcRotateCamera) {
  28978. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28979. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28980. arcRotateCamera.wheelPrecision = 100 / radius;
  28981. camera = arcRotateCamera;
  28982. }
  28983. else {
  28984. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28985. freeCamera.setTarget(worldCenter);
  28986. camera = freeCamera;
  28987. }
  28988. camera.minZ = radius * 0.01;
  28989. camera.maxZ = radius * 1000;
  28990. camera.speed = radius * 0.2;
  28991. this.activeCamera = camera;
  28992. var canvas = this.getEngine().getRenderingCanvas();
  28993. if (attachCameraControls && canvas) {
  28994. camera.attachControl(canvas);
  28995. }
  28996. }
  28997. };
  28998. /**
  28999. * Creates a default camera and a default light
  29000. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29001. * @param replace defines if the camera and/or light will replace the existing ones
  29002. * @param attachCameraControls defines if attachControl will be called on the new camera
  29003. */
  29004. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29005. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29006. if (replace === void 0) { replace = false; }
  29007. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29008. this.createDefaultLight(replace);
  29009. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29010. };
  29011. /**
  29012. * Creates a new sky box
  29013. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29014. * @param environmentTexture defines the texture to use as environment texture
  29015. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29016. * @param scale defines the overall scale of the skybox
  29017. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29018. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29019. * @returns a new mesh holding the sky box
  29020. */
  29021. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29022. if (pbr === void 0) { pbr = false; }
  29023. if (scale === void 0) { scale = 1000; }
  29024. if (blur === void 0) { blur = 0; }
  29025. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29026. if (!environmentTexture) {
  29027. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29028. return null;
  29029. }
  29030. if (setGlobalEnvTexture) {
  29031. if (environmentTexture) {
  29032. this.environmentTexture = environmentTexture;
  29033. }
  29034. }
  29035. // Skybox
  29036. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29037. if (pbr) {
  29038. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29039. hdrSkyboxMaterial.backFaceCulling = false;
  29040. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29041. if (hdrSkyboxMaterial.reflectionTexture) {
  29042. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29043. }
  29044. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29045. hdrSkyboxMaterial.disableLighting = true;
  29046. hdrSkyboxMaterial.twoSidedLighting = true;
  29047. hdrSkybox.infiniteDistance = true;
  29048. hdrSkybox.material = hdrSkyboxMaterial;
  29049. }
  29050. else {
  29051. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29052. skyboxMaterial.backFaceCulling = false;
  29053. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29054. if (skyboxMaterial.reflectionTexture) {
  29055. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29056. }
  29057. skyboxMaterial.disableLighting = true;
  29058. hdrSkybox.infiniteDistance = true;
  29059. hdrSkybox.material = skyboxMaterial;
  29060. }
  29061. return hdrSkybox;
  29062. };
  29063. /**
  29064. * Creates a new environment
  29065. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29066. * @param options defines the options you can use to configure the environment
  29067. * @returns the new EnvironmentHelper
  29068. */
  29069. Scene.prototype.createDefaultEnvironment = function (options) {
  29070. if (BABYLON.EnvironmentHelper) {
  29071. return new BABYLON.EnvironmentHelper(options, this);
  29072. }
  29073. return null;
  29074. };
  29075. /**
  29076. * Creates a new VREXperienceHelper
  29077. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29078. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29079. * @returns a new VREXperienceHelper
  29080. */
  29081. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29082. if (webVROptions === void 0) { webVROptions = {}; }
  29083. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29084. };
  29085. // Tags
  29086. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29087. if (tagsQuery === undefined) {
  29088. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29089. return list;
  29090. }
  29091. var listByTags = [];
  29092. forEach = forEach || (function (item) { return; });
  29093. for (var i in list) {
  29094. var item = list[i];
  29095. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29096. listByTags.push(item);
  29097. forEach(item);
  29098. }
  29099. }
  29100. return listByTags;
  29101. };
  29102. /**
  29103. * Get a list of meshes by tags
  29104. * @param tagsQuery defines the tags query to use
  29105. * @param forEach defines a predicate used to filter results
  29106. * @returns an array of Mesh
  29107. */
  29108. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29109. return this._getByTags(this.meshes, tagsQuery, forEach);
  29110. };
  29111. /**
  29112. * Get a list of cameras by tags
  29113. * @param tagsQuery defines the tags query to use
  29114. * @param forEach defines a predicate used to filter results
  29115. * @returns an array of Camera
  29116. */
  29117. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29118. return this._getByTags(this.cameras, tagsQuery, forEach);
  29119. };
  29120. /**
  29121. * Get a list of lights by tags
  29122. * @param tagsQuery defines the tags query to use
  29123. * @param forEach defines a predicate used to filter results
  29124. * @returns an array of Light
  29125. */
  29126. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29127. return this._getByTags(this.lights, tagsQuery, forEach);
  29128. };
  29129. /**
  29130. * Get a list of materials by tags
  29131. * @param tagsQuery defines the tags query to use
  29132. * @param forEach defines a predicate used to filter results
  29133. * @returns an array of Material
  29134. */
  29135. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29136. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29137. };
  29138. /**
  29139. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29140. * This allowed control for front to back rendering or reversly depending of the special needs.
  29141. *
  29142. * @param renderingGroupId The rendering group id corresponding to its index
  29143. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29144. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29145. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29146. */
  29147. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29148. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29149. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29150. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29151. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29152. };
  29153. /**
  29154. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29155. *
  29156. * @param renderingGroupId The rendering group id corresponding to its index
  29157. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29158. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29159. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29160. */
  29161. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29162. if (depth === void 0) { depth = true; }
  29163. if (stencil === void 0) { stencil = true; }
  29164. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29165. };
  29166. /**
  29167. * Will flag all materials as dirty to trigger new shader compilation
  29168. * @param flag defines the flag used to specify which material part must be marked as dirty
  29169. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29170. */
  29171. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29172. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29173. var material = _a[_i];
  29174. if (predicate && !predicate(material)) {
  29175. continue;
  29176. }
  29177. material.markAsDirty(flag);
  29178. }
  29179. };
  29180. /** @hidden */
  29181. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29182. var _this = this;
  29183. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29184. this._activeRequests.push(request);
  29185. request.onCompleteObservable.add(function (request) {
  29186. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29187. });
  29188. return request;
  29189. };
  29190. /** @hidden */
  29191. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29192. var _this = this;
  29193. return new Promise(function (resolve, reject) {
  29194. _this._loadFile(url, function (data) {
  29195. resolve(data);
  29196. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29197. reject(exception);
  29198. });
  29199. });
  29200. };
  29201. // Statics
  29202. Scene._FOGMODE_NONE = 0;
  29203. Scene._FOGMODE_EXP = 1;
  29204. Scene._FOGMODE_EXP2 = 2;
  29205. Scene._FOGMODE_LINEAR = 3;
  29206. Scene._uniqueIdCounter = 0;
  29207. /**
  29208. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29209. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29210. */
  29211. Scene.MinDeltaTime = 1.0;
  29212. /**
  29213. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29214. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29215. */
  29216. Scene.MaxDeltaTime = 1000.0;
  29217. /** The distance in pixel that you have to move to prevent some events */
  29218. Scene.DragMovementThreshold = 10; // in pixels
  29219. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29220. Scene.LongPressDelay = 500; // in milliseconds
  29221. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29222. Scene.DoubleClickDelay = 300; // in milliseconds
  29223. /** If you need to check double click without raising a single click at first click, enable this flag */
  29224. Scene.ExclusiveDoubleClickMode = false;
  29225. return Scene;
  29226. }());
  29227. BABYLON.Scene = Scene;
  29228. })(BABYLON || (BABYLON = {}));
  29229. //# sourceMappingURL=babylon.scene.js.map
  29230. var BABYLON;
  29231. (function (BABYLON) {
  29232. /**
  29233. * Set of assets to keep when moving a scene into an asset container.
  29234. */
  29235. var KeepAssets = /** @class */ (function () {
  29236. function KeepAssets() {
  29237. /**
  29238. * Cameras to keep.
  29239. */
  29240. this.cameras = new Array();
  29241. /**
  29242. * Lights to keep.
  29243. */
  29244. this.lights = new Array();
  29245. /**
  29246. * Meshes to keep.
  29247. */
  29248. this.meshes = new Array();
  29249. /**
  29250. * Skeletons to keep.
  29251. */
  29252. this.skeletons = new Array();
  29253. /**
  29254. * ParticleSystems to keep.
  29255. */
  29256. this.particleSystems = new Array();
  29257. /**
  29258. * Animations to keep.
  29259. */
  29260. this.animations = new Array();
  29261. /**
  29262. * AnimationGroups to keep.
  29263. */
  29264. this.animationGroups = new Array();
  29265. /**
  29266. * MultiMaterials to keep.
  29267. */
  29268. this.multiMaterials = new Array();
  29269. /**
  29270. * Materials to keep.
  29271. */
  29272. this.materials = new Array();
  29273. /**
  29274. * MorphTargetManagers to keep.
  29275. */
  29276. this.morphTargetManagers = new Array();
  29277. /**
  29278. * Geometries to keep.
  29279. */
  29280. this.geometries = new Array();
  29281. /**
  29282. * TransformNodes to keep.
  29283. */
  29284. this.transformNodes = new Array();
  29285. /**
  29286. * LensFlareSystems to keep.
  29287. */
  29288. this.lensFlareSystems = new Array();
  29289. /**
  29290. * ShadowGenerators to keep.
  29291. */
  29292. this.shadowGenerators = new Array();
  29293. /**
  29294. * ActionManagers to keep.
  29295. */
  29296. this.actionManagers = new Array();
  29297. /**
  29298. * Sounds to keep.
  29299. */
  29300. this.sounds = new Array();
  29301. /**
  29302. * Textures to keep.
  29303. */
  29304. this.textures = new Array();
  29305. /**
  29306. * Effect layers to keep.
  29307. */
  29308. this.effectLayers = new Array();
  29309. }
  29310. return KeepAssets;
  29311. }());
  29312. BABYLON.KeepAssets = KeepAssets;
  29313. /**
  29314. * Container with a set of assets that can be added or removed from a scene.
  29315. */
  29316. var AssetContainer = /** @class */ (function () {
  29317. /**
  29318. * Instantiates an AssetContainer.
  29319. * @param scene The scene the AssetContainer belongs to.
  29320. */
  29321. function AssetContainer(scene) {
  29322. // Objects
  29323. /**
  29324. * Cameras populated in the container.
  29325. */
  29326. this.cameras = new Array();
  29327. /**
  29328. * Lights populated in the container.
  29329. */
  29330. this.lights = new Array();
  29331. /**
  29332. * Meshes populated in the container.
  29333. */
  29334. this.meshes = new Array();
  29335. /**
  29336. * Skeletons populated in the container.
  29337. */
  29338. this.skeletons = new Array();
  29339. /**
  29340. * ParticleSystems populated in the container.
  29341. */
  29342. this.particleSystems = new Array();
  29343. /**
  29344. * Animations populated in the container.
  29345. */
  29346. this.animations = new Array();
  29347. /**
  29348. * AnimationGroups populated in the container.
  29349. */
  29350. this.animationGroups = new Array();
  29351. /**
  29352. * MultiMaterials populated in the container.
  29353. */
  29354. this.multiMaterials = new Array();
  29355. /**
  29356. * Materials populated in the container.
  29357. */
  29358. this.materials = new Array();
  29359. /**
  29360. * MorphTargetManagers populated in the container.
  29361. */
  29362. this.morphTargetManagers = new Array();
  29363. /**
  29364. * Geometries populated in the container.
  29365. */
  29366. this.geometries = new Array();
  29367. /**
  29368. * TransformNodes populated in the container.
  29369. */
  29370. this.transformNodes = new Array();
  29371. /**
  29372. * LensFlareSystems populated in the container.
  29373. */
  29374. this.lensFlareSystems = new Array();
  29375. /**
  29376. * ShadowGenerators populated in the container.
  29377. */
  29378. this.shadowGenerators = new Array();
  29379. /**
  29380. * ActionManagers populated in the container.
  29381. */
  29382. this.actionManagers = new Array();
  29383. /**
  29384. * Sounds populated in the container.
  29385. */
  29386. this.sounds = new Array();
  29387. /**
  29388. * Textures populated in the container.
  29389. */
  29390. this.textures = new Array();
  29391. /**
  29392. * Effect layers populated in the container.
  29393. */
  29394. this.effectLayers = new Array();
  29395. this.scene = scene;
  29396. }
  29397. /**
  29398. * Adds all the assets from the container to the scene.
  29399. */
  29400. AssetContainer.prototype.addAllToScene = function () {
  29401. var _this = this;
  29402. this.cameras.forEach(function (o) {
  29403. _this.scene.addCamera(o);
  29404. });
  29405. this.lights.forEach(function (o) {
  29406. _this.scene.addLight(o);
  29407. });
  29408. this.meshes.forEach(function (o) {
  29409. _this.scene.addMesh(o);
  29410. });
  29411. this.skeletons.forEach(function (o) {
  29412. _this.scene.addSkeleton(o);
  29413. });
  29414. this.particleSystems.forEach(function (o) {
  29415. _this.scene.addParticleSystem(o);
  29416. });
  29417. this.animations.forEach(function (o) {
  29418. _this.scene.addAnimation(o);
  29419. });
  29420. this.animationGroups.forEach(function (o) {
  29421. _this.scene.addAnimationGroup(o);
  29422. });
  29423. this.multiMaterials.forEach(function (o) {
  29424. _this.scene.addMultiMaterial(o);
  29425. });
  29426. this.materials.forEach(function (o) {
  29427. _this.scene.addMaterial(o);
  29428. });
  29429. this.morphTargetManagers.forEach(function (o) {
  29430. _this.scene.addMorphTargetManager(o);
  29431. });
  29432. this.geometries.forEach(function (o) {
  29433. _this.scene.addGeometry(o);
  29434. });
  29435. this.transformNodes.forEach(function (o) {
  29436. _this.scene.addTransformNode(o);
  29437. });
  29438. this.lensFlareSystems.forEach(function (o) {
  29439. _this.scene.addLensFlareSystem(o);
  29440. });
  29441. this.actionManagers.forEach(function (o) {
  29442. _this.scene.addActionManager(o);
  29443. });
  29444. this.sounds.forEach(function (o) {
  29445. o.play();
  29446. o.autoplay = true;
  29447. _this.scene.mainSoundTrack.AddSound(o);
  29448. });
  29449. this.textures.forEach(function (o) {
  29450. _this.scene.addTexture(o);
  29451. });
  29452. this.effectLayers.forEach(function (o) {
  29453. _this.scene.addEffectLayer(o);
  29454. });
  29455. };
  29456. /**
  29457. * Removes all the assets in the container from the scene
  29458. */
  29459. AssetContainer.prototype.removeAllFromScene = function () {
  29460. var _this = this;
  29461. this.cameras.forEach(function (o) {
  29462. _this.scene.removeCamera(o);
  29463. });
  29464. this.lights.forEach(function (o) {
  29465. _this.scene.removeLight(o);
  29466. });
  29467. this.meshes.forEach(function (o) {
  29468. _this.scene.removeMesh(o);
  29469. });
  29470. this.skeletons.forEach(function (o) {
  29471. _this.scene.removeSkeleton(o);
  29472. });
  29473. this.particleSystems.forEach(function (o) {
  29474. _this.scene.removeParticleSystem(o);
  29475. });
  29476. this.animations.forEach(function (o) {
  29477. _this.scene.removeAnimation(o);
  29478. });
  29479. this.animationGroups.forEach(function (o) {
  29480. _this.scene.removeAnimationGroup(o);
  29481. });
  29482. this.multiMaterials.forEach(function (o) {
  29483. _this.scene.removeMultiMaterial(o);
  29484. });
  29485. this.materials.forEach(function (o) {
  29486. _this.scene.removeMaterial(o);
  29487. });
  29488. this.morphTargetManagers.forEach(function (o) {
  29489. _this.scene.removeMorphTargetManager(o);
  29490. });
  29491. this.geometries.forEach(function (o) {
  29492. _this.scene.removeGeometry(o);
  29493. });
  29494. this.transformNodes.forEach(function (o) {
  29495. _this.scene.removeTransformNode(o);
  29496. });
  29497. this.lensFlareSystems.forEach(function (o) {
  29498. _this.scene.removeLensFlareSystem(o);
  29499. });
  29500. this.actionManagers.forEach(function (o) {
  29501. _this.scene.removeActionManager(o);
  29502. });
  29503. this.sounds.forEach(function (o) {
  29504. o.stop();
  29505. o.autoplay = false;
  29506. _this.scene.mainSoundTrack.RemoveSound(o);
  29507. });
  29508. this.textures.forEach(function (o) {
  29509. _this.scene.removeTexture(o);
  29510. });
  29511. this.effectLayers.forEach(function (o) {
  29512. _this.scene.removeEffectLayer(o);
  29513. });
  29514. };
  29515. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29516. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29517. var asset = sourceAssets_1[_i];
  29518. var move = true;
  29519. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29520. var keepAsset = keepAssets_1[_a];
  29521. if (asset === keepAsset) {
  29522. move = false;
  29523. break;
  29524. }
  29525. }
  29526. if (move) {
  29527. targetAssets.push(asset);
  29528. }
  29529. }
  29530. };
  29531. /**
  29532. * Removes all the assets contained in the scene and adds them to the container.
  29533. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29534. */
  29535. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29536. if (keepAssets === undefined) {
  29537. keepAssets = new KeepAssets();
  29538. }
  29539. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29540. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29541. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29542. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29543. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29544. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29545. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29546. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29547. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29548. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29549. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29550. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29551. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29552. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29553. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29554. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29555. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29556. this.removeAllFromScene();
  29557. };
  29558. /**
  29559. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29560. * @returns the root mesh
  29561. */
  29562. AssetContainer.prototype.createRootMesh = function () {
  29563. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29564. this.meshes.forEach(function (m) {
  29565. if (!m.parent) {
  29566. rootMesh.addChild(m);
  29567. }
  29568. });
  29569. this.meshes.unshift(rootMesh);
  29570. return rootMesh;
  29571. };
  29572. return AssetContainer;
  29573. }());
  29574. BABYLON.AssetContainer = AssetContainer;
  29575. })(BABYLON || (BABYLON = {}));
  29576. //# sourceMappingURL=babylon.assetContainer.js.map
  29577. var BABYLON;
  29578. (function (BABYLON) {
  29579. var Buffer = /** @class */ (function () {
  29580. /**
  29581. * Constructor
  29582. * @param engine the engine
  29583. * @param data the data to use for this buffer
  29584. * @param updatable whether the data is updatable
  29585. * @param stride the stride (optional)
  29586. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29587. * @param instanced whether the buffer is instanced (optional)
  29588. * @param useBytes set to true if the stride in in bytes (optional)
  29589. */
  29590. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29591. if (stride === void 0) { stride = 0; }
  29592. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29593. if (instanced === void 0) { instanced = false; }
  29594. if (useBytes === void 0) { useBytes = false; }
  29595. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29596. this._engine = engine.getScene().getEngine();
  29597. }
  29598. else {
  29599. this._engine = engine;
  29600. }
  29601. this._updatable = updatable;
  29602. this._instanced = instanced;
  29603. this._data = data;
  29604. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29605. if (!postponeInternalCreation) { // by default
  29606. this.create();
  29607. }
  29608. }
  29609. /**
  29610. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29611. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29612. * @param offset defines offset in the buffer (0 by default)
  29613. * @param size defines the size in floats of attributes (position is 3 for instance)
  29614. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29615. * @param instanced defines if the vertex buffer contains indexed data
  29616. * @param useBytes defines if the offset and stride are in bytes
  29617. * @returns the new vertex buffer
  29618. */
  29619. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29620. if (useBytes === void 0) { useBytes = false; }
  29621. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29622. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29623. // a lot of these parameters are ignored as they are overriden by the buffer
  29624. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29625. };
  29626. // Properties
  29627. Buffer.prototype.isUpdatable = function () {
  29628. return this._updatable;
  29629. };
  29630. Buffer.prototype.getData = function () {
  29631. return this._data;
  29632. };
  29633. Buffer.prototype.getBuffer = function () {
  29634. return this._buffer;
  29635. };
  29636. /**
  29637. * Gets the stride in float32 units (i.e. byte stride / 4).
  29638. * May not be an integer if the byte stride is not divisible by 4.
  29639. * DEPRECATED. Use byteStride instead.
  29640. * @returns the stride in float32 units
  29641. */
  29642. Buffer.prototype.getStrideSize = function () {
  29643. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29644. };
  29645. // Methods
  29646. Buffer.prototype.create = function (data) {
  29647. if (data === void 0) { data = null; }
  29648. if (!data && this._buffer) {
  29649. return; // nothing to do
  29650. }
  29651. data = data || this._data;
  29652. if (!data) {
  29653. return;
  29654. }
  29655. if (!this._buffer) { // create buffer
  29656. if (this._updatable) {
  29657. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29658. this._data = data;
  29659. }
  29660. else {
  29661. this._buffer = this._engine.createVertexBuffer(data);
  29662. }
  29663. }
  29664. else if (this._updatable) { // update buffer
  29665. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29666. this._data = data;
  29667. }
  29668. };
  29669. Buffer.prototype._rebuild = function () {
  29670. this._buffer = null;
  29671. this.create(this._data);
  29672. };
  29673. Buffer.prototype.update = function (data) {
  29674. this.create(data);
  29675. };
  29676. /**
  29677. * Updates the data directly.
  29678. * @param data the new data
  29679. * @param offset the new offset
  29680. * @param vertexCount the vertex count (optional)
  29681. * @param useBytes set to true if the offset is in bytes
  29682. */
  29683. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29684. if (useBytes === void 0) { useBytes = false; }
  29685. if (!this._buffer) {
  29686. return;
  29687. }
  29688. if (this._updatable) { // update buffer
  29689. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29690. this._data = null;
  29691. }
  29692. };
  29693. Buffer.prototype.dispose = function () {
  29694. if (!this._buffer) {
  29695. return;
  29696. }
  29697. if (this._engine._releaseBuffer(this._buffer)) {
  29698. this._buffer = null;
  29699. }
  29700. };
  29701. return Buffer;
  29702. }());
  29703. BABYLON.Buffer = Buffer;
  29704. })(BABYLON || (BABYLON = {}));
  29705. //# sourceMappingURL=babylon.buffer.js.map
  29706. var BABYLON;
  29707. (function (BABYLON) {
  29708. var VertexBuffer = /** @class */ (function () {
  29709. /**
  29710. * Constructor
  29711. * @param engine the engine
  29712. * @param data the data to use for this vertex buffer
  29713. * @param kind the vertex buffer kind
  29714. * @param updatable whether the data is updatable
  29715. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29716. * @param stride the stride (optional)
  29717. * @param instanced whether the buffer is instanced (optional)
  29718. * @param offset the offset of the data (optional)
  29719. * @param size the number of components (optional)
  29720. * @param type the type of the component (optional)
  29721. * @param normalized whether the data contains normalized data (optional)
  29722. * @param useBytes set to true if stride and offset are in bytes (optional)
  29723. */
  29724. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29725. if (normalized === void 0) { normalized = false; }
  29726. if (useBytes === void 0) { useBytes = false; }
  29727. if (data instanceof BABYLON.Buffer) {
  29728. this._buffer = data;
  29729. this._ownsBuffer = false;
  29730. }
  29731. else {
  29732. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29733. this._ownsBuffer = true;
  29734. }
  29735. this._kind = kind;
  29736. if (type == undefined) {
  29737. var data_1 = this.getData();
  29738. this.type = VertexBuffer.FLOAT;
  29739. if (data_1 instanceof Int8Array)
  29740. this.type = VertexBuffer.BYTE;
  29741. else if (data_1 instanceof Uint8Array)
  29742. this.type = VertexBuffer.UNSIGNED_BYTE;
  29743. else if (data_1 instanceof Int16Array)
  29744. this.type = VertexBuffer.SHORT;
  29745. else if (data_1 instanceof Uint16Array)
  29746. this.type = VertexBuffer.UNSIGNED_SHORT;
  29747. else if (data_1 instanceof Int32Array)
  29748. this.type = VertexBuffer.INT;
  29749. else if (data_1 instanceof Uint32Array)
  29750. this.type = VertexBuffer.UNSIGNED_INT;
  29751. }
  29752. else {
  29753. this.type = type;
  29754. }
  29755. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29756. if (useBytes) {
  29757. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29758. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29759. this.byteOffset = offset || 0;
  29760. }
  29761. else {
  29762. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29763. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29764. this.byteOffset = (offset || 0) * typeByteLength;
  29765. }
  29766. this.normalized = normalized;
  29767. this._instanced = instanced !== undefined ? instanced : false;
  29768. this._instanceDivisor = instanced ? 1 : 0;
  29769. }
  29770. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29771. /**
  29772. * Gets or sets the instance divisor when in instanced mode
  29773. */
  29774. get: function () {
  29775. return this._instanceDivisor;
  29776. },
  29777. set: function (value) {
  29778. this._instanceDivisor = value;
  29779. if (value == 0) {
  29780. this._instanced = false;
  29781. }
  29782. else {
  29783. this._instanced = true;
  29784. }
  29785. },
  29786. enumerable: true,
  29787. configurable: true
  29788. });
  29789. VertexBuffer.prototype._rebuild = function () {
  29790. if (!this._buffer) {
  29791. return;
  29792. }
  29793. this._buffer._rebuild();
  29794. };
  29795. /**
  29796. * Returns the kind of the VertexBuffer (string).
  29797. */
  29798. VertexBuffer.prototype.getKind = function () {
  29799. return this._kind;
  29800. };
  29801. // Properties
  29802. /**
  29803. * Boolean : is the VertexBuffer updatable ?
  29804. */
  29805. VertexBuffer.prototype.isUpdatable = function () {
  29806. return this._buffer.isUpdatable();
  29807. };
  29808. /**
  29809. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29810. */
  29811. VertexBuffer.prototype.getData = function () {
  29812. return this._buffer.getData();
  29813. };
  29814. /**
  29815. * Returns the WebGLBuffer associated to the VertexBuffer.
  29816. */
  29817. VertexBuffer.prototype.getBuffer = function () {
  29818. return this._buffer.getBuffer();
  29819. };
  29820. /**
  29821. * Returns the stride as a multiple of the type byte length.
  29822. * DEPRECATED. Use byteStride instead.
  29823. */
  29824. VertexBuffer.prototype.getStrideSize = function () {
  29825. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29826. };
  29827. /**
  29828. * Returns the offset as a multiple of the type byte length.
  29829. * DEPRECATED. Use byteOffset instead.
  29830. */
  29831. VertexBuffer.prototype.getOffset = function () {
  29832. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29833. };
  29834. /**
  29835. * Returns the number of components per vertex attribute (integer).
  29836. */
  29837. VertexBuffer.prototype.getSize = function () {
  29838. return this._size;
  29839. };
  29840. /**
  29841. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29842. */
  29843. VertexBuffer.prototype.getIsInstanced = function () {
  29844. return this._instanced;
  29845. };
  29846. /**
  29847. * Returns the instancing divisor, zero for non-instanced (integer).
  29848. */
  29849. VertexBuffer.prototype.getInstanceDivisor = function () {
  29850. return this._instanceDivisor;
  29851. };
  29852. // Methods
  29853. /**
  29854. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29855. * Returns the created WebGLBuffer.
  29856. */
  29857. VertexBuffer.prototype.create = function (data) {
  29858. return this._buffer.create(data);
  29859. };
  29860. /**
  29861. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29862. * This function will create a new buffer if the current one is not updatable
  29863. * Returns the updated WebGLBuffer.
  29864. */
  29865. VertexBuffer.prototype.update = function (data) {
  29866. return this._buffer.update(data);
  29867. };
  29868. /**
  29869. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29870. * Returns the directly updated WebGLBuffer.
  29871. * @param data the new data
  29872. * @param offset the new offset
  29873. * @param useBytes set to true if the offset is in bytes
  29874. */
  29875. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29876. if (useBytes === void 0) { useBytes = false; }
  29877. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29878. };
  29879. /**
  29880. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29881. */
  29882. VertexBuffer.prototype.dispose = function () {
  29883. if (this._ownsBuffer) {
  29884. this._buffer.dispose();
  29885. }
  29886. };
  29887. /**
  29888. * Enumerates each value of this vertex buffer as numbers.
  29889. * @param count the number of values to enumerate
  29890. * @param callback the callback function called for each value
  29891. */
  29892. VertexBuffer.prototype.forEach = function (count, callback) {
  29893. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29894. };
  29895. Object.defineProperty(VertexBuffer, "PositionKind", {
  29896. get: function () {
  29897. return VertexBuffer._PositionKind;
  29898. },
  29899. enumerable: true,
  29900. configurable: true
  29901. });
  29902. Object.defineProperty(VertexBuffer, "NormalKind", {
  29903. get: function () {
  29904. return VertexBuffer._NormalKind;
  29905. },
  29906. enumerable: true,
  29907. configurable: true
  29908. });
  29909. Object.defineProperty(VertexBuffer, "TangentKind", {
  29910. get: function () {
  29911. return VertexBuffer._TangentKind;
  29912. },
  29913. enumerable: true,
  29914. configurable: true
  29915. });
  29916. Object.defineProperty(VertexBuffer, "UVKind", {
  29917. get: function () {
  29918. return VertexBuffer._UVKind;
  29919. },
  29920. enumerable: true,
  29921. configurable: true
  29922. });
  29923. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29924. get: function () {
  29925. return VertexBuffer._UV2Kind;
  29926. },
  29927. enumerable: true,
  29928. configurable: true
  29929. });
  29930. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29931. get: function () {
  29932. return VertexBuffer._UV3Kind;
  29933. },
  29934. enumerable: true,
  29935. configurable: true
  29936. });
  29937. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29938. get: function () {
  29939. return VertexBuffer._UV4Kind;
  29940. },
  29941. enumerable: true,
  29942. configurable: true
  29943. });
  29944. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29945. get: function () {
  29946. return VertexBuffer._UV5Kind;
  29947. },
  29948. enumerable: true,
  29949. configurable: true
  29950. });
  29951. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29952. get: function () {
  29953. return VertexBuffer._UV6Kind;
  29954. },
  29955. enumerable: true,
  29956. configurable: true
  29957. });
  29958. Object.defineProperty(VertexBuffer, "ColorKind", {
  29959. get: function () {
  29960. return VertexBuffer._ColorKind;
  29961. },
  29962. enumerable: true,
  29963. configurable: true
  29964. });
  29965. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29966. get: function () {
  29967. return VertexBuffer._MatricesIndicesKind;
  29968. },
  29969. enumerable: true,
  29970. configurable: true
  29971. });
  29972. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29973. get: function () {
  29974. return VertexBuffer._MatricesWeightsKind;
  29975. },
  29976. enumerable: true,
  29977. configurable: true
  29978. });
  29979. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29980. get: function () {
  29981. return VertexBuffer._MatricesIndicesExtraKind;
  29982. },
  29983. enumerable: true,
  29984. configurable: true
  29985. });
  29986. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29987. get: function () {
  29988. return VertexBuffer._MatricesWeightsExtraKind;
  29989. },
  29990. enumerable: true,
  29991. configurable: true
  29992. });
  29993. /**
  29994. * Deduces the stride given a kind.
  29995. * @param kind The kind string to deduce
  29996. * @returns The deduced stride
  29997. */
  29998. VertexBuffer.DeduceStride = function (kind) {
  29999. switch (kind) {
  30000. case VertexBuffer.UVKind:
  30001. case VertexBuffer.UV2Kind:
  30002. case VertexBuffer.UV3Kind:
  30003. case VertexBuffer.UV4Kind:
  30004. case VertexBuffer.UV5Kind:
  30005. case VertexBuffer.UV6Kind:
  30006. return 2;
  30007. case VertexBuffer.NormalKind:
  30008. case VertexBuffer.PositionKind:
  30009. return 3;
  30010. case VertexBuffer.ColorKind:
  30011. case VertexBuffer.MatricesIndicesKind:
  30012. case VertexBuffer.MatricesIndicesExtraKind:
  30013. case VertexBuffer.MatricesWeightsKind:
  30014. case VertexBuffer.MatricesWeightsExtraKind:
  30015. case VertexBuffer.TangentKind:
  30016. return 4;
  30017. default:
  30018. throw new Error("Invalid kind '" + kind + "'");
  30019. }
  30020. };
  30021. /**
  30022. * Gets the byte length of the given type.
  30023. * @param type the type
  30024. * @returns the number of bytes
  30025. */
  30026. VertexBuffer.GetTypeByteLength = function (type) {
  30027. switch (type) {
  30028. case VertexBuffer.BYTE:
  30029. case VertexBuffer.UNSIGNED_BYTE:
  30030. return 1;
  30031. case VertexBuffer.SHORT:
  30032. case VertexBuffer.UNSIGNED_SHORT:
  30033. return 2;
  30034. case VertexBuffer.INT:
  30035. case VertexBuffer.FLOAT:
  30036. return 4;
  30037. default:
  30038. throw new Error("Invalid type '" + type + "'");
  30039. }
  30040. };
  30041. /**
  30042. * Enumerates each value of the given parameters as numbers.
  30043. * @param data the data to enumerate
  30044. * @param byteOffset the byte offset of the data
  30045. * @param byteStride the byte stride of the data
  30046. * @param componentCount the number of components per element
  30047. * @param componentType the type of the component
  30048. * @param count the total number of components
  30049. * @param normalized whether the data is normalized
  30050. * @param callback the callback function called for each value
  30051. */
  30052. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30053. if (data instanceof Array) {
  30054. var offset = byteOffset / 4;
  30055. var stride = byteStride / 4;
  30056. for (var index = 0; index < count; index += componentCount) {
  30057. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30058. callback(data[offset + componentIndex], index + componentIndex);
  30059. }
  30060. offset += stride;
  30061. }
  30062. }
  30063. else {
  30064. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30065. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30066. for (var index = 0; index < count; index += componentCount) {
  30067. var componentByteOffset = byteOffset;
  30068. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30069. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30070. callback(value, index + componentIndex);
  30071. componentByteOffset += componentByteLength;
  30072. }
  30073. byteOffset += byteStride;
  30074. }
  30075. }
  30076. };
  30077. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30078. switch (type) {
  30079. case VertexBuffer.BYTE: {
  30080. var value = dataView.getInt8(byteOffset);
  30081. if (normalized) {
  30082. value = Math.max(value / 127, -1);
  30083. }
  30084. return value;
  30085. }
  30086. case VertexBuffer.UNSIGNED_BYTE: {
  30087. var value = dataView.getUint8(byteOffset);
  30088. if (normalized) {
  30089. value = value / 255;
  30090. }
  30091. return value;
  30092. }
  30093. case VertexBuffer.SHORT: {
  30094. var value = dataView.getInt16(byteOffset, true);
  30095. if (normalized) {
  30096. value = Math.max(value / 16383, -1);
  30097. }
  30098. return value;
  30099. }
  30100. case VertexBuffer.UNSIGNED_SHORT: {
  30101. var value = dataView.getUint16(byteOffset, true);
  30102. if (normalized) {
  30103. value = value / 65535;
  30104. }
  30105. return value;
  30106. }
  30107. case VertexBuffer.FLOAT: {
  30108. return dataView.getFloat32(byteOffset, true);
  30109. }
  30110. default: {
  30111. throw new Error("Invalid component type " + type);
  30112. }
  30113. }
  30114. };
  30115. /**
  30116. * The byte type.
  30117. */
  30118. VertexBuffer.BYTE = 5120;
  30119. /**
  30120. * The unsigned byte type.
  30121. */
  30122. VertexBuffer.UNSIGNED_BYTE = 5121;
  30123. /**
  30124. * The short type.
  30125. */
  30126. VertexBuffer.SHORT = 5122;
  30127. /**
  30128. * The unsigned short type.
  30129. */
  30130. VertexBuffer.UNSIGNED_SHORT = 5123;
  30131. /**
  30132. * The integer type.
  30133. */
  30134. VertexBuffer.INT = 5124;
  30135. /**
  30136. * The unsigned integer type.
  30137. */
  30138. VertexBuffer.UNSIGNED_INT = 5125;
  30139. /**
  30140. * The float type.
  30141. */
  30142. VertexBuffer.FLOAT = 5126;
  30143. // Enums
  30144. VertexBuffer._PositionKind = "position";
  30145. VertexBuffer._NormalKind = "normal";
  30146. VertexBuffer._TangentKind = "tangent";
  30147. VertexBuffer._UVKind = "uv";
  30148. VertexBuffer._UV2Kind = "uv2";
  30149. VertexBuffer._UV3Kind = "uv3";
  30150. VertexBuffer._UV4Kind = "uv4";
  30151. VertexBuffer._UV5Kind = "uv5";
  30152. VertexBuffer._UV6Kind = "uv6";
  30153. VertexBuffer._ColorKind = "color";
  30154. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30155. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30156. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30157. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30158. return VertexBuffer;
  30159. }());
  30160. BABYLON.VertexBuffer = VertexBuffer;
  30161. })(BABYLON || (BABYLON = {}));
  30162. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30163. var BABYLON;
  30164. (function (BABYLON) {
  30165. /**
  30166. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30167. */
  30168. var DummyInternalTextureTracker = /** @class */ (function () {
  30169. function DummyInternalTextureTracker() {
  30170. /**
  30171. * Gets or set the previous tracker in the list
  30172. */
  30173. this.previous = null;
  30174. /**
  30175. * Gets or set the next tracker in the list
  30176. */
  30177. this.next = null;
  30178. }
  30179. return DummyInternalTextureTracker;
  30180. }());
  30181. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30182. })(BABYLON || (BABYLON = {}));
  30183. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30184. var BABYLON;
  30185. (function (BABYLON) {
  30186. /**
  30187. * Class used to store data associated with WebGL texture data for the engine
  30188. * This class should not be used directly
  30189. */
  30190. var InternalTexture = /** @class */ (function () {
  30191. /**
  30192. * Creates a new InternalTexture
  30193. * @param engine defines the engine to use
  30194. * @param dataSource defines the type of data that will be used
  30195. */
  30196. function InternalTexture(engine, dataSource) {
  30197. /**
  30198. * Observable called when the texture is loaded
  30199. */
  30200. this.onLoadedObservable = new BABYLON.Observable();
  30201. /**
  30202. * Gets or set the previous tracker in the list
  30203. */
  30204. this.previous = null;
  30205. /**
  30206. * Gets or set the next tracker in the list
  30207. */
  30208. this.next = null;
  30209. // Private
  30210. /** @hidden */
  30211. this._initialSlot = -1;
  30212. /** @hidden */
  30213. this._designatedSlot = -1;
  30214. /** @hidden */
  30215. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30216. /** @hidden */
  30217. this._comparisonFunction = 0;
  30218. /** @hidden */
  30219. this._isRGBD = false;
  30220. /** @hidden */
  30221. this._references = 1;
  30222. this._engine = engine;
  30223. this._dataSource = dataSource;
  30224. this._webGLTexture = engine._createTexture();
  30225. }
  30226. /**
  30227. * Gets the Engine the texture belongs to.
  30228. * @returns The babylon engine
  30229. */
  30230. InternalTexture.prototype.getEngine = function () {
  30231. return this._engine;
  30232. };
  30233. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30234. /**
  30235. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30236. */
  30237. get: function () {
  30238. return this._dataSource;
  30239. },
  30240. enumerable: true,
  30241. configurable: true
  30242. });
  30243. /**
  30244. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30245. */
  30246. InternalTexture.prototype.incrementReferences = function () {
  30247. this._references++;
  30248. };
  30249. /**
  30250. * Change the size of the texture (not the size of the content)
  30251. * @param width defines the new width
  30252. * @param height defines the new height
  30253. * @param depth defines the new depth (1 by default)
  30254. */
  30255. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30256. if (depth === void 0) { depth = 1; }
  30257. this.width = width;
  30258. this.height = height;
  30259. this.depth = depth;
  30260. this.baseWidth = width;
  30261. this.baseHeight = height;
  30262. this.baseDepth = depth;
  30263. this._size = width * height * depth;
  30264. };
  30265. /** @hidden */
  30266. InternalTexture.prototype._rebuild = function () {
  30267. var _this = this;
  30268. var proxy;
  30269. this.isReady = false;
  30270. this._cachedCoordinatesMode = null;
  30271. this._cachedWrapU = null;
  30272. this._cachedWrapV = null;
  30273. this._cachedAnisotropicFilteringLevel = null;
  30274. switch (this._dataSource) {
  30275. case InternalTexture.DATASOURCE_TEMP:
  30276. return;
  30277. case InternalTexture.DATASOURCE_URL:
  30278. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30279. _this.isReady = true;
  30280. }, null, this._buffer, undefined, this.format);
  30281. proxy._swapAndDie(this);
  30282. return;
  30283. case InternalTexture.DATASOURCE_RAW:
  30284. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30285. proxy._swapAndDie(this);
  30286. this.isReady = true;
  30287. return;
  30288. case InternalTexture.DATASOURCE_RAW3D:
  30289. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30290. proxy._swapAndDie(this);
  30291. this.isReady = true;
  30292. return;
  30293. case InternalTexture.DATASOURCE_DYNAMIC:
  30294. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30295. proxy._swapAndDie(this);
  30296. // The engine will make sure to update content so no need to flag it as isReady = true
  30297. return;
  30298. case InternalTexture.DATASOURCE_RENDERTARGET:
  30299. var options = new BABYLON.RenderTargetCreationOptions();
  30300. options.generateDepthBuffer = this._generateDepthBuffer;
  30301. options.generateMipMaps = this.generateMipMaps;
  30302. options.generateStencilBuffer = this._generateStencilBuffer;
  30303. options.samplingMode = this.samplingMode;
  30304. options.type = this.type;
  30305. if (this.isCube) {
  30306. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30307. }
  30308. else {
  30309. var size = {
  30310. width: this.width,
  30311. height: this.height
  30312. };
  30313. proxy = this._engine.createRenderTargetTexture(size, options);
  30314. }
  30315. proxy._swapAndDie(this);
  30316. this.isReady = true;
  30317. return;
  30318. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30319. var depthTextureOptions = {
  30320. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30321. comparisonFunction: this._comparisonFunction,
  30322. generateStencil: this._generateStencilBuffer,
  30323. isCube: this.isCube
  30324. };
  30325. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30326. proxy._swapAndDie(this);
  30327. this.isReady = true;
  30328. return;
  30329. case InternalTexture.DATASOURCE_CUBE:
  30330. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30331. _this.isReady = true;
  30332. }, null, this.format, this._extension);
  30333. proxy._swapAndDie(this);
  30334. return;
  30335. case InternalTexture.DATASOURCE_CUBERAW:
  30336. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30337. proxy._swapAndDie(this);
  30338. this.isReady = true;
  30339. return;
  30340. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30341. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30342. if (proxy) {
  30343. proxy._swapAndDie(_this);
  30344. }
  30345. _this.isReady = true;
  30346. }, null, this.format, this._extension);
  30347. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30348. return;
  30349. }
  30350. };
  30351. InternalTexture.prototype._swapAndDie = function (target) {
  30352. target._webGLTexture = this._webGLTexture;
  30353. if (this._framebuffer) {
  30354. target._framebuffer = this._framebuffer;
  30355. }
  30356. if (this._depthStencilBuffer) {
  30357. target._depthStencilBuffer = this._depthStencilBuffer;
  30358. }
  30359. if (this._lodTextureHigh) {
  30360. if (target._lodTextureHigh) {
  30361. target._lodTextureHigh.dispose();
  30362. }
  30363. target._lodTextureHigh = this._lodTextureHigh;
  30364. }
  30365. if (this._lodTextureMid) {
  30366. if (target._lodTextureMid) {
  30367. target._lodTextureMid.dispose();
  30368. }
  30369. target._lodTextureMid = this._lodTextureMid;
  30370. }
  30371. if (this._lodTextureLow) {
  30372. if (target._lodTextureLow) {
  30373. target._lodTextureLow.dispose();
  30374. }
  30375. target._lodTextureLow = this._lodTextureLow;
  30376. }
  30377. var cache = this._engine.getLoadedTexturesCache();
  30378. var index = cache.indexOf(this);
  30379. if (index !== -1) {
  30380. cache.splice(index, 1);
  30381. }
  30382. };
  30383. /**
  30384. * Dispose the current allocated resources
  30385. */
  30386. InternalTexture.prototype.dispose = function () {
  30387. if (!this._webGLTexture) {
  30388. return;
  30389. }
  30390. this._references--;
  30391. if (this._references === 0) {
  30392. this._engine._releaseTexture(this);
  30393. this._webGLTexture = null;
  30394. this.previous = null;
  30395. this.next = null;
  30396. }
  30397. };
  30398. /**
  30399. * The source of the texture data is unknown
  30400. */
  30401. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30402. /**
  30403. * Texture data comes from an URL
  30404. */
  30405. InternalTexture.DATASOURCE_URL = 1;
  30406. /**
  30407. * Texture data is only used for temporary storage
  30408. */
  30409. InternalTexture.DATASOURCE_TEMP = 2;
  30410. /**
  30411. * Texture data comes from raw data (ArrayBuffer)
  30412. */
  30413. InternalTexture.DATASOURCE_RAW = 3;
  30414. /**
  30415. * Texture content is dynamic (video or dynamic texture)
  30416. */
  30417. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30418. /**
  30419. * Texture content is generated by rendering to it
  30420. */
  30421. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30422. /**
  30423. * Texture content is part of a multi render target process
  30424. */
  30425. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30426. /**
  30427. * Texture data comes from a cube data file
  30428. */
  30429. InternalTexture.DATASOURCE_CUBE = 7;
  30430. /**
  30431. * Texture data comes from a raw cube data
  30432. */
  30433. InternalTexture.DATASOURCE_CUBERAW = 8;
  30434. /**
  30435. * Texture data come from a prefiltered cube data file
  30436. */
  30437. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30438. /**
  30439. * Texture content is raw 3D data
  30440. */
  30441. InternalTexture.DATASOURCE_RAW3D = 10;
  30442. /**
  30443. * Texture content is a depth texture
  30444. */
  30445. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30446. return InternalTexture;
  30447. }());
  30448. BABYLON.InternalTexture = InternalTexture;
  30449. })(BABYLON || (BABYLON = {}));
  30450. //# sourceMappingURL=babylon.internalTexture.js.map
  30451. var BABYLON;
  30452. (function (BABYLON) {
  30453. var BaseTexture = /** @class */ (function () {
  30454. function BaseTexture(scene) {
  30455. this._hasAlpha = false;
  30456. this.getAlphaFromRGB = false;
  30457. this.level = 1;
  30458. this.coordinatesIndex = 0;
  30459. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30460. /**
  30461. * | Value | Type | Description |
  30462. * | ----- | ------------------ | ----------- |
  30463. * | 0 | CLAMP_ADDRESSMODE | |
  30464. * | 1 | WRAP_ADDRESSMODE | |
  30465. * | 2 | MIRROR_ADDRESSMODE | |
  30466. */
  30467. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30468. /**
  30469. * | Value | Type | Description |
  30470. * | ----- | ------------------ | ----------- |
  30471. * | 0 | CLAMP_ADDRESSMODE | |
  30472. * | 1 | WRAP_ADDRESSMODE | |
  30473. * | 2 | MIRROR_ADDRESSMODE | |
  30474. */
  30475. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30476. /**
  30477. * | Value | Type | Description |
  30478. * | ----- | ------------------ | ----------- |
  30479. * | 0 | CLAMP_ADDRESSMODE | |
  30480. * | 1 | WRAP_ADDRESSMODE | |
  30481. * | 2 | MIRROR_ADDRESSMODE | |
  30482. */
  30483. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30484. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30485. this.isCube = false;
  30486. this.is3D = false;
  30487. this.gammaSpace = true;
  30488. this.invertZ = false;
  30489. this.lodLevelInAlpha = false;
  30490. this.isRenderTarget = false;
  30491. this.animations = new Array();
  30492. /**
  30493. * An event triggered when the texture is disposed.
  30494. */
  30495. this.onDisposeObservable = new BABYLON.Observable();
  30496. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30497. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30498. if (this._scene) {
  30499. this._scene.textures.push(this);
  30500. }
  30501. this._uid = null;
  30502. }
  30503. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30504. get: function () {
  30505. return this._hasAlpha;
  30506. },
  30507. set: function (value) {
  30508. if (this._hasAlpha === value) {
  30509. return;
  30510. }
  30511. this._hasAlpha = value;
  30512. if (this._scene) {
  30513. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30514. }
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30520. get: function () {
  30521. return this._coordinatesMode;
  30522. },
  30523. /**
  30524. * How a texture is mapped.
  30525. *
  30526. * | Value | Type | Description |
  30527. * | ----- | ----------------------------------- | ----------- |
  30528. * | 0 | EXPLICIT_MODE | |
  30529. * | 1 | SPHERICAL_MODE | |
  30530. * | 2 | PLANAR_MODE | |
  30531. * | 3 | CUBIC_MODE | |
  30532. * | 4 | PROJECTION_MODE | |
  30533. * | 5 | SKYBOX_MODE | |
  30534. * | 6 | INVCUBIC_MODE | |
  30535. * | 7 | EQUIRECTANGULAR_MODE | |
  30536. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30537. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30538. */
  30539. set: function (value) {
  30540. if (this._coordinatesMode === value) {
  30541. return;
  30542. }
  30543. this._coordinatesMode = value;
  30544. if (this._scene) {
  30545. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30546. }
  30547. },
  30548. enumerable: true,
  30549. configurable: true
  30550. });
  30551. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30552. /**
  30553. * Gets whether or not the texture contains RGBD data.
  30554. */
  30555. get: function () {
  30556. return this._texture != null && this._texture._isRGBD;
  30557. },
  30558. enumerable: true,
  30559. configurable: true
  30560. });
  30561. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30562. get: function () {
  30563. if (this._texture)
  30564. return this._texture._lodGenerationOffset;
  30565. return 0.0;
  30566. },
  30567. set: function (value) {
  30568. if (this._texture)
  30569. this._texture._lodGenerationOffset = value;
  30570. },
  30571. enumerable: true,
  30572. configurable: true
  30573. });
  30574. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30575. get: function () {
  30576. if (this._texture)
  30577. return this._texture._lodGenerationScale;
  30578. return 0.0;
  30579. },
  30580. set: function (value) {
  30581. if (this._texture)
  30582. this._texture._lodGenerationScale = value;
  30583. },
  30584. enumerable: true,
  30585. configurable: true
  30586. });
  30587. Object.defineProperty(BaseTexture.prototype, "uid", {
  30588. get: function () {
  30589. if (!this._uid) {
  30590. this._uid = BABYLON.Tools.RandomId();
  30591. }
  30592. return this._uid;
  30593. },
  30594. enumerable: true,
  30595. configurable: true
  30596. });
  30597. BaseTexture.prototype.toString = function () {
  30598. return this.name;
  30599. };
  30600. BaseTexture.prototype.getClassName = function () {
  30601. return "BaseTexture";
  30602. };
  30603. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30604. set: function (callback) {
  30605. if (this._onDisposeObserver) {
  30606. this.onDisposeObservable.remove(this._onDisposeObserver);
  30607. }
  30608. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30609. },
  30610. enumerable: true,
  30611. configurable: true
  30612. });
  30613. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30614. get: function () {
  30615. return true;
  30616. },
  30617. enumerable: true,
  30618. configurable: true
  30619. });
  30620. BaseTexture.prototype.getScene = function () {
  30621. return this._scene;
  30622. };
  30623. BaseTexture.prototype.getTextureMatrix = function () {
  30624. return BABYLON.Matrix.IdentityReadOnly;
  30625. };
  30626. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30627. return BABYLON.Matrix.IdentityReadOnly;
  30628. };
  30629. BaseTexture.prototype.getInternalTexture = function () {
  30630. return this._texture;
  30631. };
  30632. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30633. return !this.isBlocking || this.isReady();
  30634. };
  30635. BaseTexture.prototype.isReady = function () {
  30636. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30637. this.delayLoad();
  30638. return false;
  30639. }
  30640. if (this._texture) {
  30641. return this._texture.isReady;
  30642. }
  30643. return false;
  30644. };
  30645. BaseTexture.prototype.getSize = function () {
  30646. if (this._texture && this._texture.width) {
  30647. return new BABYLON.Size(this._texture.width, this._texture.height);
  30648. }
  30649. if (this._texture && this._texture._size) {
  30650. return new BABYLON.Size(this._texture._size, this._texture._size);
  30651. }
  30652. return BABYLON.Size.Zero();
  30653. };
  30654. BaseTexture.prototype.getBaseSize = function () {
  30655. if (!this.isReady() || !this._texture)
  30656. return BABYLON.Size.Zero();
  30657. if (this._texture._size) {
  30658. return new BABYLON.Size(this._texture._size, this._texture._size);
  30659. }
  30660. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30661. };
  30662. BaseTexture.prototype.scale = function (ratio) {
  30663. };
  30664. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30665. get: function () {
  30666. return false;
  30667. },
  30668. enumerable: true,
  30669. configurable: true
  30670. });
  30671. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30672. if (!this._scene) {
  30673. return null;
  30674. }
  30675. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30676. for (var index = 0; index < texturesCache.length; index++) {
  30677. var texturesCacheEntry = texturesCache[index];
  30678. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30679. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30680. texturesCacheEntry.incrementReferences();
  30681. return texturesCacheEntry;
  30682. }
  30683. }
  30684. }
  30685. return null;
  30686. };
  30687. BaseTexture.prototype._rebuild = function () {
  30688. };
  30689. BaseTexture.prototype.delayLoad = function () {
  30690. };
  30691. BaseTexture.prototype.clone = function () {
  30692. return null;
  30693. };
  30694. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30695. get: function () {
  30696. if (!this._texture) {
  30697. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30698. }
  30699. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30700. },
  30701. enumerable: true,
  30702. configurable: true
  30703. });
  30704. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30705. get: function () {
  30706. if (!this._texture) {
  30707. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30708. }
  30709. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30710. },
  30711. enumerable: true,
  30712. configurable: true
  30713. });
  30714. /**
  30715. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30716. * This will returns an RGBA array buffer containing either in values (0-255) or
  30717. * float values (0-1) depending of the underlying buffer type.
  30718. * @param faceIndex The face of the texture to read (in case of cube texture)
  30719. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30720. * @returns The Array buffer containing the pixels data.
  30721. */
  30722. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30723. if (faceIndex === void 0) { faceIndex = 0; }
  30724. if (level === void 0) { level = 0; }
  30725. if (!this._texture) {
  30726. return null;
  30727. }
  30728. var size = this.getSize();
  30729. var width = size.width;
  30730. var height = size.height;
  30731. var scene = this.getScene();
  30732. if (!scene) {
  30733. return null;
  30734. }
  30735. var engine = scene.getEngine();
  30736. if (level != 0) {
  30737. width = width / Math.pow(2, level);
  30738. height = height / Math.pow(2, level);
  30739. width = Math.round(width);
  30740. height = Math.round(height);
  30741. }
  30742. if (this._texture.isCube) {
  30743. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30744. }
  30745. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30746. };
  30747. BaseTexture.prototype.releaseInternalTexture = function () {
  30748. if (this._texture) {
  30749. this._texture.dispose();
  30750. this._texture = null;
  30751. }
  30752. };
  30753. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30754. get: function () {
  30755. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30756. return null;
  30757. }
  30758. if (!this._texture._sphericalPolynomial) {
  30759. this._texture._sphericalPolynomial =
  30760. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30761. }
  30762. return this._texture._sphericalPolynomial;
  30763. },
  30764. set: function (value) {
  30765. if (this._texture) {
  30766. this._texture._sphericalPolynomial = value;
  30767. }
  30768. },
  30769. enumerable: true,
  30770. configurable: true
  30771. });
  30772. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30773. get: function () {
  30774. if (this._texture) {
  30775. return this._texture._lodTextureHigh;
  30776. }
  30777. return null;
  30778. },
  30779. enumerable: true,
  30780. configurable: true
  30781. });
  30782. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30783. get: function () {
  30784. if (this._texture) {
  30785. return this._texture._lodTextureMid;
  30786. }
  30787. return null;
  30788. },
  30789. enumerable: true,
  30790. configurable: true
  30791. });
  30792. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30793. get: function () {
  30794. if (this._texture) {
  30795. return this._texture._lodTextureLow;
  30796. }
  30797. return null;
  30798. },
  30799. enumerable: true,
  30800. configurable: true
  30801. });
  30802. BaseTexture.prototype.dispose = function () {
  30803. if (!this._scene) {
  30804. return;
  30805. }
  30806. // Animations
  30807. this._scene.stopAnimation(this);
  30808. // Remove from scene
  30809. this._scene._removePendingData(this);
  30810. var index = this._scene.textures.indexOf(this);
  30811. if (index >= 0) {
  30812. this._scene.textures.splice(index, 1);
  30813. }
  30814. if (this._texture === undefined) {
  30815. return;
  30816. }
  30817. // Release
  30818. this.releaseInternalTexture();
  30819. // Callback
  30820. this.onDisposeObservable.notifyObservers(this);
  30821. this.onDisposeObservable.clear();
  30822. };
  30823. BaseTexture.prototype.serialize = function () {
  30824. if (!this.name) {
  30825. return null;
  30826. }
  30827. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30828. // Animations
  30829. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30830. return serializationObject;
  30831. };
  30832. BaseTexture.WhenAllReady = function (textures, callback) {
  30833. var numRemaining = textures.length;
  30834. if (numRemaining === 0) {
  30835. callback();
  30836. return;
  30837. }
  30838. var _loop_1 = function () {
  30839. texture = textures[i];
  30840. if (texture.isReady()) {
  30841. if (--numRemaining === 0) {
  30842. callback();
  30843. }
  30844. }
  30845. else {
  30846. onLoadObservable = texture.onLoadObservable;
  30847. var onLoadCallback_1 = function () {
  30848. onLoadObservable.removeCallback(onLoadCallback_1);
  30849. if (--numRemaining === 0) {
  30850. callback();
  30851. }
  30852. };
  30853. onLoadObservable.add(onLoadCallback_1);
  30854. }
  30855. };
  30856. var texture, onLoadObservable;
  30857. for (var i = 0; i < textures.length; i++) {
  30858. _loop_1();
  30859. }
  30860. };
  30861. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30862. __decorate([
  30863. BABYLON.serialize()
  30864. ], BaseTexture.prototype, "name", void 0);
  30865. __decorate([
  30866. BABYLON.serialize("hasAlpha")
  30867. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30868. __decorate([
  30869. BABYLON.serialize()
  30870. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30871. __decorate([
  30872. BABYLON.serialize()
  30873. ], BaseTexture.prototype, "level", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30877. __decorate([
  30878. BABYLON.serialize("coordinatesMode")
  30879. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], BaseTexture.prototype, "wrapU", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], BaseTexture.prototype, "wrapV", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], BaseTexture.prototype, "wrapR", void 0);
  30889. __decorate([
  30890. BABYLON.serialize()
  30891. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30892. __decorate([
  30893. BABYLON.serialize()
  30894. ], BaseTexture.prototype, "isCube", void 0);
  30895. __decorate([
  30896. BABYLON.serialize()
  30897. ], BaseTexture.prototype, "is3D", void 0);
  30898. __decorate([
  30899. BABYLON.serialize()
  30900. ], BaseTexture.prototype, "gammaSpace", void 0);
  30901. __decorate([
  30902. BABYLON.serialize()
  30903. ], BaseTexture.prototype, "invertZ", void 0);
  30904. __decorate([
  30905. BABYLON.serialize()
  30906. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30907. __decorate([
  30908. BABYLON.serialize()
  30909. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30910. __decorate([
  30911. BABYLON.serialize()
  30912. ], BaseTexture.prototype, "lodGenerationScale", null);
  30913. __decorate([
  30914. BABYLON.serialize()
  30915. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30916. return BaseTexture;
  30917. }());
  30918. BABYLON.BaseTexture = BaseTexture;
  30919. })(BABYLON || (BABYLON = {}));
  30920. //# sourceMappingURL=babylon.baseTexture.js.map
  30921. var BABYLON;
  30922. (function (BABYLON) {
  30923. var Texture = /** @class */ (function (_super) {
  30924. __extends(Texture, _super);
  30925. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30926. if (noMipmap === void 0) { noMipmap = false; }
  30927. if (invertY === void 0) { invertY = true; }
  30928. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30929. if (onLoad === void 0) { onLoad = null; }
  30930. if (onError === void 0) { onError = null; }
  30931. if (buffer === void 0) { buffer = null; }
  30932. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30933. var _this = _super.call(this, scene) || this;
  30934. _this.uOffset = 0;
  30935. _this.vOffset = 0;
  30936. _this.uScale = 1.0;
  30937. _this.vScale = 1.0;
  30938. _this.uAng = 0;
  30939. _this.vAng = 0;
  30940. _this.wAng = 0;
  30941. /**
  30942. * Defines the center of rotation (U)
  30943. */
  30944. _this.uRotationCenter = 0.5;
  30945. /**
  30946. * Defines the center of rotation (V)
  30947. */
  30948. _this.vRotationCenter = 0.5;
  30949. /**
  30950. * Defines the center of rotation (W)
  30951. */
  30952. _this.wRotationCenter = 0.5;
  30953. _this._isBlocking = true;
  30954. _this.name = url || "";
  30955. _this.url = url;
  30956. _this._noMipmap = noMipmap;
  30957. _this._invertY = invertY;
  30958. _this._samplingMode = samplingMode;
  30959. _this._buffer = buffer;
  30960. _this._deleteBuffer = deleteBuffer;
  30961. if (format) {
  30962. _this._format = format;
  30963. }
  30964. scene = _this.getScene();
  30965. if (!scene) {
  30966. return _this;
  30967. }
  30968. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30969. var load = function () {
  30970. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30971. _this.onLoadObservable.notifyObservers(_this);
  30972. }
  30973. if (onLoad) {
  30974. onLoad();
  30975. }
  30976. if (!_this.isBlocking && scene) {
  30977. scene.resetCachedMaterial();
  30978. }
  30979. };
  30980. if (!_this.url) {
  30981. _this._delayedOnLoad = load;
  30982. _this._delayedOnError = onError;
  30983. return _this;
  30984. }
  30985. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30986. if (!_this._texture) {
  30987. if (!scene.useDelayedTextureLoading) {
  30988. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30989. if (deleteBuffer) {
  30990. delete _this._buffer;
  30991. }
  30992. }
  30993. else {
  30994. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30995. _this._delayedOnLoad = load;
  30996. _this._delayedOnError = onError;
  30997. }
  30998. }
  30999. else {
  31000. if (_this._texture.isReady) {
  31001. BABYLON.Tools.SetImmediate(function () { return load(); });
  31002. }
  31003. else {
  31004. _this._texture.onLoadedObservable.add(load);
  31005. }
  31006. }
  31007. return _this;
  31008. }
  31009. Object.defineProperty(Texture.prototype, "noMipmap", {
  31010. get: function () {
  31011. return this._noMipmap;
  31012. },
  31013. enumerable: true,
  31014. configurable: true
  31015. });
  31016. Object.defineProperty(Texture.prototype, "isBlocking", {
  31017. get: function () {
  31018. return this._isBlocking;
  31019. },
  31020. set: function (value) {
  31021. this._isBlocking = value;
  31022. },
  31023. enumerable: true,
  31024. configurable: true
  31025. });
  31026. Object.defineProperty(Texture.prototype, "samplingMode", {
  31027. get: function () {
  31028. return this._samplingMode;
  31029. },
  31030. enumerable: true,
  31031. configurable: true
  31032. });
  31033. /**
  31034. * Update the url (and optional buffer) of this texture if url was null during construction.
  31035. * @param url the url of the texture
  31036. * @param buffer the buffer of the texture (defaults to null)
  31037. */
  31038. Texture.prototype.updateURL = function (url, buffer) {
  31039. if (buffer === void 0) { buffer = null; }
  31040. if (this.url) {
  31041. throw new Error("URL is already set");
  31042. }
  31043. this.url = url;
  31044. this._buffer = buffer;
  31045. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31046. this.delayLoad();
  31047. };
  31048. Texture.prototype.delayLoad = function () {
  31049. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31050. return;
  31051. }
  31052. var scene = this.getScene();
  31053. if (!scene) {
  31054. return;
  31055. }
  31056. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31057. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31058. if (!this._texture) {
  31059. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31060. if (this._deleteBuffer) {
  31061. delete this._buffer;
  31062. }
  31063. }
  31064. else {
  31065. if (this._delayedOnLoad) {
  31066. if (this._texture.isReady) {
  31067. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31068. }
  31069. else {
  31070. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31071. }
  31072. }
  31073. }
  31074. this._delayedOnLoad = null;
  31075. this._delayedOnError = null;
  31076. };
  31077. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31078. if (!this._texture) {
  31079. return;
  31080. }
  31081. var scene = this.getScene();
  31082. if (!scene) {
  31083. return;
  31084. }
  31085. this._samplingMode = samplingMode;
  31086. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31087. };
  31088. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31089. x *= this.uScale;
  31090. y *= this.vScale;
  31091. x -= this.uRotationCenter * this.uScale;
  31092. y -= this.vRotationCenter * this.vScale;
  31093. z -= this.wRotationCenter;
  31094. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31095. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31096. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31097. t.z += this.wRotationCenter;
  31098. };
  31099. Texture.prototype.getTextureMatrix = function () {
  31100. var _this = this;
  31101. if (this.uOffset === this._cachedUOffset &&
  31102. this.vOffset === this._cachedVOffset &&
  31103. this.uScale === this._cachedUScale &&
  31104. this.vScale === this._cachedVScale &&
  31105. this.uAng === this._cachedUAng &&
  31106. this.vAng === this._cachedVAng &&
  31107. this.wAng === this._cachedWAng) {
  31108. return this._cachedTextureMatrix;
  31109. }
  31110. this._cachedUOffset = this.uOffset;
  31111. this._cachedVOffset = this.vOffset;
  31112. this._cachedUScale = this.uScale;
  31113. this._cachedVScale = this.vScale;
  31114. this._cachedUAng = this.uAng;
  31115. this._cachedVAng = this.vAng;
  31116. this._cachedWAng = this.wAng;
  31117. if (!this._cachedTextureMatrix) {
  31118. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31119. this._rowGenerationMatrix = new BABYLON.Matrix();
  31120. this._t0 = BABYLON.Vector3.Zero();
  31121. this._t1 = BABYLON.Vector3.Zero();
  31122. this._t2 = BABYLON.Vector3.Zero();
  31123. }
  31124. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31125. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31126. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31127. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31128. this._t1.subtractInPlace(this._t0);
  31129. this._t2.subtractInPlace(this._t0);
  31130. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31131. this._cachedTextureMatrix.m[0] = this._t1.x;
  31132. this._cachedTextureMatrix.m[1] = this._t1.y;
  31133. this._cachedTextureMatrix.m[2] = this._t1.z;
  31134. this._cachedTextureMatrix.m[4] = this._t2.x;
  31135. this._cachedTextureMatrix.m[5] = this._t2.y;
  31136. this._cachedTextureMatrix.m[6] = this._t2.z;
  31137. this._cachedTextureMatrix.m[8] = this._t0.x;
  31138. this._cachedTextureMatrix.m[9] = this._t0.y;
  31139. this._cachedTextureMatrix.m[10] = this._t0.z;
  31140. var scene = this.getScene();
  31141. if (!scene) {
  31142. return this._cachedTextureMatrix;
  31143. }
  31144. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31145. return mat.hasTexture(_this);
  31146. });
  31147. return this._cachedTextureMatrix;
  31148. };
  31149. Texture.prototype.getReflectionTextureMatrix = function () {
  31150. var _this = this;
  31151. var scene = this.getScene();
  31152. if (!scene) {
  31153. return this._cachedTextureMatrix;
  31154. }
  31155. if (this.uOffset === this._cachedUOffset &&
  31156. this.vOffset === this._cachedVOffset &&
  31157. this.uScale === this._cachedUScale &&
  31158. this.vScale === this._cachedVScale &&
  31159. this.coordinatesMode === this._cachedCoordinatesMode) {
  31160. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31161. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31162. return this._cachedTextureMatrix;
  31163. }
  31164. }
  31165. else {
  31166. return this._cachedTextureMatrix;
  31167. }
  31168. }
  31169. if (!this._cachedTextureMatrix) {
  31170. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31171. }
  31172. if (!this._projectionModeMatrix) {
  31173. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31174. }
  31175. this._cachedUOffset = this.uOffset;
  31176. this._cachedVOffset = this.vOffset;
  31177. this._cachedUScale = this.uScale;
  31178. this._cachedVScale = this.vScale;
  31179. this._cachedCoordinatesMode = this.coordinatesMode;
  31180. switch (this.coordinatesMode) {
  31181. case Texture.PLANAR_MODE:
  31182. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31183. this._cachedTextureMatrix[0] = this.uScale;
  31184. this._cachedTextureMatrix[5] = this.vScale;
  31185. this._cachedTextureMatrix[12] = this.uOffset;
  31186. this._cachedTextureMatrix[13] = this.vOffset;
  31187. break;
  31188. case Texture.PROJECTION_MODE:
  31189. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31190. this._projectionModeMatrix.m[0] = 0.5;
  31191. this._projectionModeMatrix.m[5] = -0.5;
  31192. this._projectionModeMatrix.m[10] = 0.0;
  31193. this._projectionModeMatrix.m[12] = 0.5;
  31194. this._projectionModeMatrix.m[13] = 0.5;
  31195. this._projectionModeMatrix.m[14] = 1.0;
  31196. this._projectionModeMatrix.m[15] = 1.0;
  31197. var projectionMatrix = scene.getProjectionMatrix();
  31198. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31199. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31200. break;
  31201. default:
  31202. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31203. break;
  31204. }
  31205. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31206. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31207. });
  31208. return this._cachedTextureMatrix;
  31209. };
  31210. Texture.prototype.clone = function () {
  31211. var _this = this;
  31212. return BABYLON.SerializationHelper.Clone(function () {
  31213. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31214. }, this);
  31215. };
  31216. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31217. get: function () {
  31218. if (!this._onLoadObservable) {
  31219. this._onLoadObservable = new BABYLON.Observable();
  31220. }
  31221. return this._onLoadObservable;
  31222. },
  31223. enumerable: true,
  31224. configurable: true
  31225. });
  31226. Texture.prototype.serialize = function () {
  31227. var serializationObject = _super.prototype.serialize.call(this);
  31228. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31229. serializationObject.base64String = this._buffer;
  31230. serializationObject.name = serializationObject.name.replace("data:", "");
  31231. }
  31232. serializationObject.invertY = this._invertY;
  31233. serializationObject.samplingMode = this.samplingMode;
  31234. return serializationObject;
  31235. };
  31236. Texture.prototype.getClassName = function () {
  31237. return "Texture";
  31238. };
  31239. Texture.prototype.dispose = function () {
  31240. _super.prototype.dispose.call(this);
  31241. if (this.onLoadObservable) {
  31242. this.onLoadObservable.clear();
  31243. this._onLoadObservable = null;
  31244. }
  31245. this._delayedOnLoad = null;
  31246. this._delayedOnError = null;
  31247. };
  31248. // Statics
  31249. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31250. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31251. if (onLoad === void 0) { onLoad = null; }
  31252. if (onError === void 0) { onError = null; }
  31253. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31254. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31255. };
  31256. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31257. if (parsedTexture.customType) {
  31258. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31259. // Update Sampling Mode
  31260. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31261. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31262. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31263. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31264. }
  31265. }
  31266. return parsedCustomTexture;
  31267. }
  31268. if (parsedTexture.isCube) {
  31269. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31270. }
  31271. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31272. return null;
  31273. }
  31274. var texture = BABYLON.SerializationHelper.Parse(function () {
  31275. var generateMipMaps = true;
  31276. if (parsedTexture.noMipmap) {
  31277. generateMipMaps = false;
  31278. }
  31279. if (parsedTexture.mirrorPlane) {
  31280. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31281. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31282. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31283. return mirrorTexture;
  31284. }
  31285. else if (parsedTexture.isRenderTarget) {
  31286. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31287. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31288. return renderTargetTexture;
  31289. }
  31290. else {
  31291. var texture;
  31292. if (parsedTexture.base64String) {
  31293. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31294. }
  31295. else {
  31296. var url = rootUrl + parsedTexture.name;
  31297. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31298. url = parsedTexture.url;
  31299. }
  31300. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31301. }
  31302. return texture;
  31303. }
  31304. }, parsedTexture, scene);
  31305. // Update Sampling Mode
  31306. if (parsedTexture.samplingMode) {
  31307. var sampling = parsedTexture.samplingMode;
  31308. if (texture._samplingMode !== sampling) {
  31309. texture.updateSamplingMode(sampling);
  31310. }
  31311. }
  31312. // Animations
  31313. if (parsedTexture.animations) {
  31314. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31315. var parsedAnimation = parsedTexture.animations[animationIndex];
  31316. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31317. }
  31318. }
  31319. return texture;
  31320. };
  31321. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31322. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31323. if (noMipmap === void 0) { noMipmap = false; }
  31324. if (invertY === void 0) { invertY = true; }
  31325. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31326. if (onLoad === void 0) { onLoad = null; }
  31327. if (onError === void 0) { onError = null; }
  31328. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31329. if (name.substr(0, 5) !== "data:") {
  31330. name = "data:" + name;
  31331. }
  31332. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31333. };
  31334. // Constants
  31335. Texture.NEAREST_SAMPLINGMODE = 1;
  31336. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31337. Texture.BILINEAR_SAMPLINGMODE = 2;
  31338. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31339. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31340. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31341. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31342. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31343. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31344. Texture.NEAREST_LINEAR = 7;
  31345. Texture.NEAREST_NEAREST = 8;
  31346. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31347. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31348. Texture.LINEAR_LINEAR = 11;
  31349. Texture.LINEAR_NEAREST = 12;
  31350. Texture.EXPLICIT_MODE = 0;
  31351. Texture.SPHERICAL_MODE = 1;
  31352. Texture.PLANAR_MODE = 2;
  31353. Texture.CUBIC_MODE = 3;
  31354. Texture.PROJECTION_MODE = 4;
  31355. Texture.SKYBOX_MODE = 5;
  31356. Texture.INVCUBIC_MODE = 6;
  31357. Texture.EQUIRECTANGULAR_MODE = 7;
  31358. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31359. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31360. Texture.CLAMP_ADDRESSMODE = 0;
  31361. Texture.WRAP_ADDRESSMODE = 1;
  31362. Texture.MIRROR_ADDRESSMODE = 2;
  31363. /**
  31364. * 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
  31365. */
  31366. Texture.UseSerializedUrlIfAny = false;
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], Texture.prototype, "url", void 0);
  31370. __decorate([
  31371. BABYLON.serialize()
  31372. ], Texture.prototype, "uOffset", void 0);
  31373. __decorate([
  31374. BABYLON.serialize()
  31375. ], Texture.prototype, "vOffset", void 0);
  31376. __decorate([
  31377. BABYLON.serialize()
  31378. ], Texture.prototype, "uScale", void 0);
  31379. __decorate([
  31380. BABYLON.serialize()
  31381. ], Texture.prototype, "vScale", void 0);
  31382. __decorate([
  31383. BABYLON.serialize()
  31384. ], Texture.prototype, "uAng", void 0);
  31385. __decorate([
  31386. BABYLON.serialize()
  31387. ], Texture.prototype, "vAng", void 0);
  31388. __decorate([
  31389. BABYLON.serialize()
  31390. ], Texture.prototype, "wAng", void 0);
  31391. __decorate([
  31392. BABYLON.serialize()
  31393. ], Texture.prototype, "uRotationCenter", void 0);
  31394. __decorate([
  31395. BABYLON.serialize()
  31396. ], Texture.prototype, "vRotationCenter", void 0);
  31397. __decorate([
  31398. BABYLON.serialize()
  31399. ], Texture.prototype, "wRotationCenter", void 0);
  31400. __decorate([
  31401. BABYLON.serialize()
  31402. ], Texture.prototype, "isBlocking", null);
  31403. return Texture;
  31404. }(BABYLON.BaseTexture));
  31405. BABYLON.Texture = Texture;
  31406. })(BABYLON || (BABYLON = {}));
  31407. //# sourceMappingURL=babylon.texture.js.map
  31408. var BABYLON;
  31409. (function (BABYLON) {
  31410. /**
  31411. * @hidden
  31412. **/
  31413. var _InstancesBatch = /** @class */ (function () {
  31414. function _InstancesBatch() {
  31415. this.mustReturn = false;
  31416. this.visibleInstances = new Array();
  31417. this.renderSelf = new Array();
  31418. }
  31419. return _InstancesBatch;
  31420. }());
  31421. BABYLON._InstancesBatch = _InstancesBatch;
  31422. var Mesh = /** @class */ (function (_super) {
  31423. __extends(Mesh, _super);
  31424. /**
  31425. * @constructor
  31426. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31427. * @param {Scene} scene The scene to add this mesh to.
  31428. * @param {Node} parent The parent of this mesh, if it has one
  31429. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31430. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31431. * When false, achieved by calling a clone(), also passing False.
  31432. * This will make creation of children, recursive.
  31433. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31434. */
  31435. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31436. if (scene === void 0) { scene = null; }
  31437. if (parent === void 0) { parent = null; }
  31438. if (source === void 0) { source = null; }
  31439. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31440. var _this = _super.call(this, name, scene) || this;
  31441. // Events
  31442. /**
  31443. * An event triggered before rendering the mesh
  31444. */
  31445. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31446. /**
  31447. * An event triggered after rendering the mesh
  31448. */
  31449. _this.onAfterRenderObservable = new BABYLON.Observable();
  31450. /**
  31451. * An event triggered before drawing the mesh
  31452. */
  31453. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31454. // Members
  31455. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31456. _this.instances = new Array();
  31457. _this._LODLevels = new Array();
  31458. _this._visibleInstances = {};
  31459. _this._renderIdForInstances = new Array();
  31460. _this._batchCache = new _InstancesBatch();
  31461. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31462. // Use by builder only to know what orientation were the mesh build in.
  31463. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31464. _this.overrideMaterialSideOrientation = null;
  31465. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31466. // Will be used to save a source mesh reference, If any
  31467. _this._source = null;
  31468. scene = _this.getScene();
  31469. if (source) {
  31470. // Geometry
  31471. if (source._geometry) {
  31472. source._geometry.applyToMesh(_this);
  31473. }
  31474. // Deep copy
  31475. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31476. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31477. // Source mesh
  31478. _this._source = source;
  31479. // Metadata
  31480. if (source.metadata && source.metadata.clone) {
  31481. _this.metadata = source.metadata.clone();
  31482. }
  31483. else {
  31484. _this.metadata = source.metadata;
  31485. }
  31486. // Tags
  31487. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31488. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31489. }
  31490. // Parent
  31491. _this.parent = source.parent;
  31492. // Pivot
  31493. _this.setPivotMatrix(source.getPivotMatrix());
  31494. _this.id = name + "." + source.id;
  31495. // Material
  31496. _this.material = source.material;
  31497. var index;
  31498. if (!doNotCloneChildren) {
  31499. // Children
  31500. var directDescendants = source.getDescendants(true);
  31501. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31502. var child = directDescendants[index_1];
  31503. if (child.clone) {
  31504. child.clone(name + "." + child.name, _this);
  31505. }
  31506. }
  31507. }
  31508. // Physics clone
  31509. var physicsEngine = _this.getScene().getPhysicsEngine();
  31510. if (clonePhysicsImpostor && physicsEngine) {
  31511. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31512. if (impostor) {
  31513. _this.physicsImpostor = impostor.clone(_this);
  31514. }
  31515. }
  31516. // Particles
  31517. for (index = 0; index < scene.particleSystems.length; index++) {
  31518. var system = scene.particleSystems[index];
  31519. if (system.emitter === source) {
  31520. system.clone(system.name, _this);
  31521. }
  31522. }
  31523. _this.computeWorldMatrix(true);
  31524. }
  31525. // Parent
  31526. if (parent !== null) {
  31527. _this.parent = parent;
  31528. }
  31529. return _this;
  31530. }
  31531. Object.defineProperty(Mesh, "FRONTSIDE", {
  31532. /**
  31533. * Mesh side orientation : usually the external or front surface
  31534. */
  31535. get: function () {
  31536. return Mesh._FRONTSIDE;
  31537. },
  31538. enumerable: true,
  31539. configurable: true
  31540. });
  31541. Object.defineProperty(Mesh, "BACKSIDE", {
  31542. /**
  31543. * Mesh side orientation : usually the internal or back surface
  31544. */
  31545. get: function () {
  31546. return Mesh._BACKSIDE;
  31547. },
  31548. enumerable: true,
  31549. configurable: true
  31550. });
  31551. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31552. /**
  31553. * Mesh side orientation : both internal and external or front and back surfaces
  31554. */
  31555. get: function () {
  31556. return Mesh._DOUBLESIDE;
  31557. },
  31558. enumerable: true,
  31559. configurable: true
  31560. });
  31561. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31562. /**
  31563. * Mesh side orientation : by default, `FRONTSIDE`
  31564. */
  31565. get: function () {
  31566. return Mesh._DEFAULTSIDE;
  31567. },
  31568. enumerable: true,
  31569. configurable: true
  31570. });
  31571. Object.defineProperty(Mesh, "NO_CAP", {
  31572. /**
  31573. * Mesh cap setting : no cap
  31574. */
  31575. get: function () {
  31576. return Mesh._NO_CAP;
  31577. },
  31578. enumerable: true,
  31579. configurable: true
  31580. });
  31581. Object.defineProperty(Mesh, "CAP_START", {
  31582. /**
  31583. * Mesh cap setting : one cap at the beginning of the mesh
  31584. */
  31585. get: function () {
  31586. return Mesh._CAP_START;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(Mesh, "CAP_END", {
  31592. /**
  31593. * Mesh cap setting : one cap at the end of the mesh
  31594. */
  31595. get: function () {
  31596. return Mesh._CAP_END;
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. Object.defineProperty(Mesh, "CAP_ALL", {
  31602. /**
  31603. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31604. */
  31605. get: function () {
  31606. return Mesh._CAP_ALL;
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31612. set: function (callback) {
  31613. if (this._onBeforeDrawObserver) {
  31614. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31615. }
  31616. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31617. },
  31618. enumerable: true,
  31619. configurable: true
  31620. });
  31621. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31622. get: function () {
  31623. return this._morphTargetManager;
  31624. },
  31625. set: function (value) {
  31626. if (this._morphTargetManager === value) {
  31627. return;
  31628. }
  31629. this._morphTargetManager = value;
  31630. this._syncGeometryWithMorphTargetManager();
  31631. },
  31632. enumerable: true,
  31633. configurable: true
  31634. });
  31635. Object.defineProperty(Mesh.prototype, "source", {
  31636. get: function () {
  31637. return this._source;
  31638. },
  31639. enumerable: true,
  31640. configurable: true
  31641. });
  31642. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31643. get: function () {
  31644. return this._unIndexed;
  31645. },
  31646. set: function (value) {
  31647. if (this._unIndexed !== value) {
  31648. this._unIndexed = value;
  31649. this._markSubMeshesAsAttributesDirty();
  31650. }
  31651. },
  31652. enumerable: true,
  31653. configurable: true
  31654. });
  31655. // Methods
  31656. /**
  31657. * Returns the string "Mesh".
  31658. */
  31659. Mesh.prototype.getClassName = function () {
  31660. return "Mesh";
  31661. };
  31662. /**
  31663. * Returns a string.
  31664. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31665. */
  31666. Mesh.prototype.toString = function (fullDetails) {
  31667. var ret = _super.prototype.toString.call(this, fullDetails);
  31668. ret += ", n vertices: " + this.getTotalVertices();
  31669. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31670. if (this.animations) {
  31671. for (var i = 0; i < this.animations.length; i++) {
  31672. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31673. }
  31674. }
  31675. if (fullDetails) {
  31676. if (this._geometry) {
  31677. var ib = this.getIndices();
  31678. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31679. if (vb && ib) {
  31680. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31681. }
  31682. }
  31683. else {
  31684. ret += ", flat shading: UNKNOWN";
  31685. }
  31686. }
  31687. return ret;
  31688. };
  31689. Mesh.prototype._unBindEffect = function () {
  31690. _super.prototype._unBindEffect.call(this);
  31691. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31692. var instance = _a[_i];
  31693. instance._unBindEffect();
  31694. }
  31695. };
  31696. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31697. /**
  31698. * True if the mesh has some Levels Of Details (LOD).
  31699. * Returns a boolean.
  31700. */
  31701. get: function () {
  31702. return this._LODLevels.length > 0;
  31703. },
  31704. enumerable: true,
  31705. configurable: true
  31706. });
  31707. /**
  31708. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31709. * @returns an array of {BABYLON.MeshLODLevel}
  31710. */
  31711. Mesh.prototype.getLODLevels = function () {
  31712. return this._LODLevels;
  31713. };
  31714. Mesh.prototype._sortLODLevels = function () {
  31715. this._LODLevels.sort(function (a, b) {
  31716. if (a.distance < b.distance) {
  31717. return 1;
  31718. }
  31719. if (a.distance > b.distance) {
  31720. return -1;
  31721. }
  31722. return 0;
  31723. });
  31724. };
  31725. /**
  31726. * Add a mesh as LOD level triggered at the given distance.
  31727. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31728. * @param distance The distance from the center of the object to show this level
  31729. * @param mesh The mesh to be added as LOD level (can be null)
  31730. * @return This mesh (for chaining)
  31731. */
  31732. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31733. if (mesh && mesh._masterMesh) {
  31734. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31735. return this;
  31736. }
  31737. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31738. this._LODLevels.push(level);
  31739. if (mesh) {
  31740. mesh._masterMesh = this;
  31741. }
  31742. this._sortLODLevels();
  31743. return this;
  31744. };
  31745. /**
  31746. * Returns the LOD level mesh at the passed distance or null if not found.
  31747. * It is related to the method `addLODLevel(distance, mesh)`.
  31748. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31749. * Returns an object Mesh or `null`.
  31750. */
  31751. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31752. for (var index = 0; index < this._LODLevels.length; index++) {
  31753. var level = this._LODLevels[index];
  31754. if (level.distance === distance) {
  31755. return level.mesh;
  31756. }
  31757. }
  31758. return null;
  31759. };
  31760. /**
  31761. * Remove a mesh from the LOD array
  31762. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31763. * @param {Mesh} mesh The mesh to be removed.
  31764. * @return {Mesh} This mesh (for chaining)
  31765. */
  31766. Mesh.prototype.removeLODLevel = function (mesh) {
  31767. for (var index = 0; index < this._LODLevels.length; index++) {
  31768. if (this._LODLevels[index].mesh === mesh) {
  31769. this._LODLevels.splice(index, 1);
  31770. if (mesh) {
  31771. mesh._masterMesh = null;
  31772. }
  31773. }
  31774. }
  31775. this._sortLODLevels();
  31776. return this;
  31777. };
  31778. /**
  31779. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31780. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31781. */
  31782. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31783. if (!this._LODLevels || this._LODLevels.length === 0) {
  31784. return this;
  31785. }
  31786. var bSphere;
  31787. if (boundingSphere) {
  31788. bSphere = boundingSphere;
  31789. }
  31790. else {
  31791. var boundingInfo = this.getBoundingInfo();
  31792. bSphere = boundingInfo.boundingSphere;
  31793. }
  31794. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31795. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31796. if (this.onLODLevelSelection) {
  31797. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31798. }
  31799. return this;
  31800. }
  31801. for (var index = 0; index < this._LODLevels.length; index++) {
  31802. var level = this._LODLevels[index];
  31803. if (level.distance < distanceToCamera) {
  31804. if (level.mesh) {
  31805. level.mesh._preActivate();
  31806. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31807. }
  31808. if (this.onLODLevelSelection) {
  31809. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31810. }
  31811. return level.mesh;
  31812. }
  31813. }
  31814. if (this.onLODLevelSelection) {
  31815. this.onLODLevelSelection(distanceToCamera, this, this);
  31816. }
  31817. return this;
  31818. };
  31819. Object.defineProperty(Mesh.prototype, "geometry", {
  31820. /**
  31821. * Returns the mesh internal Geometry object.
  31822. */
  31823. get: function () {
  31824. return this._geometry;
  31825. },
  31826. enumerable: true,
  31827. configurable: true
  31828. });
  31829. /**
  31830. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31831. */
  31832. Mesh.prototype.getTotalVertices = function () {
  31833. if (this._geometry === null || this._geometry === undefined) {
  31834. return 0;
  31835. }
  31836. return this._geometry.getTotalVertices();
  31837. };
  31838. /**
  31839. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31840. * 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.
  31841. * You can force the copy with forceCopy === true
  31842. * Returns null if the mesh has no geometry or no vertex buffer.
  31843. * Possible `kind` values :
  31844. * - BABYLON.VertexBuffer.PositionKind
  31845. * - BABYLON.VertexBuffer.UVKind
  31846. * - BABYLON.VertexBuffer.UV2Kind
  31847. * - BABYLON.VertexBuffer.UV3Kind
  31848. * - BABYLON.VertexBuffer.UV4Kind
  31849. * - BABYLON.VertexBuffer.UV5Kind
  31850. * - BABYLON.VertexBuffer.UV6Kind
  31851. * - BABYLON.VertexBuffer.ColorKind
  31852. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31853. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31854. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31855. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31856. */
  31857. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31858. if (!this._geometry) {
  31859. return null;
  31860. }
  31861. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31862. };
  31863. /**
  31864. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31865. * Returns `null` if the mesh has no geometry.
  31866. * Possible `kind` values :
  31867. * - BABYLON.VertexBuffer.PositionKind
  31868. * - BABYLON.VertexBuffer.UVKind
  31869. * - BABYLON.VertexBuffer.UV2Kind
  31870. * - BABYLON.VertexBuffer.UV3Kind
  31871. * - BABYLON.VertexBuffer.UV4Kind
  31872. * - BABYLON.VertexBuffer.UV5Kind
  31873. * - BABYLON.VertexBuffer.UV6Kind
  31874. * - BABYLON.VertexBuffer.ColorKind
  31875. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31876. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31877. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31878. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31879. */
  31880. Mesh.prototype.getVertexBuffer = function (kind) {
  31881. if (!this._geometry) {
  31882. return null;
  31883. }
  31884. return this._geometry.getVertexBuffer(kind);
  31885. };
  31886. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31887. if (!this._geometry) {
  31888. if (this._delayInfo) {
  31889. return this._delayInfo.indexOf(kind) !== -1;
  31890. }
  31891. return false;
  31892. }
  31893. return this._geometry.isVerticesDataPresent(kind);
  31894. };
  31895. /**
  31896. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31897. * Possible `kind` values :
  31898. * - BABYLON.VertexBuffer.PositionKind
  31899. * - BABYLON.VertexBuffer.UVKind
  31900. * - BABYLON.VertexBuffer.UV2Kind
  31901. * - BABYLON.VertexBuffer.UV3Kind
  31902. * - BABYLON.VertexBuffer.UV4Kind
  31903. * - BABYLON.VertexBuffer.UV5Kind
  31904. * - BABYLON.VertexBuffer.UV6Kind
  31905. * - BABYLON.VertexBuffer.ColorKind
  31906. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31907. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31908. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31909. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31910. */
  31911. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31912. if (!this._geometry) {
  31913. if (this._delayInfo) {
  31914. return this._delayInfo.indexOf(kind) !== -1;
  31915. }
  31916. return false;
  31917. }
  31918. return this._geometry.isVertexBufferUpdatable(kind);
  31919. };
  31920. /**
  31921. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31922. * Possible `kind` values :
  31923. * - BABYLON.VertexBuffer.PositionKind
  31924. * - BABYLON.VertexBuffer.UVKind
  31925. * - BABYLON.VertexBuffer.UV2Kind
  31926. * - BABYLON.VertexBuffer.UV3Kind
  31927. * - BABYLON.VertexBuffer.UV4Kind
  31928. * - BABYLON.VertexBuffer.UV5Kind
  31929. * - BABYLON.VertexBuffer.UV6Kind
  31930. * - BABYLON.VertexBuffer.ColorKind
  31931. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31932. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31933. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31934. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31935. */
  31936. Mesh.prototype.getVerticesDataKinds = function () {
  31937. if (!this._geometry) {
  31938. var result = new Array();
  31939. if (this._delayInfo) {
  31940. this._delayInfo.forEach(function (kind, index, array) {
  31941. result.push(kind);
  31942. });
  31943. }
  31944. return result;
  31945. }
  31946. return this._geometry.getVerticesDataKinds();
  31947. };
  31948. /**
  31949. * Returns a positive integer : the total number of indices in this mesh geometry.
  31950. * Returns zero if the mesh has no geometry.
  31951. */
  31952. Mesh.prototype.getTotalIndices = function () {
  31953. if (!this._geometry) {
  31954. return 0;
  31955. }
  31956. return this._geometry.getTotalIndices();
  31957. };
  31958. /**
  31959. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31960. * 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.
  31961. * Returns an empty array if the mesh has no geometry.
  31962. */
  31963. Mesh.prototype.getIndices = function (copyWhenShared) {
  31964. if (!this._geometry) {
  31965. return [];
  31966. }
  31967. return this._geometry.getIndices(copyWhenShared);
  31968. };
  31969. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31970. get: function () {
  31971. return this._masterMesh !== null && this._masterMesh !== undefined;
  31972. },
  31973. enumerable: true,
  31974. configurable: true
  31975. });
  31976. /**
  31977. * Determine if the current mesh is ready to be rendered
  31978. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31979. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31980. * @returns true if all associated assets are ready (material, textures, shaders)
  31981. */
  31982. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31983. if (completeCheck === void 0) { completeCheck = false; }
  31984. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31985. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31986. return false;
  31987. }
  31988. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31989. return false;
  31990. }
  31991. if (!this.subMeshes || this.subMeshes.length === 0) {
  31992. return true;
  31993. }
  31994. if (!completeCheck) {
  31995. return true;
  31996. }
  31997. var engine = this.getEngine();
  31998. var scene = this.getScene();
  31999. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32000. this.computeWorldMatrix();
  32001. var mat = this.material || scene.defaultMaterial;
  32002. if (mat) {
  32003. if (mat.storeEffectOnSubMeshes) {
  32004. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32005. var subMesh = _a[_i];
  32006. var effectiveMaterial = subMesh.getMaterial();
  32007. if (effectiveMaterial) {
  32008. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32009. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32010. return false;
  32011. }
  32012. }
  32013. else {
  32014. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32015. return false;
  32016. }
  32017. }
  32018. }
  32019. }
  32020. }
  32021. else {
  32022. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32023. return false;
  32024. }
  32025. }
  32026. }
  32027. // Shadows
  32028. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32029. var light = _c[_b];
  32030. var generator = light.getShadowGenerator();
  32031. if (generator) {
  32032. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32033. var subMesh = _e[_d];
  32034. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32035. return false;
  32036. }
  32037. }
  32038. }
  32039. }
  32040. // LOD
  32041. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32042. var lod = _g[_f];
  32043. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32044. return false;
  32045. }
  32046. }
  32047. return true;
  32048. };
  32049. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32050. /**
  32051. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32052. * This property is pertinent only for updatable parametric shapes.
  32053. */
  32054. get: function () {
  32055. return this._areNormalsFrozen;
  32056. },
  32057. enumerable: true,
  32058. configurable: true
  32059. });
  32060. /**
  32061. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32062. * It has no effect at all on other shapes.
  32063. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32064. * Returns the Mesh.
  32065. */
  32066. Mesh.prototype.freezeNormals = function () {
  32067. this._areNormalsFrozen = true;
  32068. return this;
  32069. };
  32070. /**
  32071. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32072. * It has no effect at all on other shapes.
  32073. * It reactivates the mesh normals computation if it was previously frozen.
  32074. * Returns the Mesh.
  32075. */
  32076. Mesh.prototype.unfreezeNormals = function () {
  32077. this._areNormalsFrozen = false;
  32078. return this;
  32079. };
  32080. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32081. /**
  32082. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32083. */
  32084. set: function (count) {
  32085. this._overridenInstanceCount = count;
  32086. },
  32087. enumerable: true,
  32088. configurable: true
  32089. });
  32090. // Methods
  32091. Mesh.prototype._preActivate = function () {
  32092. var sceneRenderId = this.getScene().getRenderId();
  32093. if (this._preActivateId === sceneRenderId) {
  32094. return this;
  32095. }
  32096. this._preActivateId = sceneRenderId;
  32097. this._visibleInstances = null;
  32098. return this;
  32099. };
  32100. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32101. if (this._visibleInstances) {
  32102. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32103. }
  32104. return this;
  32105. };
  32106. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32107. if (!this._visibleInstances) {
  32108. this._visibleInstances = {};
  32109. this._visibleInstances.defaultRenderId = renderId;
  32110. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32111. }
  32112. if (!this._visibleInstances[renderId]) {
  32113. this._visibleInstances[renderId] = new Array();
  32114. }
  32115. this._visibleInstances[renderId].push(instance);
  32116. return this;
  32117. };
  32118. /**
  32119. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32120. * This means the mesh underlying bounding box and sphere are recomputed.
  32121. * Returns the Mesh.
  32122. */
  32123. Mesh.prototype.refreshBoundingInfo = function () {
  32124. return this._refreshBoundingInfo(false);
  32125. };
  32126. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32127. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32128. return this;
  32129. }
  32130. var data = this._getPositionData(applySkeleton);
  32131. if (data) {
  32132. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32133. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32134. }
  32135. if (this.subMeshes) {
  32136. for (var index = 0; index < this.subMeshes.length; index++) {
  32137. this.subMeshes[index].refreshBoundingInfo();
  32138. }
  32139. }
  32140. this._updateBoundingInfo();
  32141. return this;
  32142. };
  32143. Mesh.prototype._getPositionData = function (applySkeleton) {
  32144. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32145. if (data && applySkeleton && this.skeleton) {
  32146. data = BABYLON.Tools.Slice(data);
  32147. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32148. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32149. if (matricesWeightsData && matricesIndicesData) {
  32150. var needExtras = this.numBoneInfluencers > 4;
  32151. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32152. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32153. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32154. var tempVector = BABYLON.Tmp.Vector3[0];
  32155. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32156. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32157. var matWeightIdx = 0;
  32158. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32159. finalMatrix.reset();
  32160. var inf;
  32161. var weight;
  32162. for (inf = 0; inf < 4; inf++) {
  32163. weight = matricesWeightsData[matWeightIdx + inf];
  32164. if (weight <= 0)
  32165. break;
  32166. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32167. finalMatrix.addToSelf(tempMatrix);
  32168. }
  32169. if (needExtras) {
  32170. for (inf = 0; inf < 4; inf++) {
  32171. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32172. if (weight <= 0)
  32173. break;
  32174. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32175. finalMatrix.addToSelf(tempMatrix);
  32176. }
  32177. }
  32178. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32179. tempVector.toArray(data, index);
  32180. }
  32181. }
  32182. }
  32183. return data;
  32184. };
  32185. Mesh.prototype._createGlobalSubMesh = function (force) {
  32186. var totalVertices = this.getTotalVertices();
  32187. if (!totalVertices || !this.getIndices()) {
  32188. return null;
  32189. }
  32190. // Check if we need to recreate the submeshes
  32191. if (this.subMeshes && this.subMeshes.length > 0) {
  32192. var ib = this.getIndices();
  32193. if (!ib) {
  32194. return null;
  32195. }
  32196. var totalIndices = ib.length;
  32197. var needToRecreate = false;
  32198. if (force) {
  32199. needToRecreate = true;
  32200. }
  32201. else {
  32202. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32203. var submesh = _a[_i];
  32204. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32205. needToRecreate = true;
  32206. break;
  32207. }
  32208. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32209. needToRecreate = true;
  32210. break;
  32211. }
  32212. }
  32213. }
  32214. if (!needToRecreate) {
  32215. return this.subMeshes[0];
  32216. }
  32217. }
  32218. this.releaseSubMeshes();
  32219. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32220. };
  32221. Mesh.prototype.subdivide = function (count) {
  32222. if (count < 1) {
  32223. return;
  32224. }
  32225. var totalIndices = this.getTotalIndices();
  32226. var subdivisionSize = (totalIndices / count) | 0;
  32227. var offset = 0;
  32228. // Ensure that subdivisionSize is a multiple of 3
  32229. while (subdivisionSize % 3 !== 0) {
  32230. subdivisionSize++;
  32231. }
  32232. this.releaseSubMeshes();
  32233. for (var index = 0; index < count; index++) {
  32234. if (offset >= totalIndices) {
  32235. break;
  32236. }
  32237. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32238. offset += subdivisionSize;
  32239. }
  32240. this.synchronizeInstances();
  32241. };
  32242. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32243. if (updatable === void 0) { updatable = false; }
  32244. if (!this._geometry) {
  32245. var vertexData = new BABYLON.VertexData();
  32246. vertexData.set(data, kind);
  32247. var scene = this.getScene();
  32248. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32249. }
  32250. else {
  32251. this._geometry.setVerticesData(kind, data, updatable, stride);
  32252. }
  32253. return this;
  32254. };
  32255. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32256. if (updatable === void 0) { updatable = true; }
  32257. var vb = this.getVertexBuffer(kind);
  32258. if (!vb || vb.isUpdatable() === updatable) {
  32259. return;
  32260. }
  32261. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32262. };
  32263. /**
  32264. * Sets the mesh VertexBuffer.
  32265. * Returns the Mesh.
  32266. */
  32267. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32268. if (!this._geometry) {
  32269. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32270. }
  32271. this._geometry.setVerticesBuffer(buffer);
  32272. return this;
  32273. };
  32274. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32275. if (!this._geometry) {
  32276. return this;
  32277. }
  32278. if (!makeItUnique) {
  32279. this._geometry.updateVerticesData(kind, data, updateExtends);
  32280. }
  32281. else {
  32282. this.makeGeometryUnique();
  32283. this.updateVerticesData(kind, data, updateExtends, false);
  32284. }
  32285. return this;
  32286. };
  32287. /**
  32288. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32289. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32290. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32291. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32292. * Returns the Mesh.
  32293. */
  32294. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32295. if (computeNormals === void 0) { computeNormals = true; }
  32296. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32297. if (!positions) {
  32298. return this;
  32299. }
  32300. positionFunction(positions);
  32301. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32302. if (computeNormals) {
  32303. var indices = this.getIndices();
  32304. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32305. if (!normals) {
  32306. return this;
  32307. }
  32308. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32309. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32310. }
  32311. return this;
  32312. };
  32313. /**
  32314. * Creates a un-shared specific occurence of the geometry for the mesh.
  32315. * Returns the Mesh.
  32316. */
  32317. Mesh.prototype.makeGeometryUnique = function () {
  32318. if (!this._geometry) {
  32319. return this;
  32320. }
  32321. var oldGeometry = this._geometry;
  32322. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32323. oldGeometry.releaseForMesh(this, true);
  32324. geometry.applyToMesh(this);
  32325. return this;
  32326. };
  32327. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32328. if (totalVertices === void 0) { totalVertices = null; }
  32329. if (updatable === void 0) { updatable = false; }
  32330. if (!this._geometry) {
  32331. var vertexData = new BABYLON.VertexData();
  32332. vertexData.indices = indices;
  32333. var scene = this.getScene();
  32334. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32335. }
  32336. else {
  32337. this._geometry.setIndices(indices, totalVertices, updatable);
  32338. }
  32339. return this;
  32340. };
  32341. /**
  32342. * Update the current index buffer
  32343. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32344. * Returns the Mesh.
  32345. */
  32346. Mesh.prototype.updateIndices = function (indices, offset) {
  32347. if (!this._geometry) {
  32348. return this;
  32349. }
  32350. this._geometry.updateIndices(indices, offset);
  32351. return this;
  32352. };
  32353. /**
  32354. * Invert the geometry to move from a right handed system to a left handed one.
  32355. * Returns the Mesh.
  32356. */
  32357. Mesh.prototype.toLeftHanded = function () {
  32358. if (!this._geometry) {
  32359. return this;
  32360. }
  32361. this._geometry.toLeftHanded();
  32362. return this;
  32363. };
  32364. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32365. if (!this._geometry) {
  32366. return this;
  32367. }
  32368. var engine = this.getScene().getEngine();
  32369. // Wireframe
  32370. var indexToBind;
  32371. if (this._unIndexed) {
  32372. indexToBind = null;
  32373. }
  32374. else {
  32375. switch (fillMode) {
  32376. case BABYLON.Material.PointFillMode:
  32377. indexToBind = null;
  32378. break;
  32379. case BABYLON.Material.WireFrameFillMode:
  32380. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32381. break;
  32382. default:
  32383. case BABYLON.Material.TriangleFillMode:
  32384. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32385. break;
  32386. }
  32387. }
  32388. // VBOs
  32389. this._geometry._bind(effect, indexToBind);
  32390. return this;
  32391. };
  32392. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32393. if (alternate === void 0) { alternate = false; }
  32394. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32395. return this;
  32396. }
  32397. this.onBeforeDrawObservable.notifyObservers(this);
  32398. var scene = this.getScene();
  32399. var engine = scene.getEngine();
  32400. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32401. // or triangles as points
  32402. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32403. }
  32404. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32405. // Triangles as wireframe
  32406. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32407. }
  32408. else {
  32409. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32410. }
  32411. if (scene._isAlternateRenderingEnabled && !alternate) {
  32412. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32413. if (!effect || !scene.activeCamera) {
  32414. return this;
  32415. }
  32416. scene._switchToAlternateCameraConfiguration(true);
  32417. this._effectiveMaterial.bindView(effect);
  32418. this._effectiveMaterial.bindViewProjection(effect);
  32419. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32420. this._draw(subMesh, fillMode, instancesCount, true);
  32421. engine.setViewport(scene.activeCamera.viewport);
  32422. scene._switchToAlternateCameraConfiguration(false);
  32423. this._effectiveMaterial.bindView(effect);
  32424. this._effectiveMaterial.bindViewProjection(effect);
  32425. }
  32426. return this;
  32427. };
  32428. /**
  32429. * Registers for this mesh a javascript function called just before the rendering process.
  32430. * This function is passed the current mesh.
  32431. * Return the Mesh.
  32432. */
  32433. Mesh.prototype.registerBeforeRender = function (func) {
  32434. this.onBeforeRenderObservable.add(func);
  32435. return this;
  32436. };
  32437. /**
  32438. * Disposes a previously registered javascript function called before the rendering.
  32439. * This function is passed the current mesh.
  32440. * Returns the Mesh.
  32441. */
  32442. Mesh.prototype.unregisterBeforeRender = function (func) {
  32443. this.onBeforeRenderObservable.removeCallback(func);
  32444. return this;
  32445. };
  32446. /**
  32447. * Registers for this mesh a javascript function called just after the rendering is complete.
  32448. * This function is passed the current mesh.
  32449. * Returns the Mesh.
  32450. */
  32451. Mesh.prototype.registerAfterRender = function (func) {
  32452. this.onAfterRenderObservable.add(func);
  32453. return this;
  32454. };
  32455. /**
  32456. * Disposes a previously registered javascript function called after the rendering.
  32457. * This function is passed the current mesh.
  32458. * Return the Mesh.
  32459. */
  32460. Mesh.prototype.unregisterAfterRender = function (func) {
  32461. this.onAfterRenderObservable.removeCallback(func);
  32462. return this;
  32463. };
  32464. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32465. var scene = this.getScene();
  32466. this._batchCache.mustReturn = false;
  32467. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32468. this._batchCache.visibleInstances[subMeshId] = null;
  32469. if (this._visibleInstances) {
  32470. var currentRenderId = scene.getRenderId();
  32471. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32472. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32473. var selfRenderId = this._renderId;
  32474. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32475. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32476. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32477. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32478. }
  32479. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32480. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32481. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32482. this._batchCache.mustReturn = true;
  32483. return this._batchCache;
  32484. }
  32485. if (currentRenderId !== selfRenderId) {
  32486. this._batchCache.renderSelf[subMeshId] = false;
  32487. }
  32488. }
  32489. this._renderIdForInstances[subMeshId] = currentRenderId;
  32490. }
  32491. return this._batchCache;
  32492. };
  32493. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32494. var visibleInstances = batch.visibleInstances[subMesh._id];
  32495. if (!visibleInstances) {
  32496. return this;
  32497. }
  32498. var matricesCount = visibleInstances.length + 1;
  32499. var bufferSize = matricesCount * 16 * 4;
  32500. var currentInstancesBufferSize = this._instancesBufferSize;
  32501. var instancesBuffer = this._instancesBuffer;
  32502. while (this._instancesBufferSize < bufferSize) {
  32503. this._instancesBufferSize *= 2;
  32504. }
  32505. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32506. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32507. }
  32508. var offset = 0;
  32509. var instancesCount = 0;
  32510. var world = this.getWorldMatrix();
  32511. if (batch.renderSelf[subMesh._id]) {
  32512. world.copyToArray(this._instancesData, offset);
  32513. offset += 16;
  32514. instancesCount++;
  32515. }
  32516. if (visibleInstances) {
  32517. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32518. var instance = visibleInstances[instanceIndex];
  32519. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32520. offset += 16;
  32521. instancesCount++;
  32522. }
  32523. }
  32524. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32525. if (instancesBuffer) {
  32526. instancesBuffer.dispose();
  32527. }
  32528. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32529. this._instancesBuffer = instancesBuffer;
  32530. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32531. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32532. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32533. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32534. }
  32535. else {
  32536. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32537. }
  32538. this._bind(subMesh, effect, fillMode);
  32539. this._draw(subMesh, fillMode, instancesCount);
  32540. engine.unbindInstanceAttributes();
  32541. return this;
  32542. };
  32543. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32544. var scene = this.getScene();
  32545. var engine = scene.getEngine();
  32546. if (hardwareInstancedRendering) {
  32547. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32548. }
  32549. else {
  32550. if (batch.renderSelf[subMesh._id]) {
  32551. // Draw
  32552. if (onBeforeDraw) {
  32553. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32554. }
  32555. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32556. }
  32557. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32558. if (visibleInstancesForSubMesh) {
  32559. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32560. var instance = visibleInstancesForSubMesh[instanceIndex];
  32561. // World
  32562. var world = instance.getWorldMatrix();
  32563. if (onBeforeDraw) {
  32564. onBeforeDraw(true, world, effectiveMaterial);
  32565. }
  32566. // Draw
  32567. this._draw(subMesh, fillMode);
  32568. }
  32569. }
  32570. }
  32571. return this;
  32572. };
  32573. /**
  32574. * Triggers the draw call for the mesh.
  32575. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32576. * Returns the Mesh.
  32577. */
  32578. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32579. this._checkOcclusionQuery();
  32580. if (this._isOccluded) {
  32581. return this;
  32582. }
  32583. var scene = this.getScene();
  32584. // Managing instances
  32585. var batch = this._getInstancesRenderList(subMesh._id);
  32586. if (batch.mustReturn) {
  32587. return this;
  32588. }
  32589. // Checking geometry state
  32590. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32591. return this;
  32592. }
  32593. this.onBeforeRenderObservable.notifyObservers(this);
  32594. var engine = scene.getEngine();
  32595. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32596. // Material
  32597. var material = subMesh.getMaterial();
  32598. if (!material) {
  32599. return this;
  32600. }
  32601. this._effectiveMaterial = material;
  32602. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32603. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32604. return this;
  32605. }
  32606. }
  32607. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32608. return this;
  32609. }
  32610. // Alpha mode
  32611. if (enableAlphaMode) {
  32612. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32613. }
  32614. // Outline - step 1
  32615. var savedDepthWrite = engine.getDepthWrite();
  32616. if (this.renderOutline) {
  32617. engine.setDepthWrite(false);
  32618. scene.getOutlineRenderer().render(subMesh, batch);
  32619. engine.setDepthWrite(savedDepthWrite);
  32620. }
  32621. var effect;
  32622. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32623. effect = subMesh.effect;
  32624. }
  32625. else {
  32626. effect = this._effectiveMaterial.getEffect();
  32627. }
  32628. if (!effect) {
  32629. return this;
  32630. }
  32631. var sideOrientation = this.overrideMaterialSideOrientation;
  32632. if (sideOrientation == null) {
  32633. sideOrientation = this._effectiveMaterial.sideOrientation;
  32634. if (this._getWorldMatrixDeterminant() < 0) {
  32635. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32636. }
  32637. }
  32638. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32639. if (this._effectiveMaterial.forceDepthWrite) {
  32640. engine.setDepthWrite(true);
  32641. }
  32642. // Bind
  32643. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32644. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32645. this._bind(subMesh, effect, fillMode);
  32646. }
  32647. var world = this.getWorldMatrix();
  32648. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32649. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32650. }
  32651. else {
  32652. this._effectiveMaterial.bind(world, this);
  32653. }
  32654. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32655. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32656. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32657. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32658. }
  32659. // Draw
  32660. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32661. // Unbind
  32662. this._effectiveMaterial.unbind();
  32663. // Outline - step 2
  32664. if (this.renderOutline && savedDepthWrite) {
  32665. engine.setDepthWrite(true);
  32666. engine.setColorWrite(false);
  32667. scene.getOutlineRenderer().render(subMesh, batch);
  32668. engine.setColorWrite(true);
  32669. }
  32670. // Overlay
  32671. if (this.renderOverlay) {
  32672. var currentMode = engine.getAlphaMode();
  32673. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32674. scene.getOutlineRenderer().render(subMesh, batch, true);
  32675. engine.setAlphaMode(currentMode);
  32676. }
  32677. this.onAfterRenderObservable.notifyObservers(this);
  32678. return this;
  32679. };
  32680. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32681. if (isInstance && effectiveMaterial) {
  32682. effectiveMaterial.bindOnlyWorldMatrix(world);
  32683. }
  32684. };
  32685. /**
  32686. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32687. */
  32688. Mesh.prototype.getEmittedParticleSystems = function () {
  32689. var results = new Array();
  32690. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32691. var particleSystem = this.getScene().particleSystems[index];
  32692. if (particleSystem.emitter === this) {
  32693. results.push(particleSystem);
  32694. }
  32695. }
  32696. return results;
  32697. };
  32698. /**
  32699. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32700. */
  32701. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32702. var results = new Array();
  32703. var descendants = this.getDescendants();
  32704. descendants.push(this);
  32705. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32706. var particleSystem = this.getScene().particleSystems[index];
  32707. var emitter = particleSystem.emitter;
  32708. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32709. results.push(particleSystem);
  32710. }
  32711. }
  32712. return results;
  32713. };
  32714. /**
  32715. * Normalize matrix weights so that all vertices have a total weight set to 1
  32716. */
  32717. Mesh.prototype.cleanMatrixWeights = function () {
  32718. var epsilon = 1e-3;
  32719. var noInfluenceBoneIndex = 0.0;
  32720. if (this.skeleton) {
  32721. noInfluenceBoneIndex = this.skeleton.bones.length;
  32722. }
  32723. else {
  32724. return;
  32725. }
  32726. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32727. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32728. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32729. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32730. var influencers = this.numBoneInfluencers;
  32731. var size = matricesWeights.length;
  32732. for (var i = 0; i < size; i += 4) {
  32733. var weight = 0.0;
  32734. var firstZeroWeight = -1;
  32735. for (var j = 0; j < 4; j++) {
  32736. var w = matricesWeights[i + j];
  32737. weight += w;
  32738. if (w < epsilon && firstZeroWeight < 0) {
  32739. firstZeroWeight = j;
  32740. }
  32741. }
  32742. if (matricesWeightsExtra) {
  32743. for (var j = 0; j < 4; j++) {
  32744. var w = matricesWeightsExtra[i + j];
  32745. weight += w;
  32746. if (w < epsilon && firstZeroWeight < 0) {
  32747. firstZeroWeight = j + 4;
  32748. }
  32749. }
  32750. }
  32751. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32752. firstZeroWeight = influencers - 1;
  32753. }
  32754. if (weight > epsilon) {
  32755. var mweight = 1.0 / weight;
  32756. for (var j = 0; j < 4; j++) {
  32757. matricesWeights[i + j] *= mweight;
  32758. }
  32759. if (matricesWeightsExtra) {
  32760. for (var j = 0; j < 4; j++) {
  32761. matricesWeightsExtra[i + j] *= mweight;
  32762. }
  32763. }
  32764. }
  32765. else {
  32766. if (firstZeroWeight >= 4) {
  32767. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32768. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32769. }
  32770. else {
  32771. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32772. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32773. }
  32774. }
  32775. }
  32776. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32777. if (matricesIndicesExtra) {
  32778. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32779. }
  32780. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32781. if (matricesWeightsExtra) {
  32782. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32783. }
  32784. };
  32785. Mesh.prototype._checkDelayState = function () {
  32786. var scene = this.getScene();
  32787. if (this._geometry) {
  32788. this._geometry.load(scene);
  32789. }
  32790. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32791. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32792. this._queueLoad(scene);
  32793. }
  32794. return this;
  32795. };
  32796. Mesh.prototype._queueLoad = function (scene) {
  32797. var _this = this;
  32798. scene._addPendingData(this);
  32799. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32800. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32801. if (data instanceof ArrayBuffer) {
  32802. _this._delayLoadingFunction(data, _this);
  32803. }
  32804. else {
  32805. _this._delayLoadingFunction(JSON.parse(data), _this);
  32806. }
  32807. _this.instances.forEach(function (instance) {
  32808. instance._syncSubMeshes();
  32809. });
  32810. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32811. scene._removePendingData(_this);
  32812. }, function () { }, scene.database, getBinaryData);
  32813. return this;
  32814. };
  32815. /**
  32816. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32817. */
  32818. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32819. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32820. return false;
  32821. }
  32822. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32823. return false;
  32824. }
  32825. this._checkDelayState();
  32826. return true;
  32827. };
  32828. /**
  32829. * Sets the mesh material by the material or multiMaterial `id` property.
  32830. * The material `id` is a string identifying the material or the multiMaterial.
  32831. * This method returns the Mesh.
  32832. */
  32833. Mesh.prototype.setMaterialByID = function (id) {
  32834. var materials = this.getScene().materials;
  32835. var index;
  32836. for (index = materials.length - 1; index > -1; index--) {
  32837. if (materials[index].id === id) {
  32838. this.material = materials[index];
  32839. return this;
  32840. }
  32841. }
  32842. // Multi
  32843. var multiMaterials = this.getScene().multiMaterials;
  32844. for (index = multiMaterials.length - 1; index > -1; index--) {
  32845. if (multiMaterials[index].id === id) {
  32846. this.material = multiMaterials[index];
  32847. return this;
  32848. }
  32849. }
  32850. return this;
  32851. };
  32852. /**
  32853. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32854. */
  32855. Mesh.prototype.getAnimatables = function () {
  32856. var results = new Array();
  32857. if (this.material) {
  32858. results.push(this.material);
  32859. }
  32860. if (this.skeleton) {
  32861. results.push(this.skeleton);
  32862. }
  32863. return results;
  32864. };
  32865. /**
  32866. * Modifies the mesh geometry according to the passed transformation matrix.
  32867. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32868. * The mesh normals are modified accordingly the same transformation.
  32869. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32870. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32871. * Returns the Mesh.
  32872. */
  32873. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32874. // Position
  32875. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32876. return this;
  32877. }
  32878. var submeshes = this.subMeshes.splice(0);
  32879. this._resetPointsArrayCache();
  32880. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32881. var temp = new Array();
  32882. var index;
  32883. for (index = 0; index < data.length; index += 3) {
  32884. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32885. }
  32886. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32887. // Normals
  32888. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32889. return this;
  32890. }
  32891. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32892. temp = [];
  32893. for (index = 0; index < data.length; index += 3) {
  32894. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32895. }
  32896. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32897. // flip faces?
  32898. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32899. this.flipFaces();
  32900. }
  32901. // Restore submeshes
  32902. this.releaseSubMeshes();
  32903. this.subMeshes = submeshes;
  32904. return this;
  32905. };
  32906. /**
  32907. * Modifies the mesh geometry according to its own current World Matrix.
  32908. * The mesh World Matrix is then reset.
  32909. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32910. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32911. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32912. * Returns the Mesh.
  32913. */
  32914. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32915. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32916. this.scaling.copyFromFloats(1, 1, 1);
  32917. this.position.copyFromFloats(0, 0, 0);
  32918. this.rotation.copyFromFloats(0, 0, 0);
  32919. //only if quaternion is already set
  32920. if (this.rotationQuaternion) {
  32921. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32922. }
  32923. this._worldMatrix = BABYLON.Matrix.Identity();
  32924. return this;
  32925. };
  32926. Object.defineProperty(Mesh.prototype, "_positions", {
  32927. // Cache
  32928. get: function () {
  32929. if (this._geometry) {
  32930. return this._geometry._positions;
  32931. }
  32932. return null;
  32933. },
  32934. enumerable: true,
  32935. configurable: true
  32936. });
  32937. Mesh.prototype._resetPointsArrayCache = function () {
  32938. if (this._geometry) {
  32939. this._geometry._resetPointsArrayCache();
  32940. }
  32941. return this;
  32942. };
  32943. Mesh.prototype._generatePointsArray = function () {
  32944. if (this._geometry) {
  32945. return this._geometry._generatePointsArray();
  32946. }
  32947. return false;
  32948. };
  32949. /**
  32950. * Returns a new Mesh object generated from the current mesh properties.
  32951. * This method must not get confused with createInstance().
  32952. * The parameter `name` is a string, the name given to the new mesh.
  32953. * The optional parameter `newParent` can be any Node object (default `null`).
  32954. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32955. * 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.
  32956. */
  32957. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32958. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32959. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32960. };
  32961. /**
  32962. * Releases resources associated with this mesh.
  32963. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32964. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32965. */
  32966. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32967. var _this = this;
  32968. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32969. this.morphTargetManager = null;
  32970. if (this._geometry) {
  32971. this._geometry.releaseForMesh(this, true);
  32972. }
  32973. // Sources
  32974. var meshes = this.getScene().meshes;
  32975. meshes.forEach(function (abstractMesh) {
  32976. var mesh = abstractMesh;
  32977. if (mesh._source && mesh._source === _this) {
  32978. mesh._source = null;
  32979. }
  32980. });
  32981. this._source = null;
  32982. // Instances
  32983. if (this._instancesBuffer) {
  32984. this._instancesBuffer.dispose();
  32985. this._instancesBuffer = null;
  32986. }
  32987. while (this.instances.length) {
  32988. this.instances[0].dispose();
  32989. }
  32990. // Effect layers.
  32991. var effectLayers = this.getScene().effectLayers;
  32992. for (var i = 0; i < effectLayers.length; i++) {
  32993. var effectLayer = effectLayers[i];
  32994. if (effectLayer) {
  32995. effectLayer._disposeMesh(this);
  32996. }
  32997. }
  32998. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32999. };
  33000. /**
  33001. * Modifies the mesh geometry according to a displacement map.
  33002. * 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.
  33003. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33004. * This method returns nothing.
  33005. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33006. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33007. * 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.
  33008. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33009. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33010. *
  33011. * Returns the Mesh.
  33012. */
  33013. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33014. var _this = this;
  33015. var scene = this.getScene();
  33016. var onload = function (img) {
  33017. // Getting height map data
  33018. var canvas = document.createElement("canvas");
  33019. var context = canvas.getContext("2d");
  33020. var heightMapWidth = img.width;
  33021. var heightMapHeight = img.height;
  33022. canvas.width = heightMapWidth;
  33023. canvas.height = heightMapHeight;
  33024. context.drawImage(img, 0, 0);
  33025. // Create VertexData from map data
  33026. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33027. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33028. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33029. //execute success callback, if set
  33030. if (onSuccess) {
  33031. onSuccess(_this);
  33032. }
  33033. };
  33034. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33035. return this;
  33036. };
  33037. /**
  33038. * Modifies the mesh geometry according to a displacementMap buffer.
  33039. * 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.
  33040. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33041. * This method returns nothing.
  33042. * 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.
  33043. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33044. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33045. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33046. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33047. *
  33048. * Returns the Mesh.
  33049. */
  33050. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33051. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33052. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33053. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33054. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33055. return this;
  33056. }
  33057. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33058. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33059. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33060. var position = BABYLON.Vector3.Zero();
  33061. var normal = BABYLON.Vector3.Zero();
  33062. var uv = BABYLON.Vector2.Zero();
  33063. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33064. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33065. for (var index = 0; index < positions.length; index += 3) {
  33066. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33067. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33068. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33069. // Compute height
  33070. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33071. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33072. var pos = (u + v * heightMapWidth) * 4;
  33073. var r = buffer[pos] / 255.0;
  33074. var g = buffer[pos + 1] / 255.0;
  33075. var b = buffer[pos + 2] / 255.0;
  33076. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33077. normal.normalize();
  33078. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33079. position = position.add(normal);
  33080. position.toArray(positions, index);
  33081. }
  33082. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33083. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33084. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33085. return this;
  33086. };
  33087. /**
  33088. * Modify the mesh to get a flat shading rendering.
  33089. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33090. * This method returns the Mesh.
  33091. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33092. */
  33093. Mesh.prototype.convertToFlatShadedMesh = function () {
  33094. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33095. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33096. var kinds = this.getVerticesDataKinds();
  33097. var vbs = {};
  33098. var data = {};
  33099. var newdata = {};
  33100. var updatableNormals = false;
  33101. var kindIndex;
  33102. var kind;
  33103. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33104. kind = kinds[kindIndex];
  33105. var vertexBuffer = this.getVertexBuffer(kind);
  33106. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33107. updatableNormals = vertexBuffer.isUpdatable();
  33108. kinds.splice(kindIndex, 1);
  33109. kindIndex--;
  33110. continue;
  33111. }
  33112. vbs[kind] = vertexBuffer;
  33113. data[kind] = vbs[kind].getData();
  33114. newdata[kind] = [];
  33115. }
  33116. // Save previous submeshes
  33117. var previousSubmeshes = this.subMeshes.slice(0);
  33118. var indices = this.getIndices();
  33119. var totalIndices = this.getTotalIndices();
  33120. // Generating unique vertices per face
  33121. var index;
  33122. for (index = 0; index < totalIndices; index++) {
  33123. var vertexIndex = indices[index];
  33124. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33125. kind = kinds[kindIndex];
  33126. var stride = vbs[kind].getStrideSize();
  33127. for (var offset = 0; offset < stride; offset++) {
  33128. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33129. }
  33130. }
  33131. }
  33132. // Updating faces & normal
  33133. var normals = [];
  33134. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33135. for (index = 0; index < totalIndices; index += 3) {
  33136. indices[index] = index;
  33137. indices[index + 1] = index + 1;
  33138. indices[index + 2] = index + 2;
  33139. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33140. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33141. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33142. var p1p2 = p1.subtract(p2);
  33143. var p3p2 = p3.subtract(p2);
  33144. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33145. // Store same normals for every vertex
  33146. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33147. normals.push(normal.x);
  33148. normals.push(normal.y);
  33149. normals.push(normal.z);
  33150. }
  33151. }
  33152. this.setIndices(indices);
  33153. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33154. // Updating vertex buffers
  33155. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33156. kind = kinds[kindIndex];
  33157. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33158. }
  33159. // Updating submeshes
  33160. this.releaseSubMeshes();
  33161. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33162. var previousOne = previousSubmeshes[submeshIndex];
  33163. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33164. }
  33165. this.synchronizeInstances();
  33166. return this;
  33167. };
  33168. /**
  33169. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33170. * In other words, more vertices, no more indices and a single bigger VBO.
  33171. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33172. * Returns the Mesh.
  33173. */
  33174. Mesh.prototype.convertToUnIndexedMesh = function () {
  33175. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33176. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33177. var kinds = this.getVerticesDataKinds();
  33178. var vbs = {};
  33179. var data = {};
  33180. var newdata = {};
  33181. var kindIndex;
  33182. var kind;
  33183. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33184. kind = kinds[kindIndex];
  33185. var vertexBuffer = this.getVertexBuffer(kind);
  33186. vbs[kind] = vertexBuffer;
  33187. data[kind] = vbs[kind].getData();
  33188. newdata[kind] = [];
  33189. }
  33190. // Save previous submeshes
  33191. var previousSubmeshes = this.subMeshes.slice(0);
  33192. var indices = this.getIndices();
  33193. var totalIndices = this.getTotalIndices();
  33194. // Generating unique vertices per face
  33195. var index;
  33196. for (index = 0; index < totalIndices; index++) {
  33197. var vertexIndex = indices[index];
  33198. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33199. kind = kinds[kindIndex];
  33200. var stride = vbs[kind].getStrideSize();
  33201. for (var offset = 0; offset < stride; offset++) {
  33202. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33203. }
  33204. }
  33205. }
  33206. // Updating indices
  33207. for (index = 0; index < totalIndices; index += 3) {
  33208. indices[index] = index;
  33209. indices[index + 1] = index + 1;
  33210. indices[index + 2] = index + 2;
  33211. }
  33212. this.setIndices(indices);
  33213. // Updating vertex buffers
  33214. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33215. kind = kinds[kindIndex];
  33216. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33217. }
  33218. // Updating submeshes
  33219. this.releaseSubMeshes();
  33220. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33221. var previousOne = previousSubmeshes[submeshIndex];
  33222. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33223. }
  33224. this._unIndexed = true;
  33225. this.synchronizeInstances();
  33226. return this;
  33227. };
  33228. /**
  33229. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33230. * This method returns the Mesh.
  33231. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33232. */
  33233. Mesh.prototype.flipFaces = function (flipNormals) {
  33234. if (flipNormals === void 0) { flipNormals = false; }
  33235. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33236. var i;
  33237. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33238. for (i = 0; i < vertex_data.normals.length; i++) {
  33239. vertex_data.normals[i] *= -1;
  33240. }
  33241. }
  33242. if (vertex_data.indices) {
  33243. var temp;
  33244. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33245. // reassign indices
  33246. temp = vertex_data.indices[i + 1];
  33247. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33248. vertex_data.indices[i + 2] = temp;
  33249. }
  33250. }
  33251. vertex_data.applyToMesh(this);
  33252. return this;
  33253. };
  33254. // Instances
  33255. /**
  33256. * Creates a new InstancedMesh object from the mesh model.
  33257. * An instance shares the same properties and the same material than its model.
  33258. * Only these properties of each instance can then be set individually :
  33259. * - position
  33260. * - rotation
  33261. * - rotationQuaternion
  33262. * - setPivotMatrix
  33263. * - scaling
  33264. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33265. * Warning : this method is not supported for Line mesh and LineSystem
  33266. */
  33267. Mesh.prototype.createInstance = function (name) {
  33268. return new BABYLON.InstancedMesh(name, this);
  33269. };
  33270. /**
  33271. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33272. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33273. * This method returns the Mesh.
  33274. */
  33275. Mesh.prototype.synchronizeInstances = function () {
  33276. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33277. var instance = this.instances[instanceIndex];
  33278. instance._syncSubMeshes();
  33279. }
  33280. return this;
  33281. };
  33282. /**
  33283. * Simplify the mesh according to the given array of settings.
  33284. * Function will return immediately and will simplify async. It returns the Mesh.
  33285. * @param settings a collection of simplification settings.
  33286. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33287. * @param type the type of simplification to run.
  33288. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33289. */
  33290. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33291. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33292. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33293. this.getScene().simplificationQueue.addTask({
  33294. settings: settings,
  33295. parallelProcessing: parallelProcessing,
  33296. mesh: this,
  33297. simplificationType: simplificationType,
  33298. successCallback: successCallback
  33299. });
  33300. return this;
  33301. };
  33302. /**
  33303. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33304. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33305. * This should be used together with the simplification to avoid disappearing triangles.
  33306. * Returns the Mesh.
  33307. * @param successCallback an optional success callback to be called after the optimization finished.
  33308. */
  33309. Mesh.prototype.optimizeIndices = function (successCallback) {
  33310. var _this = this;
  33311. var indices = this.getIndices();
  33312. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33313. if (!positions || !indices) {
  33314. return this;
  33315. }
  33316. var vectorPositions = new Array();
  33317. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33318. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33319. }
  33320. var dupes = new Array();
  33321. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33322. var realPos = vectorPositions.length - 1 - iteration;
  33323. var testedPosition = vectorPositions[realPos];
  33324. for (var j = 0; j < realPos; ++j) {
  33325. var againstPosition = vectorPositions[j];
  33326. if (testedPosition.equals(againstPosition)) {
  33327. dupes[realPos] = j;
  33328. break;
  33329. }
  33330. }
  33331. }, function () {
  33332. for (var i = 0; i < indices.length; ++i) {
  33333. indices[i] = dupes[indices[i]] || indices[i];
  33334. }
  33335. //indices are now reordered
  33336. var originalSubMeshes = _this.subMeshes.slice(0);
  33337. _this.setIndices(indices);
  33338. _this.subMeshes = originalSubMeshes;
  33339. if (successCallback) {
  33340. successCallback(_this);
  33341. }
  33342. });
  33343. return this;
  33344. };
  33345. Mesh.prototype.serialize = function (serializationObject) {
  33346. serializationObject.name = this.name;
  33347. serializationObject.id = this.id;
  33348. serializationObject.type = this.getClassName();
  33349. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33350. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33351. }
  33352. serializationObject.position = this.position.asArray();
  33353. if (this.rotationQuaternion) {
  33354. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33355. }
  33356. else if (this.rotation) {
  33357. serializationObject.rotation = this.rotation.asArray();
  33358. }
  33359. serializationObject.scaling = this.scaling.asArray();
  33360. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33361. serializationObject.isEnabled = this.isEnabled(false);
  33362. serializationObject.isVisible = this.isVisible;
  33363. serializationObject.infiniteDistance = this.infiniteDistance;
  33364. serializationObject.pickable = this.isPickable;
  33365. serializationObject.receiveShadows = this.receiveShadows;
  33366. serializationObject.billboardMode = this.billboardMode;
  33367. serializationObject.visibility = this.visibility;
  33368. serializationObject.checkCollisions = this.checkCollisions;
  33369. serializationObject.isBlocker = this.isBlocker;
  33370. // Parent
  33371. if (this.parent) {
  33372. serializationObject.parentId = this.parent.id;
  33373. }
  33374. // Geometry
  33375. serializationObject.isUnIndexed = this.isUnIndexed;
  33376. var geometry = this._geometry;
  33377. if (geometry) {
  33378. var geometryId = geometry.id;
  33379. serializationObject.geometryId = geometryId;
  33380. // SubMeshes
  33381. serializationObject.subMeshes = [];
  33382. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33383. var subMesh = this.subMeshes[subIndex];
  33384. serializationObject.subMeshes.push({
  33385. materialIndex: subMesh.materialIndex,
  33386. verticesStart: subMesh.verticesStart,
  33387. verticesCount: subMesh.verticesCount,
  33388. indexStart: subMesh.indexStart,
  33389. indexCount: subMesh.indexCount
  33390. });
  33391. }
  33392. }
  33393. // Material
  33394. if (this.material) {
  33395. serializationObject.materialId = this.material.id;
  33396. }
  33397. else {
  33398. this.material = null;
  33399. }
  33400. // Morph targets
  33401. if (this.morphTargetManager) {
  33402. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33403. }
  33404. // Skeleton
  33405. if (this.skeleton) {
  33406. serializationObject.skeletonId = this.skeleton.id;
  33407. }
  33408. // Physics
  33409. //TODO implement correct serialization for physics impostors.
  33410. var impostor = this.getPhysicsImpostor();
  33411. if (impostor) {
  33412. serializationObject.physicsMass = impostor.getParam("mass");
  33413. serializationObject.physicsFriction = impostor.getParam("friction");
  33414. serializationObject.physicsRestitution = impostor.getParam("mass");
  33415. serializationObject.physicsImpostor = impostor.type;
  33416. }
  33417. // Metadata
  33418. if (this.metadata) {
  33419. serializationObject.metadata = this.metadata;
  33420. }
  33421. // Instances
  33422. serializationObject.instances = [];
  33423. for (var index = 0; index < this.instances.length; index++) {
  33424. var instance = this.instances[index];
  33425. var serializationInstance = {
  33426. name: instance.name,
  33427. id: instance.id,
  33428. position: instance.position.asArray(),
  33429. scaling: instance.scaling.asArray()
  33430. };
  33431. if (instance.rotationQuaternion) {
  33432. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33433. }
  33434. else if (instance.rotation) {
  33435. serializationInstance.rotation = instance.rotation.asArray();
  33436. }
  33437. serializationObject.instances.push(serializationInstance);
  33438. // Animations
  33439. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33440. serializationInstance.ranges = instance.serializeAnimationRanges();
  33441. }
  33442. //
  33443. // Animations
  33444. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33445. serializationObject.ranges = this.serializeAnimationRanges();
  33446. // Layer mask
  33447. serializationObject.layerMask = this.layerMask;
  33448. // Alpha
  33449. serializationObject.alphaIndex = this.alphaIndex;
  33450. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33451. // Overlay
  33452. serializationObject.overlayAlpha = this.overlayAlpha;
  33453. serializationObject.overlayColor = this.overlayColor.asArray();
  33454. serializationObject.renderOverlay = this.renderOverlay;
  33455. // Fog
  33456. serializationObject.applyFog = this.applyFog;
  33457. // Action Manager
  33458. if (this.actionManager) {
  33459. serializationObject.actions = this.actionManager.serialize(this.name);
  33460. }
  33461. };
  33462. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33463. if (!this.geometry) {
  33464. return;
  33465. }
  33466. this._markSubMeshesAsAttributesDirty();
  33467. var morphTargetManager = this._morphTargetManager;
  33468. if (morphTargetManager && morphTargetManager.vertexCount) {
  33469. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33470. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33471. this.morphTargetManager = null;
  33472. return;
  33473. }
  33474. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33475. var morphTarget = morphTargetManager.getActiveTarget(index);
  33476. var positions = morphTarget.getPositions();
  33477. if (!positions) {
  33478. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33479. return;
  33480. }
  33481. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33482. var normals = morphTarget.getNormals();
  33483. if (normals) {
  33484. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33485. }
  33486. var tangents = morphTarget.getTangents();
  33487. if (tangents) {
  33488. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33489. }
  33490. }
  33491. }
  33492. else {
  33493. var index = 0;
  33494. // Positions
  33495. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33496. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33497. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33498. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33499. }
  33500. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33501. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33502. }
  33503. index++;
  33504. }
  33505. }
  33506. };
  33507. // Statics
  33508. /**
  33509. * Returns a new Mesh object parsed from the source provided.
  33510. * The parameter `parsedMesh` is the source.
  33511. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33512. */
  33513. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33514. var mesh;
  33515. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33516. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33517. }
  33518. else {
  33519. mesh = new Mesh(parsedMesh.name, scene);
  33520. }
  33521. mesh.id = parsedMesh.id;
  33522. if (BABYLON.Tags) {
  33523. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33524. }
  33525. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33526. if (parsedMesh.metadata !== undefined) {
  33527. mesh.metadata = parsedMesh.metadata;
  33528. }
  33529. if (parsedMesh.rotationQuaternion) {
  33530. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33531. }
  33532. else if (parsedMesh.rotation) {
  33533. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33534. }
  33535. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33536. if (parsedMesh.localMatrix) {
  33537. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33538. }
  33539. else if (parsedMesh.pivotMatrix) {
  33540. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33541. }
  33542. mesh.setEnabled(parsedMesh.isEnabled);
  33543. mesh.isVisible = parsedMesh.isVisible;
  33544. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33545. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33546. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33547. if (parsedMesh.applyFog !== undefined) {
  33548. mesh.applyFog = parsedMesh.applyFog;
  33549. }
  33550. if (parsedMesh.pickable !== undefined) {
  33551. mesh.isPickable = parsedMesh.pickable;
  33552. }
  33553. if (parsedMesh.alphaIndex !== undefined) {
  33554. mesh.alphaIndex = parsedMesh.alphaIndex;
  33555. }
  33556. mesh.receiveShadows = parsedMesh.receiveShadows;
  33557. mesh.billboardMode = parsedMesh.billboardMode;
  33558. if (parsedMesh.visibility !== undefined) {
  33559. mesh.visibility = parsedMesh.visibility;
  33560. }
  33561. mesh.checkCollisions = parsedMesh.checkCollisions;
  33562. if (parsedMesh.isBlocker !== undefined) {
  33563. mesh.isBlocker = parsedMesh.isBlocker;
  33564. }
  33565. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33566. // freezeWorldMatrix
  33567. if (parsedMesh.freezeWorldMatrix) {
  33568. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33569. }
  33570. // Parent
  33571. if (parsedMesh.parentId) {
  33572. mesh._waitingParentId = parsedMesh.parentId;
  33573. }
  33574. // Actions
  33575. if (parsedMesh.actions !== undefined) {
  33576. mesh._waitingActions = parsedMesh.actions;
  33577. }
  33578. // Overlay
  33579. if (parsedMesh.overlayAlpha !== undefined) {
  33580. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33581. }
  33582. if (parsedMesh.overlayColor !== undefined) {
  33583. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33584. }
  33585. if (parsedMesh.renderOverlay !== undefined) {
  33586. mesh.renderOverlay = parsedMesh.renderOverlay;
  33587. }
  33588. // Geometry
  33589. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33590. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33591. if (parsedMesh.delayLoadingFile) {
  33592. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33593. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33594. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33595. if (parsedMesh._binaryInfo) {
  33596. mesh._binaryInfo = parsedMesh._binaryInfo;
  33597. }
  33598. mesh._delayInfo = [];
  33599. if (parsedMesh.hasUVs) {
  33600. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33601. }
  33602. if (parsedMesh.hasUVs2) {
  33603. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33604. }
  33605. if (parsedMesh.hasUVs3) {
  33606. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33607. }
  33608. if (parsedMesh.hasUVs4) {
  33609. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33610. }
  33611. if (parsedMesh.hasUVs5) {
  33612. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33613. }
  33614. if (parsedMesh.hasUVs6) {
  33615. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33616. }
  33617. if (parsedMesh.hasColors) {
  33618. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33619. }
  33620. if (parsedMesh.hasMatricesIndices) {
  33621. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33622. }
  33623. if (parsedMesh.hasMatricesWeights) {
  33624. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33625. }
  33626. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33627. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33628. mesh._checkDelayState();
  33629. }
  33630. }
  33631. else {
  33632. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33633. }
  33634. // Material
  33635. if (parsedMesh.materialId) {
  33636. mesh.setMaterialByID(parsedMesh.materialId);
  33637. }
  33638. else {
  33639. mesh.material = null;
  33640. }
  33641. // Morph targets
  33642. if (parsedMesh.morphTargetManagerId > -1) {
  33643. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33644. }
  33645. // Skeleton
  33646. if (parsedMesh.skeletonId > -1) {
  33647. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33648. if (parsedMesh.numBoneInfluencers) {
  33649. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33650. }
  33651. }
  33652. // Animations
  33653. if (parsedMesh.animations) {
  33654. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33655. var parsedAnimation = parsedMesh.animations[animationIndex];
  33656. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33657. }
  33658. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33659. }
  33660. if (parsedMesh.autoAnimate) {
  33661. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33662. }
  33663. // Layer Mask
  33664. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33665. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33666. }
  33667. else {
  33668. mesh.layerMask = 0x0FFFFFFF;
  33669. }
  33670. // Physics
  33671. if (parsedMesh.physicsImpostor) {
  33672. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33673. mass: parsedMesh.physicsMass,
  33674. friction: parsedMesh.physicsFriction,
  33675. restitution: parsedMesh.physicsRestitution
  33676. }, scene);
  33677. }
  33678. // Instances
  33679. if (parsedMesh.instances) {
  33680. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33681. var parsedInstance = parsedMesh.instances[index];
  33682. var instance = mesh.createInstance(parsedInstance.name);
  33683. if (parsedInstance.id) {
  33684. instance.id = parsedInstance.id;
  33685. }
  33686. if (BABYLON.Tags) {
  33687. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33688. }
  33689. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33690. if (parsedInstance.parentId) {
  33691. instance._waitingParentId = parsedInstance.parentId;
  33692. }
  33693. if (parsedInstance.rotationQuaternion) {
  33694. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33695. }
  33696. else if (parsedInstance.rotation) {
  33697. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33698. }
  33699. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33700. instance.checkCollisions = mesh.checkCollisions;
  33701. if (parsedMesh.animations) {
  33702. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33703. parsedAnimation = parsedMesh.animations[animationIndex];
  33704. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33705. }
  33706. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33707. if (parsedMesh.autoAnimate) {
  33708. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33709. }
  33710. }
  33711. }
  33712. }
  33713. return mesh;
  33714. };
  33715. /**
  33716. * Creates a ribbon mesh.
  33717. * Please consider using the same method from the MeshBuilder class instead.
  33718. * 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.
  33719. *
  33720. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33721. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33722. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33723. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33724. * 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.
  33725. * 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.
  33726. * 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
  33727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33728. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33730. */
  33731. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33732. if (closeArray === void 0) { closeArray = false; }
  33733. if (updatable === void 0) { updatable = false; }
  33734. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33735. pathArray: pathArray,
  33736. closeArray: closeArray,
  33737. closePath: closePath,
  33738. offset: offset,
  33739. updatable: updatable,
  33740. sideOrientation: sideOrientation,
  33741. instance: instance
  33742. }, scene);
  33743. };
  33744. /**
  33745. * Creates a plane polygonal mesh. By default, this is a disc.
  33746. * Please consider using the same method from the MeshBuilder class instead.
  33747. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33748. * 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.
  33749. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33750. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33752. */
  33753. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33754. if (scene === void 0) { scene = null; }
  33755. var options = {
  33756. radius: radius,
  33757. tessellation: tessellation,
  33758. sideOrientation: sideOrientation,
  33759. updatable: updatable
  33760. };
  33761. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33762. };
  33763. /**
  33764. * Creates a box mesh.
  33765. * Please consider using the same method from the MeshBuilder class instead.
  33766. * The parameter `size` sets the size (float) of each box side (default 1).
  33767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33768. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33770. */
  33771. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33772. if (scene === void 0) { scene = null; }
  33773. var options = {
  33774. size: size,
  33775. sideOrientation: sideOrientation,
  33776. updatable: updatable
  33777. };
  33778. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33779. };
  33780. /**
  33781. * Creates a sphere mesh.
  33782. * Please consider using the same method from the MeshBuilder class instead.
  33783. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33784. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33786. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33788. */
  33789. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33790. var options = {
  33791. segments: segments,
  33792. diameterX: diameter,
  33793. diameterY: diameter,
  33794. diameterZ: diameter,
  33795. sideOrientation: sideOrientation,
  33796. updatable: updatable
  33797. };
  33798. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33799. };
  33800. /**
  33801. * Creates a cylinder or a cone mesh.
  33802. * Please consider using the same method from the MeshBuilder class instead.
  33803. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33804. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33805. * 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.
  33806. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33807. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33808. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33809. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33811. */
  33812. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33813. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33814. if (scene !== undefined) {
  33815. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33816. updatable = scene;
  33817. }
  33818. scene = subdivisions;
  33819. subdivisions = 1;
  33820. }
  33821. var options = {
  33822. height: height,
  33823. diameterTop: diameterTop,
  33824. diameterBottom: diameterBottom,
  33825. tessellation: tessellation,
  33826. subdivisions: subdivisions,
  33827. sideOrientation: sideOrientation,
  33828. updatable: updatable
  33829. };
  33830. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33831. };
  33832. // Torus (Code from SharpDX.org)
  33833. /**
  33834. * Creates a torus mesh.
  33835. * Please consider using the same method from the MeshBuilder class instead.
  33836. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33837. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33838. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33839. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33840. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33842. */
  33843. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33844. var options = {
  33845. diameter: diameter,
  33846. thickness: thickness,
  33847. tessellation: tessellation,
  33848. sideOrientation: sideOrientation,
  33849. updatable: updatable
  33850. };
  33851. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33852. };
  33853. /**
  33854. * Creates a torus knot mesh.
  33855. * Please consider using the same method from the MeshBuilder class instead.
  33856. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33857. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33858. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33859. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33861. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33863. */
  33864. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33865. var options = {
  33866. radius: radius,
  33867. tube: tube,
  33868. radialSegments: radialSegments,
  33869. tubularSegments: tubularSegments,
  33870. p: p,
  33871. q: q,
  33872. sideOrientation: sideOrientation,
  33873. updatable: updatable
  33874. };
  33875. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33876. };
  33877. /**
  33878. * Creates a line mesh.
  33879. * Please consider using the same method from the MeshBuilder class instead.
  33880. * 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.
  33881. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33882. * The parameter `points` is an array successive Vector3.
  33883. * 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
  33884. * When updating an instance, remember that only point positions can change, not the number of points.
  33885. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33886. */
  33887. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33888. if (scene === void 0) { scene = null; }
  33889. if (updatable === void 0) { updatable = false; }
  33890. if (instance === void 0) { instance = null; }
  33891. var options = {
  33892. points: points,
  33893. updatable: updatable,
  33894. instance: instance
  33895. };
  33896. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33897. };
  33898. /**
  33899. * Creates a dashed line mesh.
  33900. * Please consider using the same method from the MeshBuilder class instead.
  33901. * 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.
  33902. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33903. * The parameter `points` is an array successive Vector3.
  33904. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33905. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33906. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33907. * 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
  33908. * When updating an instance, remember that only point positions can change, not the number of points.
  33909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33910. */
  33911. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33912. if (scene === void 0) { scene = null; }
  33913. var options = {
  33914. points: points,
  33915. dashSize: dashSize,
  33916. gapSize: gapSize,
  33917. dashNb: dashNb,
  33918. updatable: updatable,
  33919. instance: instance
  33920. };
  33921. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33922. };
  33923. /**
  33924. * Creates a polygon mesh.
  33925. * Please consider using the same method from the MeshBuilder class instead.
  33926. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33927. * 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.
  33928. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33930. * Remember you can only change the shape positions, not their number when updating a polygon.
  33931. */
  33932. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33933. var options = {
  33934. shape: shape,
  33935. holes: holes,
  33936. updatable: updatable,
  33937. sideOrientation: sideOrientation
  33938. };
  33939. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33940. };
  33941. /**
  33942. * Creates an extruded polygon mesh, with depth in the Y direction.
  33943. * Please consider using the same method from the MeshBuilder class instead.
  33944. */
  33945. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33946. var options = {
  33947. shape: shape,
  33948. holes: holes,
  33949. depth: depth,
  33950. updatable: updatable,
  33951. sideOrientation: sideOrientation
  33952. };
  33953. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33954. };
  33955. /**
  33956. * Creates an extruded shape mesh.
  33957. * 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.
  33958. * Please consider using the same method from the MeshBuilder class instead.
  33959. *
  33960. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33961. * 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
  33962. * extruded along the Z axis.
  33963. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33964. * 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.
  33965. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33966. * 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
  33967. * 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
  33968. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33969. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33970. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33972. */
  33973. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33974. if (scene === void 0) { scene = null; }
  33975. var options = {
  33976. shape: shape,
  33977. path: path,
  33978. scale: scale,
  33979. rotation: rotation,
  33980. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33981. sideOrientation: sideOrientation,
  33982. instance: instance,
  33983. updatable: updatable
  33984. };
  33985. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33986. };
  33987. /**
  33988. * Creates an custom extruded shape mesh.
  33989. * 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.
  33990. * Please consider using the same method from the MeshBuilder class instead.
  33991. *
  33992. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33993. * 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
  33994. * extruded along the Z axis.
  33995. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33996. * 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
  33997. * and the distance of this point from the begining of the path :
  33998. * ```javascript
  33999. * var rotationFunction = function(i, distance) {
  34000. * // do things
  34001. * return rotationValue; }
  34002. * ```
  34003. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34004. * 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
  34005. * and the distance of this point from the begining of the path :
  34006. * ```javascript
  34007. * var scaleFunction = function(i, distance) {
  34008. * // do things
  34009. * return scaleValue;}
  34010. * ```
  34011. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34012. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34013. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34014. * 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
  34015. * 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
  34016. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34017. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34018. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34019. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34020. */
  34021. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34022. var options = {
  34023. shape: shape,
  34024. path: path,
  34025. scaleFunction: scaleFunction,
  34026. rotationFunction: rotationFunction,
  34027. ribbonCloseArray: ribbonCloseArray,
  34028. ribbonClosePath: ribbonClosePath,
  34029. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34030. sideOrientation: sideOrientation,
  34031. instance: instance,
  34032. updatable: updatable
  34033. };
  34034. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34035. };
  34036. /**
  34037. * Creates lathe mesh.
  34038. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34039. * Please consider using the same method from the MeshBuilder class instead.
  34040. * 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
  34041. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34042. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34043. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34044. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34045. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34047. */
  34048. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34049. var options = {
  34050. shape: shape,
  34051. radius: radius,
  34052. tessellation: tessellation,
  34053. sideOrientation: sideOrientation,
  34054. updatable: updatable
  34055. };
  34056. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34057. };
  34058. /**
  34059. * Creates a plane mesh.
  34060. * Please consider using the same method from the MeshBuilder class instead.
  34061. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34062. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34063. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34065. */
  34066. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34067. var options = {
  34068. size: size,
  34069. width: size,
  34070. height: size,
  34071. sideOrientation: sideOrientation,
  34072. updatable: updatable
  34073. };
  34074. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34075. };
  34076. /**
  34077. * Creates a ground mesh.
  34078. * Please consider using the same method from the MeshBuilder class instead.
  34079. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34080. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34082. */
  34083. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34084. var options = {
  34085. width: width,
  34086. height: height,
  34087. subdivisions: subdivisions,
  34088. updatable: updatable
  34089. };
  34090. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34091. };
  34092. /**
  34093. * Creates a tiled ground mesh.
  34094. * Please consider using the same method from the MeshBuilder class instead.
  34095. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34096. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34097. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34098. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34099. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34100. * numbers of subdivisions on the ground width and height of each tile.
  34101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34102. */
  34103. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34104. var options = {
  34105. xmin: xmin,
  34106. zmin: zmin,
  34107. xmax: xmax,
  34108. zmax: zmax,
  34109. subdivisions: subdivisions,
  34110. precision: precision,
  34111. updatable: updatable
  34112. };
  34113. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34114. };
  34115. /**
  34116. * Creates a ground mesh from a height map.
  34117. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34118. * Please consider using the same method from the MeshBuilder class instead.
  34119. * The parameter `url` sets the URL of the height map image resource.
  34120. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34121. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34122. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34123. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34124. * 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).
  34125. * This function is passed the newly built mesh :
  34126. * ```javascript
  34127. * function(mesh) { // do things
  34128. * return; }
  34129. * ```
  34130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34131. */
  34132. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34133. var options = {
  34134. width: width,
  34135. height: height,
  34136. subdivisions: subdivisions,
  34137. minHeight: minHeight,
  34138. maxHeight: maxHeight,
  34139. updatable: updatable,
  34140. onReady: onReady
  34141. };
  34142. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34143. };
  34144. /**
  34145. * Creates a tube mesh.
  34146. * 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.
  34147. * Please consider using the same method from the MeshBuilder class instead.
  34148. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34149. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34150. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34151. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34152. * 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.
  34153. * It must return a radius value (positive float) :
  34154. * ```javascript
  34155. * var radiusFunction = function(i, distance) {
  34156. * // do things
  34157. * return radius; }
  34158. * ```
  34159. * 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
  34160. * 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
  34161. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34162. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34163. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34164. */
  34165. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34166. var options = {
  34167. path: path,
  34168. radius: radius,
  34169. tessellation: tessellation,
  34170. radiusFunction: radiusFunction,
  34171. arc: 1,
  34172. cap: cap,
  34173. updatable: updatable,
  34174. sideOrientation: sideOrientation,
  34175. instance: instance
  34176. };
  34177. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34178. };
  34179. /**
  34180. * Creates a polyhedron mesh.
  34181. * Please consider using the same method from the MeshBuilder class instead.
  34182. * 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
  34183. * to choose the wanted type.
  34184. * The parameter `size` (positive float, default 1) sets the polygon size.
  34185. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34186. * 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`.
  34187. * 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
  34188. * 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)`).
  34189. * 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
  34190. * 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.
  34191. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34192. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34194. */
  34195. Mesh.CreatePolyhedron = function (name, options, scene) {
  34196. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34197. };
  34198. /**
  34199. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34200. * Please consider using the same method from the MeshBuilder class instead.
  34201. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34202. * 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`).
  34203. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34204. * 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.
  34205. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34206. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34207. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34208. */
  34209. Mesh.CreateIcoSphere = function (name, options, scene) {
  34210. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34211. };
  34212. /**
  34213. * Creates a decal mesh.
  34214. * Please consider using the same method from the MeshBuilder class instead.
  34215. * 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.
  34216. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34217. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34218. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34219. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34220. */
  34221. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34222. var options = {
  34223. position: position,
  34224. normal: normal,
  34225. size: size,
  34226. angle: angle
  34227. };
  34228. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34229. };
  34230. // Skeletons
  34231. /**
  34232. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34233. */
  34234. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34235. if (!this._sourcePositions) {
  34236. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34237. if (!source) {
  34238. return this._sourcePositions;
  34239. }
  34240. this._sourcePositions = new Float32Array(source);
  34241. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34242. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34243. }
  34244. }
  34245. return this._sourcePositions;
  34246. };
  34247. /**
  34248. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34249. */
  34250. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34251. if (!this._sourceNormals) {
  34252. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34253. if (!source) {
  34254. return this._sourceNormals;
  34255. }
  34256. this._sourceNormals = new Float32Array(source);
  34257. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34258. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34259. }
  34260. }
  34261. return this._sourceNormals;
  34262. };
  34263. /**
  34264. * Updates the vertex buffer by applying transformation from the bones.
  34265. * Returns the Mesh.
  34266. *
  34267. * @param {skeleton} skeleton to apply
  34268. */
  34269. Mesh.prototype.applySkeleton = function (skeleton) {
  34270. if (!this.geometry) {
  34271. return this;
  34272. }
  34273. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34274. return this;
  34275. }
  34276. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34277. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34278. return this;
  34279. }
  34280. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34281. return this;
  34282. }
  34283. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34284. return this;
  34285. }
  34286. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34287. return this;
  34288. }
  34289. if (!this._sourcePositions) {
  34290. var submeshes = this.subMeshes.slice();
  34291. this.setPositionsForCPUSkinning();
  34292. this.subMeshes = submeshes;
  34293. }
  34294. if (!this._sourceNormals) {
  34295. this.setNormalsForCPUSkinning();
  34296. }
  34297. // positionsData checks for not being Float32Array will only pass at most once
  34298. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34299. if (!positionsData) {
  34300. return this;
  34301. }
  34302. if (!(positionsData instanceof Float32Array)) {
  34303. positionsData = new Float32Array(positionsData);
  34304. }
  34305. // normalsData checks for not being Float32Array will only pass at most once
  34306. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34307. if (!normalsData) {
  34308. return this;
  34309. }
  34310. if (!(normalsData instanceof Float32Array)) {
  34311. normalsData = new Float32Array(normalsData);
  34312. }
  34313. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34314. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34315. if (!matricesWeightsData || !matricesIndicesData) {
  34316. return this;
  34317. }
  34318. var needExtras = this.numBoneInfluencers > 4;
  34319. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34320. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34321. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34322. var tempVector3 = BABYLON.Vector3.Zero();
  34323. var finalMatrix = new BABYLON.Matrix();
  34324. var tempMatrix = new BABYLON.Matrix();
  34325. var matWeightIdx = 0;
  34326. var inf;
  34327. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34328. var weight;
  34329. for (inf = 0; inf < 4; inf++) {
  34330. weight = matricesWeightsData[matWeightIdx + inf];
  34331. if (weight > 0) {
  34332. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34333. finalMatrix.addToSelf(tempMatrix);
  34334. }
  34335. else
  34336. break;
  34337. }
  34338. if (needExtras) {
  34339. for (inf = 0; inf < 4; inf++) {
  34340. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34341. if (weight > 0) {
  34342. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34343. finalMatrix.addToSelf(tempMatrix);
  34344. }
  34345. else
  34346. break;
  34347. }
  34348. }
  34349. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34350. tempVector3.toArray(positionsData, index);
  34351. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34352. tempVector3.toArray(normalsData, index);
  34353. finalMatrix.reset();
  34354. }
  34355. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34356. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34357. return this;
  34358. };
  34359. // Tools
  34360. /**
  34361. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34362. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34363. */
  34364. Mesh.MinMax = function (meshes) {
  34365. var minVector = null;
  34366. var maxVector = null;
  34367. meshes.forEach(function (mesh, index, array) {
  34368. var boundingInfo = mesh.getBoundingInfo();
  34369. var boundingBox = boundingInfo.boundingBox;
  34370. if (!minVector || !maxVector) {
  34371. minVector = boundingBox.minimumWorld;
  34372. maxVector = boundingBox.maximumWorld;
  34373. }
  34374. else {
  34375. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34376. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34377. }
  34378. });
  34379. if (!minVector || !maxVector) {
  34380. return {
  34381. min: BABYLON.Vector3.Zero(),
  34382. max: BABYLON.Vector3.Zero()
  34383. };
  34384. }
  34385. return {
  34386. min: minVector,
  34387. max: maxVector
  34388. };
  34389. };
  34390. /**
  34391. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34392. */
  34393. Mesh.Center = function (meshesOrMinMaxVector) {
  34394. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34395. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34396. };
  34397. /**
  34398. * Merge the array of meshes into a single mesh for performance reasons.
  34399. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34400. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34401. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34402. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34403. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34404. */
  34405. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34406. if (disposeSource === void 0) { disposeSource = true; }
  34407. var index;
  34408. if (!allow32BitsIndices) {
  34409. var totalVertices = 0;
  34410. // Counting vertices
  34411. for (index = 0; index < meshes.length; index++) {
  34412. if (meshes[index]) {
  34413. totalVertices += meshes[index].getTotalVertices();
  34414. if (totalVertices > 65536) {
  34415. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34416. return null;
  34417. }
  34418. }
  34419. }
  34420. }
  34421. // Merge
  34422. var vertexData = null;
  34423. var otherVertexData;
  34424. var indiceArray = new Array();
  34425. var source = null;
  34426. for (index = 0; index < meshes.length; index++) {
  34427. if (meshes[index]) {
  34428. meshes[index].computeWorldMatrix(true);
  34429. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34430. otherVertexData.transform(meshes[index].getWorldMatrix());
  34431. if (vertexData) {
  34432. vertexData.merge(otherVertexData);
  34433. }
  34434. else {
  34435. vertexData = otherVertexData;
  34436. source = meshes[index];
  34437. }
  34438. if (subdivideWithSubMeshes) {
  34439. indiceArray.push(meshes[index].getTotalIndices());
  34440. }
  34441. }
  34442. }
  34443. source = source;
  34444. if (!meshSubclass) {
  34445. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34446. }
  34447. vertexData.applyToMesh(meshSubclass);
  34448. // Setting properties
  34449. meshSubclass.material = source.material;
  34450. meshSubclass.checkCollisions = source.checkCollisions;
  34451. // Cleaning
  34452. if (disposeSource) {
  34453. for (index = 0; index < meshes.length; index++) {
  34454. if (meshes[index]) {
  34455. meshes[index].dispose();
  34456. }
  34457. }
  34458. }
  34459. // Subdivide
  34460. if (subdivideWithSubMeshes) {
  34461. //-- removal of global submesh
  34462. meshSubclass.releaseSubMeshes();
  34463. index = 0;
  34464. var offset = 0;
  34465. //-- apply subdivision according to index table
  34466. while (index < indiceArray.length) {
  34467. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34468. offset += indiceArray[index];
  34469. index++;
  34470. }
  34471. }
  34472. return meshSubclass;
  34473. };
  34474. // Consts
  34475. Mesh._FRONTSIDE = 0;
  34476. Mesh._BACKSIDE = 1;
  34477. Mesh._DOUBLESIDE = 2;
  34478. Mesh._DEFAULTSIDE = 0;
  34479. Mesh._NO_CAP = 0;
  34480. Mesh._CAP_START = 1;
  34481. Mesh._CAP_END = 2;
  34482. Mesh._CAP_ALL = 3;
  34483. return Mesh;
  34484. }(BABYLON.AbstractMesh));
  34485. BABYLON.Mesh = Mesh;
  34486. })(BABYLON || (BABYLON = {}));
  34487. //# sourceMappingURL=babylon.mesh.js.map
  34488. var BABYLON;
  34489. (function (BABYLON) {
  34490. var BaseSubMesh = /** @class */ (function () {
  34491. function BaseSubMesh() {
  34492. }
  34493. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34494. get: function () {
  34495. return this._materialEffect;
  34496. },
  34497. enumerable: true,
  34498. configurable: true
  34499. });
  34500. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34501. if (defines === void 0) { defines = null; }
  34502. if (this._materialEffect === effect) {
  34503. if (!effect) {
  34504. this._materialDefines = null;
  34505. }
  34506. return;
  34507. }
  34508. this._materialDefines = defines;
  34509. this._materialEffect = effect;
  34510. };
  34511. return BaseSubMesh;
  34512. }());
  34513. BABYLON.BaseSubMesh = BaseSubMesh;
  34514. var SubMesh = /** @class */ (function (_super) {
  34515. __extends(SubMesh, _super);
  34516. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34517. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34518. var _this = _super.call(this) || this;
  34519. _this.materialIndex = materialIndex;
  34520. _this.verticesStart = verticesStart;
  34521. _this.verticesCount = verticesCount;
  34522. _this.indexStart = indexStart;
  34523. _this.indexCount = indexCount;
  34524. _this._renderId = 0;
  34525. _this._mesh = mesh;
  34526. _this._renderingMesh = renderingMesh || mesh;
  34527. mesh.subMeshes.push(_this);
  34528. _this._trianglePlanes = [];
  34529. _this._id = mesh.subMeshes.length - 1;
  34530. if (createBoundingBox) {
  34531. _this.refreshBoundingInfo();
  34532. mesh.computeWorldMatrix(true);
  34533. }
  34534. return _this;
  34535. }
  34536. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34537. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34538. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34539. };
  34540. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34541. get: function () {
  34542. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34543. },
  34544. enumerable: true,
  34545. configurable: true
  34546. });
  34547. /**
  34548. * Returns the submesh BoudingInfo object.
  34549. */
  34550. SubMesh.prototype.getBoundingInfo = function () {
  34551. if (this.IsGlobal) {
  34552. return this._mesh.getBoundingInfo();
  34553. }
  34554. return this._boundingInfo;
  34555. };
  34556. /**
  34557. * Sets the submesh BoundingInfo.
  34558. * Return the SubMesh.
  34559. */
  34560. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34561. this._boundingInfo = boundingInfo;
  34562. return this;
  34563. };
  34564. /**
  34565. * Returns the mesh of the current submesh.
  34566. */
  34567. SubMesh.prototype.getMesh = function () {
  34568. return this._mesh;
  34569. };
  34570. /**
  34571. * Returns the rendering mesh of the submesh.
  34572. */
  34573. SubMesh.prototype.getRenderingMesh = function () {
  34574. return this._renderingMesh;
  34575. };
  34576. /**
  34577. * Returns the submesh material.
  34578. */
  34579. SubMesh.prototype.getMaterial = function () {
  34580. var rootMaterial = this._renderingMesh.material;
  34581. if (rootMaterial === null || rootMaterial === undefined) {
  34582. return this._mesh.getScene().defaultMaterial;
  34583. }
  34584. else if (rootMaterial.getSubMaterial) {
  34585. var multiMaterial = rootMaterial;
  34586. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34587. if (this._currentMaterial !== effectiveMaterial) {
  34588. this._currentMaterial = effectiveMaterial;
  34589. this._materialDefines = null;
  34590. }
  34591. return effectiveMaterial;
  34592. }
  34593. return rootMaterial;
  34594. };
  34595. // Methods
  34596. /**
  34597. * Sets a new updated BoundingInfo object to the submesh.
  34598. * Returns the SubMesh.
  34599. */
  34600. SubMesh.prototype.refreshBoundingInfo = function () {
  34601. this._lastColliderWorldVertices = null;
  34602. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34603. return this;
  34604. }
  34605. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34606. if (!data) {
  34607. this._boundingInfo = this._mesh.getBoundingInfo();
  34608. return this;
  34609. }
  34610. var indices = this._renderingMesh.getIndices();
  34611. var extend;
  34612. //is this the only submesh?
  34613. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34614. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34615. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34616. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34617. }
  34618. else {
  34619. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34620. }
  34621. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34622. return this;
  34623. };
  34624. SubMesh.prototype._checkCollision = function (collider) {
  34625. var boundingInfo = this.getBoundingInfo();
  34626. return boundingInfo._checkCollision(collider);
  34627. };
  34628. /**
  34629. * Updates the submesh BoundingInfo.
  34630. * Returns the Submesh.
  34631. */
  34632. SubMesh.prototype.updateBoundingInfo = function (world) {
  34633. var boundingInfo = this.getBoundingInfo();
  34634. if (!boundingInfo) {
  34635. this.refreshBoundingInfo();
  34636. boundingInfo = this.getBoundingInfo();
  34637. }
  34638. boundingInfo.update(world);
  34639. return this;
  34640. };
  34641. /**
  34642. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34643. * Boolean returned.
  34644. */
  34645. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34646. var boundingInfo = this.getBoundingInfo();
  34647. if (!boundingInfo) {
  34648. return false;
  34649. }
  34650. return boundingInfo.isInFrustum(frustumPlanes);
  34651. };
  34652. /**
  34653. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34654. * Boolean returned.
  34655. */
  34656. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34657. var boundingInfo = this.getBoundingInfo();
  34658. if (!boundingInfo) {
  34659. return false;
  34660. }
  34661. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34662. };
  34663. /**
  34664. * Renders the submesh.
  34665. * Returns it.
  34666. */
  34667. SubMesh.prototype.render = function (enableAlphaMode) {
  34668. this._renderingMesh.render(this, enableAlphaMode);
  34669. return this;
  34670. };
  34671. /**
  34672. * Returns a new Index Buffer.
  34673. * Type returned : WebGLBuffer.
  34674. */
  34675. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34676. if (!this._linesIndexBuffer) {
  34677. var linesIndices = [];
  34678. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34679. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34680. }
  34681. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34682. this.linesIndexCount = linesIndices.length;
  34683. }
  34684. return this._linesIndexBuffer;
  34685. };
  34686. /**
  34687. * True is the passed Ray intersects the submesh bounding box.
  34688. * Boolean returned.
  34689. */
  34690. SubMesh.prototype.canIntersects = function (ray) {
  34691. var boundingInfo = this.getBoundingInfo();
  34692. if (!boundingInfo) {
  34693. return false;
  34694. }
  34695. return ray.intersectsBox(boundingInfo.boundingBox);
  34696. };
  34697. /**
  34698. * Returns an object IntersectionInfo.
  34699. */
  34700. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34701. var intersectInfo = null;
  34702. var material = this.getMaterial();
  34703. if (!material) {
  34704. return null;
  34705. }
  34706. switch (material.fillMode) {
  34707. case BABYLON.Material.PointListDrawMode:
  34708. case BABYLON.Material.LineListDrawMode:
  34709. case BABYLON.Material.LineLoopDrawMode:
  34710. case BABYLON.Material.LineStripDrawMode:
  34711. case BABYLON.Material.TriangleFanDrawMode:
  34712. case BABYLON.Material.TriangleStripDrawMode:
  34713. return null;
  34714. }
  34715. // LineMesh first as it's also a Mesh...
  34716. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34717. var lineMesh = this._mesh;
  34718. // Line test
  34719. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34720. var p0 = positions[indices[index]];
  34721. var p1 = positions[indices[index + 1]];
  34722. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34723. if (length < 0) {
  34724. continue;
  34725. }
  34726. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34727. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34728. if (fastCheck) {
  34729. break;
  34730. }
  34731. }
  34732. }
  34733. }
  34734. else {
  34735. // Triangles test
  34736. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34737. var p0 = positions[indices[index]];
  34738. var p1 = positions[indices[index + 1]];
  34739. var p2 = positions[indices[index + 2]];
  34740. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34741. if (currentIntersectInfo) {
  34742. if (currentIntersectInfo.distance < 0) {
  34743. continue;
  34744. }
  34745. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34746. intersectInfo = currentIntersectInfo;
  34747. intersectInfo.faceId = index / 3;
  34748. if (fastCheck) {
  34749. break;
  34750. }
  34751. }
  34752. }
  34753. }
  34754. }
  34755. return intersectInfo;
  34756. };
  34757. SubMesh.prototype._rebuild = function () {
  34758. if (this._linesIndexBuffer) {
  34759. this._linesIndexBuffer = null;
  34760. }
  34761. };
  34762. // Clone
  34763. /**
  34764. * Creates a new Submesh from the passed Mesh.
  34765. */
  34766. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34767. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34768. if (!this.IsGlobal) {
  34769. var boundingInfo = this.getBoundingInfo();
  34770. if (!boundingInfo) {
  34771. return result;
  34772. }
  34773. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34774. }
  34775. return result;
  34776. };
  34777. // Dispose
  34778. /**
  34779. * Disposes the Submesh.
  34780. * Returns nothing.
  34781. */
  34782. SubMesh.prototype.dispose = function () {
  34783. if (this._linesIndexBuffer) {
  34784. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34785. this._linesIndexBuffer = null;
  34786. }
  34787. // Remove from mesh
  34788. var index = this._mesh.subMeshes.indexOf(this);
  34789. this._mesh.subMeshes.splice(index, 1);
  34790. };
  34791. // Statics
  34792. /**
  34793. * Creates a new Submesh from the passed parameters :
  34794. * - materialIndex (integer) : the index of the main mesh material.
  34795. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34796. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34797. * - mesh (Mesh) : the main mesh to create the submesh from.
  34798. * - renderingMesh (optional Mesh) : rendering mesh.
  34799. */
  34800. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34801. var minVertexIndex = Number.MAX_VALUE;
  34802. var maxVertexIndex = -Number.MAX_VALUE;
  34803. renderingMesh = (renderingMesh || mesh);
  34804. var indices = renderingMesh.getIndices();
  34805. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34806. var vertexIndex = indices[index];
  34807. if (vertexIndex < minVertexIndex)
  34808. minVertexIndex = vertexIndex;
  34809. if (vertexIndex > maxVertexIndex)
  34810. maxVertexIndex = vertexIndex;
  34811. }
  34812. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34813. };
  34814. return SubMesh;
  34815. }(BaseSubMesh));
  34816. BABYLON.SubMesh = SubMesh;
  34817. })(BABYLON || (BABYLON = {}));
  34818. //# sourceMappingURL=babylon.subMesh.js.map
  34819. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34820. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34821. s = arguments[i];
  34822. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34823. t[p] = s[p];
  34824. }
  34825. return t;
  34826. };
  34827. var BABYLON;
  34828. (function (BABYLON) {
  34829. /**
  34830. * Manages the defines for the Material
  34831. */
  34832. var MaterialDefines = /** @class */ (function () {
  34833. function MaterialDefines() {
  34834. this._isDirty = true;
  34835. /** @hidden */
  34836. this._areLightsDirty = true;
  34837. /** @hidden */
  34838. this._areAttributesDirty = true;
  34839. /** @hidden */
  34840. this._areTexturesDirty = true;
  34841. /** @hidden */
  34842. this._areFresnelDirty = true;
  34843. /** @hidden */
  34844. this._areMiscDirty = true;
  34845. /** @hidden */
  34846. this._areImageProcessingDirty = true;
  34847. /** @hidden */
  34848. this._normals = false;
  34849. /** @hidden */
  34850. this._uvs = false;
  34851. /** @hidden */
  34852. this._needNormals = false;
  34853. /** @hidden */
  34854. this._needUVs = false;
  34855. }
  34856. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34857. /**
  34858. * Specifies if the material needs to be re-calculated
  34859. */
  34860. get: function () {
  34861. return this._isDirty;
  34862. },
  34863. enumerable: true,
  34864. configurable: true
  34865. });
  34866. /**
  34867. * Marks the material to indicate that it has been re-calculated
  34868. */
  34869. MaterialDefines.prototype.markAsProcessed = function () {
  34870. this._isDirty = false;
  34871. this._areAttributesDirty = false;
  34872. this._areTexturesDirty = false;
  34873. this._areFresnelDirty = false;
  34874. this._areLightsDirty = false;
  34875. this._areMiscDirty = false;
  34876. this._areImageProcessingDirty = false;
  34877. };
  34878. /**
  34879. * Marks the material to indicate that it needs to be re-calculated
  34880. */
  34881. MaterialDefines.prototype.markAsUnprocessed = function () {
  34882. this._isDirty = true;
  34883. };
  34884. /**
  34885. * Marks the material to indicate all of its defines need to be re-calculated
  34886. */
  34887. MaterialDefines.prototype.markAllAsDirty = function () {
  34888. this._areTexturesDirty = true;
  34889. this._areAttributesDirty = true;
  34890. this._areLightsDirty = true;
  34891. this._areFresnelDirty = true;
  34892. this._areMiscDirty = true;
  34893. this._areImageProcessingDirty = true;
  34894. this._isDirty = true;
  34895. };
  34896. /**
  34897. * Marks the material to indicate that image processing needs to be re-calculated
  34898. */
  34899. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34900. this._areImageProcessingDirty = true;
  34901. this._isDirty = true;
  34902. };
  34903. /**
  34904. * Marks the material to indicate the lights need to be re-calculated
  34905. */
  34906. MaterialDefines.prototype.markAsLightDirty = function () {
  34907. this._areLightsDirty = true;
  34908. this._isDirty = true;
  34909. };
  34910. /**
  34911. * Marks the attribute state as changed
  34912. */
  34913. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34914. this._areAttributesDirty = true;
  34915. this._isDirty = true;
  34916. };
  34917. /**
  34918. * Marks the texture state as changed
  34919. */
  34920. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34921. this._areTexturesDirty = true;
  34922. this._isDirty = true;
  34923. };
  34924. /**
  34925. * Marks the fresnel state as changed
  34926. */
  34927. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34928. this._areFresnelDirty = true;
  34929. this._isDirty = true;
  34930. };
  34931. /**
  34932. * Marks the misc state as changed
  34933. */
  34934. MaterialDefines.prototype.markAsMiscDirty = function () {
  34935. this._areMiscDirty = true;
  34936. this._isDirty = true;
  34937. };
  34938. /**
  34939. * Rebuilds the material defines
  34940. */
  34941. MaterialDefines.prototype.rebuild = function () {
  34942. if (this._keys) {
  34943. delete this._keys;
  34944. }
  34945. this._keys = [];
  34946. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34947. var key = _a[_i];
  34948. if (key[0] === "_") {
  34949. continue;
  34950. }
  34951. this._keys.push(key);
  34952. }
  34953. };
  34954. /**
  34955. * Specifies if two material defines are equal
  34956. * @param other - A material define instance to compare to
  34957. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34958. */
  34959. MaterialDefines.prototype.isEqual = function (other) {
  34960. if (this._keys.length !== other._keys.length) {
  34961. return false;
  34962. }
  34963. for (var index = 0; index < this._keys.length; index++) {
  34964. var prop = this._keys[index];
  34965. if (this[prop] !== other[prop]) {
  34966. return false;
  34967. }
  34968. }
  34969. return true;
  34970. };
  34971. /**
  34972. * Clones this instance's defines to another instance
  34973. * @param other - material defines to clone values to
  34974. */
  34975. MaterialDefines.prototype.cloneTo = function (other) {
  34976. if (this._keys.length !== other._keys.length) {
  34977. other._keys = this._keys.slice(0);
  34978. }
  34979. for (var index = 0; index < this._keys.length; index++) {
  34980. var prop = this._keys[index];
  34981. other[prop] = this[prop];
  34982. }
  34983. };
  34984. /**
  34985. * Resets the material define values
  34986. */
  34987. MaterialDefines.prototype.reset = function () {
  34988. for (var index = 0; index < this._keys.length; index++) {
  34989. var prop = this._keys[index];
  34990. var type = typeof this[prop];
  34991. switch (type) {
  34992. case "number":
  34993. this[prop] = 0;
  34994. break;
  34995. case "string":
  34996. this[prop] = "";
  34997. break;
  34998. default:
  34999. this[prop] = false;
  35000. break;
  35001. }
  35002. }
  35003. };
  35004. /**
  35005. * Converts the material define values to a string
  35006. * @returns - String of material define information
  35007. */
  35008. MaterialDefines.prototype.toString = function () {
  35009. var result = "";
  35010. for (var index = 0; index < this._keys.length; index++) {
  35011. var prop = this._keys[index];
  35012. var value = this[prop];
  35013. var type = typeof value;
  35014. switch (type) {
  35015. case "number":
  35016. case "string":
  35017. result += "#define " + prop + " " + value + "\n";
  35018. break;
  35019. default:
  35020. if (value) {
  35021. result += "#define " + prop + "\n";
  35022. }
  35023. break;
  35024. }
  35025. }
  35026. return result;
  35027. };
  35028. return MaterialDefines;
  35029. }());
  35030. BABYLON.MaterialDefines = MaterialDefines;
  35031. /**
  35032. * Base class for the main features of a material in Babylon.js
  35033. */
  35034. var Material = /** @class */ (function () {
  35035. /**
  35036. * Creates a material instance
  35037. * @param name defines the name of the material
  35038. * @param scene defines the scene to reference
  35039. * @param doNotAdd specifies if the material should be added to the scene
  35040. */
  35041. function Material(name, scene, doNotAdd) {
  35042. /**
  35043. * Specifies if the ready state should be checked on each call
  35044. */
  35045. this.checkReadyOnEveryCall = false;
  35046. /**
  35047. * Specifies if the ready state should be checked once
  35048. */
  35049. this.checkReadyOnlyOnce = false;
  35050. /**
  35051. * The state of the material
  35052. */
  35053. this.state = "";
  35054. /**
  35055. * The alpha value of the material
  35056. */
  35057. this._alpha = 1.0;
  35058. /**
  35059. * Specifies if back face culling is enabled
  35060. */
  35061. this._backFaceCulling = true;
  35062. /**
  35063. * Specifies if the material should be serialized
  35064. */
  35065. this.doNotSerialize = false;
  35066. /**
  35067. * Specifies if the effect should be stored on sub meshes
  35068. */
  35069. this.storeEffectOnSubMeshes = false;
  35070. /**
  35071. * An event triggered when the material is disposed
  35072. */
  35073. this.onDisposeObservable = new BABYLON.Observable();
  35074. /**
  35075. * An event triggered when the material is bound
  35076. */
  35077. this.onBindObservable = new BABYLON.Observable();
  35078. /**
  35079. * An event triggered when the material is unbound
  35080. */
  35081. this.onUnBindObservable = new BABYLON.Observable();
  35082. /**
  35083. * Stores the value of the alpha mode
  35084. */
  35085. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35086. /**
  35087. * Stores the state of the need depth pre-pass value
  35088. */
  35089. this._needDepthPrePass = false;
  35090. /**
  35091. * Specifies if depth writing should be disabled
  35092. */
  35093. this.disableDepthWrite = false;
  35094. /**
  35095. * Specifies if depth writing should be forced
  35096. */
  35097. this.forceDepthWrite = false;
  35098. /**
  35099. * Specifies if there should be a separate pass for culling
  35100. */
  35101. this.separateCullingPass = false;
  35102. /**
  35103. * Stores the state specifing if fog should be enabled
  35104. */
  35105. this._fogEnabled = true;
  35106. /**
  35107. * Stores the size of points
  35108. */
  35109. this.pointSize = 1.0;
  35110. /**
  35111. * Stores the z offset value
  35112. */
  35113. this.zOffset = 0;
  35114. /**
  35115. * Specifies if the material was previously ready
  35116. */
  35117. this._wasPreviouslyReady = false;
  35118. /**
  35119. * Stores the fill mode state
  35120. */
  35121. this._fillMode = Material.TriangleFillMode;
  35122. this.name = name;
  35123. this.id = name || BABYLON.Tools.RandomId();
  35124. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35125. this.uniqueId = this._scene.getUniqueId();
  35126. if (this._scene.useRightHandedSystem) {
  35127. this.sideOrientation = Material.ClockWiseSideOrientation;
  35128. }
  35129. else {
  35130. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35131. }
  35132. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35133. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35134. if (!doNotAdd) {
  35135. this._scene.materials.push(this);
  35136. }
  35137. }
  35138. Object.defineProperty(Material, "TriangleFillMode", {
  35139. /**
  35140. * Returns the triangle fill mode
  35141. */
  35142. get: function () {
  35143. return Material._TriangleFillMode;
  35144. },
  35145. enumerable: true,
  35146. configurable: true
  35147. });
  35148. Object.defineProperty(Material, "WireFrameFillMode", {
  35149. /**
  35150. * Returns the wireframe mode
  35151. */
  35152. get: function () {
  35153. return Material._WireFrameFillMode;
  35154. },
  35155. enumerable: true,
  35156. configurable: true
  35157. });
  35158. Object.defineProperty(Material, "PointFillMode", {
  35159. /**
  35160. * Returns the point fill mode
  35161. */
  35162. get: function () {
  35163. return Material._PointFillMode;
  35164. },
  35165. enumerable: true,
  35166. configurable: true
  35167. });
  35168. Object.defineProperty(Material, "PointListDrawMode", {
  35169. /**
  35170. * Returns the point list draw mode
  35171. */
  35172. get: function () {
  35173. return Material._PointListDrawMode;
  35174. },
  35175. enumerable: true,
  35176. configurable: true
  35177. });
  35178. Object.defineProperty(Material, "LineListDrawMode", {
  35179. /**
  35180. * Returns the line list draw mode
  35181. */
  35182. get: function () {
  35183. return Material._LineListDrawMode;
  35184. },
  35185. enumerable: true,
  35186. configurable: true
  35187. });
  35188. Object.defineProperty(Material, "LineLoopDrawMode", {
  35189. /**
  35190. * Returns the line loop draw mode
  35191. */
  35192. get: function () {
  35193. return Material._LineLoopDrawMode;
  35194. },
  35195. enumerable: true,
  35196. configurable: true
  35197. });
  35198. Object.defineProperty(Material, "LineStripDrawMode", {
  35199. /**
  35200. * Returns the line strip draw mode
  35201. */
  35202. get: function () {
  35203. return Material._LineStripDrawMode;
  35204. },
  35205. enumerable: true,
  35206. configurable: true
  35207. });
  35208. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35209. /**
  35210. * Returns the triangle strip draw mode
  35211. */
  35212. get: function () {
  35213. return Material._TriangleStripDrawMode;
  35214. },
  35215. enumerable: true,
  35216. configurable: true
  35217. });
  35218. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35219. /**
  35220. * Returns the triangle fan draw mode
  35221. */
  35222. get: function () {
  35223. return Material._TriangleFanDrawMode;
  35224. },
  35225. enumerable: true,
  35226. configurable: true
  35227. });
  35228. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35229. /**
  35230. * Returns the clock-wise side orientation
  35231. */
  35232. get: function () {
  35233. return Material._ClockWiseSideOrientation;
  35234. },
  35235. enumerable: true,
  35236. configurable: true
  35237. });
  35238. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35239. /**
  35240. * Returns the counter clock-wise side orientation
  35241. */
  35242. get: function () {
  35243. return Material._CounterClockWiseSideOrientation;
  35244. },
  35245. enumerable: true,
  35246. configurable: true
  35247. });
  35248. Object.defineProperty(Material, "TextureDirtyFlag", {
  35249. /**
  35250. * Returns the dirty texture flag value
  35251. */
  35252. get: function () {
  35253. return Material._TextureDirtyFlag;
  35254. },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. Object.defineProperty(Material, "LightDirtyFlag", {
  35259. /**
  35260. * Returns the dirty light flag value
  35261. */
  35262. get: function () {
  35263. return Material._LightDirtyFlag;
  35264. },
  35265. enumerable: true,
  35266. configurable: true
  35267. });
  35268. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35269. /**
  35270. * Returns the dirty fresnel flag value
  35271. */
  35272. get: function () {
  35273. return Material._FresnelDirtyFlag;
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35279. /**
  35280. * Returns the dirty attributes flag value
  35281. */
  35282. get: function () {
  35283. return Material._AttributesDirtyFlag;
  35284. },
  35285. enumerable: true,
  35286. configurable: true
  35287. });
  35288. Object.defineProperty(Material, "MiscDirtyFlag", {
  35289. /**
  35290. * Returns the dirty misc flag value
  35291. */
  35292. get: function () {
  35293. return Material._MiscDirtyFlag;
  35294. },
  35295. enumerable: true,
  35296. configurable: true
  35297. });
  35298. Object.defineProperty(Material.prototype, "alpha", {
  35299. /**
  35300. * Gets the alpha value of the material
  35301. */
  35302. get: function () {
  35303. return this._alpha;
  35304. },
  35305. /**
  35306. * Sets the alpha value of the material
  35307. */
  35308. set: function (value) {
  35309. if (this._alpha === value) {
  35310. return;
  35311. }
  35312. this._alpha = value;
  35313. this.markAsDirty(Material.MiscDirtyFlag);
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35319. /**
  35320. * Gets the back-face culling state
  35321. */
  35322. get: function () {
  35323. return this._backFaceCulling;
  35324. },
  35325. /**
  35326. * Sets the back-face culling state
  35327. */
  35328. set: function (value) {
  35329. if (this._backFaceCulling === value) {
  35330. return;
  35331. }
  35332. this._backFaceCulling = value;
  35333. this.markAsDirty(Material.TextureDirtyFlag);
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(Material.prototype, "onDispose", {
  35339. /**
  35340. * Called during a dispose event
  35341. */
  35342. set: function (callback) {
  35343. if (this._onDisposeObserver) {
  35344. this.onDisposeObservable.remove(this._onDisposeObserver);
  35345. }
  35346. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35347. },
  35348. enumerable: true,
  35349. configurable: true
  35350. });
  35351. Object.defineProperty(Material.prototype, "onBind", {
  35352. /**
  35353. * Called during a bind event
  35354. */
  35355. set: function (callback) {
  35356. if (this._onBindObserver) {
  35357. this.onBindObservable.remove(this._onBindObserver);
  35358. }
  35359. this._onBindObserver = this.onBindObservable.add(callback);
  35360. },
  35361. enumerable: true,
  35362. configurable: true
  35363. });
  35364. Object.defineProperty(Material.prototype, "alphaMode", {
  35365. /**
  35366. * Gets the value of the alpha mode
  35367. */
  35368. get: function () {
  35369. return this._alphaMode;
  35370. },
  35371. /**
  35372. * Sets the value of the alpha mode.
  35373. *
  35374. * | Value | Type | Description |
  35375. * | --- | --- | --- |
  35376. * | 0 | ALPHA_DISABLE | |
  35377. * | 1 | ALPHA_ADD | |
  35378. * | 2 | ALPHA_COMBINE | |
  35379. * | 3 | ALPHA_SUBTRACT | |
  35380. * | 4 | ALPHA_MULTIPLY | |
  35381. * | 5 | ALPHA_MAXIMIZED | |
  35382. * | 6 | ALPHA_ONEONE | |
  35383. * | 7 | ALPHA_PREMULTIPLIED | |
  35384. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35385. * | 9 | ALPHA_INTERPOLATE | |
  35386. * | 10 | ALPHA_SCREENMODE | |
  35387. *
  35388. */
  35389. set: function (value) {
  35390. if (this._alphaMode === value) {
  35391. return;
  35392. }
  35393. this._alphaMode = value;
  35394. this.markAsDirty(Material.TextureDirtyFlag);
  35395. },
  35396. enumerable: true,
  35397. configurable: true
  35398. });
  35399. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35400. /**
  35401. * Gets the depth pre-pass value
  35402. */
  35403. get: function () {
  35404. return this._needDepthPrePass;
  35405. },
  35406. /**
  35407. * Sets the need depth pre-pass value
  35408. */
  35409. set: function (value) {
  35410. if (this._needDepthPrePass === value) {
  35411. return;
  35412. }
  35413. this._needDepthPrePass = value;
  35414. if (this._needDepthPrePass) {
  35415. this.checkReadyOnEveryCall = true;
  35416. }
  35417. },
  35418. enumerable: true,
  35419. configurable: true
  35420. });
  35421. Object.defineProperty(Material.prototype, "fogEnabled", {
  35422. /**
  35423. * Gets the value of the fog enabled state
  35424. */
  35425. get: function () {
  35426. return this._fogEnabled;
  35427. },
  35428. /**
  35429. * Sets the state for enabling fog
  35430. */
  35431. set: function (value) {
  35432. if (this._fogEnabled === value) {
  35433. return;
  35434. }
  35435. this._fogEnabled = value;
  35436. this.markAsDirty(Material.MiscDirtyFlag);
  35437. },
  35438. enumerable: true,
  35439. configurable: true
  35440. });
  35441. Object.defineProperty(Material.prototype, "wireframe", {
  35442. /**
  35443. * Gets a value specifying if wireframe mode is enabled
  35444. */
  35445. get: function () {
  35446. switch (this._fillMode) {
  35447. case Material.WireFrameFillMode:
  35448. case Material.LineListDrawMode:
  35449. case Material.LineLoopDrawMode:
  35450. case Material.LineStripDrawMode:
  35451. return true;
  35452. }
  35453. return this._scene.forceWireframe;
  35454. },
  35455. /**
  35456. * Sets the state of wireframe mode
  35457. */
  35458. set: function (value) {
  35459. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. Object.defineProperty(Material.prototype, "pointsCloud", {
  35465. /**
  35466. * Gets the value specifying if point clouds are enabled
  35467. */
  35468. get: function () {
  35469. switch (this._fillMode) {
  35470. case Material.PointFillMode:
  35471. case Material.PointListDrawMode:
  35472. return true;
  35473. }
  35474. return this._scene.forcePointsCloud;
  35475. },
  35476. /**
  35477. * Sets the state of point cloud mode
  35478. */
  35479. set: function (value) {
  35480. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35481. },
  35482. enumerable: true,
  35483. configurable: true
  35484. });
  35485. Object.defineProperty(Material.prototype, "fillMode", {
  35486. /**
  35487. * Gets the material fill mode
  35488. */
  35489. get: function () {
  35490. return this._fillMode;
  35491. },
  35492. /**
  35493. * Sets the material fill mode
  35494. */
  35495. set: function (value) {
  35496. if (this._fillMode === value) {
  35497. return;
  35498. }
  35499. this._fillMode = value;
  35500. this.markAsDirty(Material.MiscDirtyFlag);
  35501. },
  35502. enumerable: true,
  35503. configurable: true
  35504. });
  35505. /**
  35506. * Returns a string representation of the current material
  35507. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35508. * @returns a string with material information
  35509. */
  35510. Material.prototype.toString = function (fullDetails) {
  35511. var ret = "Name: " + this.name;
  35512. if (fullDetails) {
  35513. }
  35514. return ret;
  35515. };
  35516. /**
  35517. * Gets the class name of the material
  35518. * @returns a string with the class name of the material
  35519. */
  35520. Material.prototype.getClassName = function () {
  35521. return "Material";
  35522. };
  35523. Object.defineProperty(Material.prototype, "isFrozen", {
  35524. /**
  35525. * Specifies if updates for the material been locked
  35526. */
  35527. get: function () {
  35528. return this.checkReadyOnlyOnce;
  35529. },
  35530. enumerable: true,
  35531. configurable: true
  35532. });
  35533. /**
  35534. * Locks updates for the material
  35535. */
  35536. Material.prototype.freeze = function () {
  35537. this.checkReadyOnlyOnce = true;
  35538. };
  35539. /**
  35540. * Unlocks updates for the material
  35541. */
  35542. Material.prototype.unfreeze = function () {
  35543. this.checkReadyOnlyOnce = false;
  35544. };
  35545. /**
  35546. * Specifies if the material is ready to be used
  35547. * @param mesh defines the mesh to check
  35548. * @param useInstances specifies if instances should be used
  35549. * @returns a boolean indicating if the material is ready to be used
  35550. */
  35551. Material.prototype.isReady = function (mesh, useInstances) {
  35552. return true;
  35553. };
  35554. /**
  35555. * Specifies that the submesh is ready to be used
  35556. * @param mesh defines the mesh to check
  35557. * @param subMesh defines which submesh to check
  35558. * @param useInstances specifies that instances should be used
  35559. * @returns a boolean indicating that the submesh is ready or not
  35560. */
  35561. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35562. return false;
  35563. };
  35564. /**
  35565. * Returns the material effect
  35566. * @returns the effect associated with the material
  35567. */
  35568. Material.prototype.getEffect = function () {
  35569. return this._effect;
  35570. };
  35571. /**
  35572. * Returns the current scene
  35573. * @returns a Scene
  35574. */
  35575. Material.prototype.getScene = function () {
  35576. return this._scene;
  35577. };
  35578. /**
  35579. * Specifies if the material will require alpha blending
  35580. * @returns a boolean specifying if alpha blending is needed
  35581. */
  35582. Material.prototype.needAlphaBlending = function () {
  35583. return (this.alpha < 1.0);
  35584. };
  35585. /**
  35586. * Specifies if the mesh will require alpha blending
  35587. * @param mesh defines the mesh to check
  35588. * @returns a boolean specifying if alpha blending is needed for the mesh
  35589. */
  35590. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35591. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35592. };
  35593. /**
  35594. * Specifies if this material should be rendered in alpha test mode
  35595. * @returns a boolean specifying if an alpha test is needed.
  35596. */
  35597. Material.prototype.needAlphaTesting = function () {
  35598. return false;
  35599. };
  35600. /**
  35601. * Gets the texture used for the alpha test
  35602. * @returns the texture to use for alpha testing
  35603. */
  35604. Material.prototype.getAlphaTestTexture = function () {
  35605. return null;
  35606. };
  35607. /**
  35608. * Marks the material to indicate that it needs to be re-calculated
  35609. */
  35610. Material.prototype.markDirty = function () {
  35611. this._wasPreviouslyReady = false;
  35612. };
  35613. /** @hidden */
  35614. Material.prototype._preBind = function (effect, overrideOrientation) {
  35615. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35616. var engine = this._scene.getEngine();
  35617. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35618. var reverse = orientation === Material.ClockWiseSideOrientation;
  35619. engine.enableEffect(effect ? effect : this._effect);
  35620. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35621. return reverse;
  35622. };
  35623. /**
  35624. * Binds the material to the mesh
  35625. * @param world defines the world transformation matrix
  35626. * @param mesh defines the mesh to bind the material to
  35627. */
  35628. Material.prototype.bind = function (world, mesh) {
  35629. };
  35630. /**
  35631. * Binds the submesh to the material
  35632. * @param world defines the world transformation matrix
  35633. * @param mesh defines the mesh containing the submesh
  35634. * @param subMesh defines the submesh to bind the material to
  35635. */
  35636. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35637. };
  35638. /**
  35639. * Binds the world matrix to the material
  35640. * @param world defines the world transformation matrix
  35641. */
  35642. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35643. };
  35644. /**
  35645. * Binds the scene's uniform buffer to the effect.
  35646. * @param effect defines the effect to bind to the scene uniform buffer
  35647. * @param sceneUbo defines the uniform buffer storing scene data
  35648. */
  35649. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35650. sceneUbo.bindToEffect(effect, "Scene");
  35651. };
  35652. /**
  35653. * Binds the view matrix to the effect
  35654. * @param effect defines the effect to bind the view matrix to
  35655. */
  35656. Material.prototype.bindView = function (effect) {
  35657. if (!this._useUBO) {
  35658. effect.setMatrix("view", this.getScene().getViewMatrix());
  35659. }
  35660. else {
  35661. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35662. }
  35663. };
  35664. /**
  35665. * Binds the view projection matrix to the effect
  35666. * @param effect defines the effect to bind the view projection matrix to
  35667. */
  35668. Material.prototype.bindViewProjection = function (effect) {
  35669. if (!this._useUBO) {
  35670. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35671. }
  35672. else {
  35673. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35674. }
  35675. };
  35676. /**
  35677. * Specifies if material alpha testing should be turned on for the mesh
  35678. * @param mesh defines the mesh to check
  35679. */
  35680. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35681. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35682. };
  35683. /**
  35684. * Processes to execute after binding the material to a mesh
  35685. * @param mesh defines the rendered mesh
  35686. */
  35687. Material.prototype._afterBind = function (mesh) {
  35688. this._scene._cachedMaterial = this;
  35689. if (mesh) {
  35690. this._scene._cachedVisibility = mesh.visibility;
  35691. }
  35692. else {
  35693. this._scene._cachedVisibility = 1;
  35694. }
  35695. if (mesh) {
  35696. this.onBindObservable.notifyObservers(mesh);
  35697. }
  35698. if (this.disableDepthWrite) {
  35699. var engine = this._scene.getEngine();
  35700. this._cachedDepthWriteState = engine.getDepthWrite();
  35701. engine.setDepthWrite(false);
  35702. }
  35703. };
  35704. /**
  35705. * Unbinds the material from the mesh
  35706. */
  35707. Material.prototype.unbind = function () {
  35708. this.onUnBindObservable.notifyObservers(this);
  35709. if (this.disableDepthWrite) {
  35710. var engine = this._scene.getEngine();
  35711. engine.setDepthWrite(this._cachedDepthWriteState);
  35712. }
  35713. };
  35714. /**
  35715. * Gets the active textures from the material
  35716. * @returns an array of textures
  35717. */
  35718. Material.prototype.getActiveTextures = function () {
  35719. return [];
  35720. };
  35721. /**
  35722. * Specifies if the material uses a texture
  35723. * @param texture defines the texture to check against the material
  35724. * @returns a boolean specifying if the material uses the texture
  35725. */
  35726. Material.prototype.hasTexture = function (texture) {
  35727. return false;
  35728. };
  35729. /**
  35730. * Makes a duplicate of the material, and gives it a new name
  35731. * @param name defines the new name for the duplicated material
  35732. * @returns the cloned material
  35733. */
  35734. Material.prototype.clone = function (name) {
  35735. return null;
  35736. };
  35737. /**
  35738. * Gets the meshes bound to the material
  35739. * @returns an array of meshes bound to the material
  35740. */
  35741. Material.prototype.getBindedMeshes = function () {
  35742. var result = new Array();
  35743. for (var index = 0; index < this._scene.meshes.length; index++) {
  35744. var mesh = this._scene.meshes[index];
  35745. if (mesh.material === this) {
  35746. result.push(mesh);
  35747. }
  35748. }
  35749. return result;
  35750. };
  35751. /**
  35752. * Force shader compilation
  35753. * @param mesh defines the mesh associated with this material
  35754. * @param onCompiled defines a function to execute once the material is compiled
  35755. * @param options defines the options to configure the compilation
  35756. */
  35757. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35758. var _this = this;
  35759. var localOptions = __assign({ clipPlane: false }, options);
  35760. var subMesh = new BABYLON.BaseSubMesh();
  35761. var scene = this.getScene();
  35762. var checkReady = function () {
  35763. if (!_this._scene || !_this._scene.getEngine()) {
  35764. return;
  35765. }
  35766. if (subMesh._materialDefines) {
  35767. subMesh._materialDefines._renderId = -1;
  35768. }
  35769. var clipPlaneState = scene.clipPlane;
  35770. if (localOptions.clipPlane) {
  35771. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35772. }
  35773. if (_this.storeEffectOnSubMeshes) {
  35774. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35775. if (onCompiled) {
  35776. onCompiled(_this);
  35777. }
  35778. }
  35779. else {
  35780. setTimeout(checkReady, 16);
  35781. }
  35782. }
  35783. else {
  35784. if (_this.isReady(mesh)) {
  35785. if (onCompiled) {
  35786. onCompiled(_this);
  35787. }
  35788. }
  35789. else {
  35790. setTimeout(checkReady, 16);
  35791. }
  35792. }
  35793. if (localOptions.clipPlane) {
  35794. scene.clipPlane = clipPlaneState;
  35795. }
  35796. };
  35797. checkReady();
  35798. };
  35799. /**
  35800. * Force shader compilation
  35801. * @param mesh defines the mesh that will use this material
  35802. * @param options defines additional options for compiling the shaders
  35803. * @returns a promise that resolves when the compilation completes
  35804. */
  35805. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35806. var _this = this;
  35807. return new Promise(function (resolve) {
  35808. _this.forceCompilation(mesh, function () {
  35809. resolve();
  35810. }, options);
  35811. });
  35812. };
  35813. /**
  35814. * Marks a define in the material to indicate that it needs to be re-computed
  35815. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35816. */
  35817. Material.prototype.markAsDirty = function (flag) {
  35818. if (flag & Material.TextureDirtyFlag) {
  35819. this._markAllSubMeshesAsTexturesDirty();
  35820. }
  35821. if (flag & Material.LightDirtyFlag) {
  35822. this._markAllSubMeshesAsLightsDirty();
  35823. }
  35824. if (flag & Material.FresnelDirtyFlag) {
  35825. this._markAllSubMeshesAsFresnelDirty();
  35826. }
  35827. if (flag & Material.AttributesDirtyFlag) {
  35828. this._markAllSubMeshesAsAttributesDirty();
  35829. }
  35830. if (flag & Material.MiscDirtyFlag) {
  35831. this._markAllSubMeshesAsMiscDirty();
  35832. }
  35833. this.getScene().resetCachedMaterial();
  35834. };
  35835. /**
  35836. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35837. * @param func defines a function which checks material defines against the submeshes
  35838. */
  35839. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35840. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35841. var mesh = _a[_i];
  35842. if (!mesh.subMeshes) {
  35843. continue;
  35844. }
  35845. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35846. var subMesh = _c[_b];
  35847. if (subMesh.getMaterial() !== this) {
  35848. continue;
  35849. }
  35850. if (!subMesh._materialDefines) {
  35851. continue;
  35852. }
  35853. func(subMesh._materialDefines);
  35854. }
  35855. }
  35856. };
  35857. /**
  35858. * Indicates that image processing needs to be re-calculated for all submeshes
  35859. */
  35860. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35861. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35862. };
  35863. /**
  35864. * Indicates that textures need to be re-calculated for all submeshes
  35865. */
  35866. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35867. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35868. };
  35869. /**
  35870. * Indicates that fresnel needs to be re-calculated for all submeshes
  35871. */
  35872. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35873. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35874. };
  35875. /**
  35876. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35877. */
  35878. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35879. this._markAllSubMeshesAsDirty(function (defines) {
  35880. defines.markAsFresnelDirty();
  35881. defines.markAsMiscDirty();
  35882. });
  35883. };
  35884. /**
  35885. * Indicates that lights need to be re-calculated for all submeshes
  35886. */
  35887. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35888. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35889. };
  35890. /**
  35891. * Indicates that attributes need to be re-calculated for all submeshes
  35892. */
  35893. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35894. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35895. };
  35896. /**
  35897. * Indicates that misc needs to be re-calculated for all submeshes
  35898. */
  35899. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35900. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35901. };
  35902. /**
  35903. * Indicates that textures and misc need to be re-calculated for all submeshes
  35904. */
  35905. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35906. this._markAllSubMeshesAsDirty(function (defines) {
  35907. defines.markAsTexturesDirty();
  35908. defines.markAsMiscDirty();
  35909. });
  35910. };
  35911. /**
  35912. * Disposes the material
  35913. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35914. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35915. */
  35916. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35917. // Animations
  35918. this.getScene().stopAnimation(this);
  35919. this.getScene().freeProcessedMaterials();
  35920. // Remove from scene
  35921. var index = this._scene.materials.indexOf(this);
  35922. if (index >= 0) {
  35923. this._scene.materials.splice(index, 1);
  35924. }
  35925. // Remove from meshes
  35926. for (index = 0; index < this._scene.meshes.length; index++) {
  35927. var mesh = this._scene.meshes[index];
  35928. if (mesh.material === this) {
  35929. mesh.material = null;
  35930. if (mesh.geometry) {
  35931. var geometry = (mesh.geometry);
  35932. if (this.storeEffectOnSubMeshes) {
  35933. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35934. var subMesh = _a[_i];
  35935. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35936. if (forceDisposeEffect && subMesh._materialEffect) {
  35937. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35938. }
  35939. }
  35940. }
  35941. else {
  35942. geometry._releaseVertexArrayObject(this._effect);
  35943. }
  35944. }
  35945. }
  35946. }
  35947. this._uniformBuffer.dispose();
  35948. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35949. if (forceDisposeEffect && this._effect) {
  35950. if (!this.storeEffectOnSubMeshes) {
  35951. this._scene.getEngine()._releaseEffect(this._effect);
  35952. }
  35953. this._effect = null;
  35954. }
  35955. // Callback
  35956. this.onDisposeObservable.notifyObservers(this);
  35957. this.onDisposeObservable.clear();
  35958. this.onBindObservable.clear();
  35959. this.onUnBindObservable.clear();
  35960. };
  35961. /**
  35962. * Serializes this material
  35963. * @returns the serialized material object
  35964. */
  35965. Material.prototype.serialize = function () {
  35966. return BABYLON.SerializationHelper.Serialize(this);
  35967. };
  35968. /**
  35969. * Creates a MultiMaterial from parsed MultiMaterial data.
  35970. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35971. * @param scene defines the hosting scene
  35972. * @returns a new MultiMaterial
  35973. */
  35974. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35975. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35976. multiMaterial.id = parsedMultiMaterial.id;
  35977. if (BABYLON.Tags) {
  35978. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35979. }
  35980. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35981. var subMatId = parsedMultiMaterial.materials[matIndex];
  35982. if (subMatId) {
  35983. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35984. }
  35985. else {
  35986. multiMaterial.subMaterials.push(null);
  35987. }
  35988. }
  35989. return multiMaterial;
  35990. };
  35991. /**
  35992. * Creates a material from parsed material data
  35993. * @param parsedMaterial defines parsed material data
  35994. * @param scene defines the hosting scene
  35995. * @param rootUrl defines the root URL to use to load textures
  35996. * @returns a new material
  35997. */
  35998. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35999. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36000. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36001. }
  36002. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36003. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36004. if (!BABYLON.LegacyPBRMaterial) {
  36005. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36006. return;
  36007. }
  36008. }
  36009. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36010. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36011. };
  36012. // Triangle views
  36013. Material._TriangleFillMode = 0;
  36014. Material._WireFrameFillMode = 1;
  36015. Material._PointFillMode = 2;
  36016. // Draw modes
  36017. Material._PointListDrawMode = 3;
  36018. Material._LineListDrawMode = 4;
  36019. Material._LineLoopDrawMode = 5;
  36020. Material._LineStripDrawMode = 6;
  36021. Material._TriangleStripDrawMode = 7;
  36022. Material._TriangleFanDrawMode = 8;
  36023. /**
  36024. * Stores the clock-wise side orientation
  36025. */
  36026. Material._ClockWiseSideOrientation = 0;
  36027. /**
  36028. * Stores the counter clock-wise side orientation
  36029. */
  36030. Material._CounterClockWiseSideOrientation = 1;
  36031. /**
  36032. * The dirty texture flag value
  36033. */
  36034. Material._TextureDirtyFlag = 1;
  36035. /**
  36036. * The dirty light flag value
  36037. */
  36038. Material._LightDirtyFlag = 2;
  36039. /**
  36040. * The dirty fresnel flag value
  36041. */
  36042. Material._FresnelDirtyFlag = 4;
  36043. /**
  36044. * The dirty attribute flag value
  36045. */
  36046. Material._AttributesDirtyFlag = 8;
  36047. /**
  36048. * The dirty misc flag value
  36049. */
  36050. Material._MiscDirtyFlag = 16;
  36051. __decorate([
  36052. BABYLON.serialize()
  36053. ], Material.prototype, "id", void 0);
  36054. __decorate([
  36055. BABYLON.serialize()
  36056. ], Material.prototype, "uniqueId", void 0);
  36057. __decorate([
  36058. BABYLON.serialize()
  36059. ], Material.prototype, "name", void 0);
  36060. __decorate([
  36061. BABYLON.serialize()
  36062. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36063. __decorate([
  36064. BABYLON.serialize()
  36065. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36066. __decorate([
  36067. BABYLON.serialize()
  36068. ], Material.prototype, "state", void 0);
  36069. __decorate([
  36070. BABYLON.serialize("alpha")
  36071. ], Material.prototype, "_alpha", void 0);
  36072. __decorate([
  36073. BABYLON.serialize("backFaceCulling")
  36074. ], Material.prototype, "_backFaceCulling", void 0);
  36075. __decorate([
  36076. BABYLON.serialize()
  36077. ], Material.prototype, "sideOrientation", void 0);
  36078. __decorate([
  36079. BABYLON.serialize("alphaMode")
  36080. ], Material.prototype, "_alphaMode", void 0);
  36081. __decorate([
  36082. BABYLON.serialize()
  36083. ], Material.prototype, "_needDepthPrePass", void 0);
  36084. __decorate([
  36085. BABYLON.serialize()
  36086. ], Material.prototype, "disableDepthWrite", void 0);
  36087. __decorate([
  36088. BABYLON.serialize()
  36089. ], Material.prototype, "forceDepthWrite", void 0);
  36090. __decorate([
  36091. BABYLON.serialize()
  36092. ], Material.prototype, "separateCullingPass", void 0);
  36093. __decorate([
  36094. BABYLON.serialize("fogEnabled")
  36095. ], Material.prototype, "_fogEnabled", void 0);
  36096. __decorate([
  36097. BABYLON.serialize()
  36098. ], Material.prototype, "pointSize", void 0);
  36099. __decorate([
  36100. BABYLON.serialize()
  36101. ], Material.prototype, "zOffset", void 0);
  36102. __decorate([
  36103. BABYLON.serialize()
  36104. ], Material.prototype, "wireframe", null);
  36105. __decorate([
  36106. BABYLON.serialize()
  36107. ], Material.prototype, "pointsCloud", null);
  36108. __decorate([
  36109. BABYLON.serialize()
  36110. ], Material.prototype, "fillMode", null);
  36111. return Material;
  36112. }());
  36113. BABYLON.Material = Material;
  36114. })(BABYLON || (BABYLON = {}));
  36115. //# sourceMappingURL=babylon.material.js.map
  36116. var BABYLON;
  36117. (function (BABYLON) {
  36118. var UniformBuffer = /** @class */ (function () {
  36119. /**
  36120. * Uniform buffer objects.
  36121. *
  36122. * Handles blocks of uniform on the GPU.
  36123. *
  36124. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36125. *
  36126. * For more information, please refer to :
  36127. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36128. */
  36129. function UniformBuffer(engine, data, dynamic) {
  36130. this._engine = engine;
  36131. this._noUBO = !engine.supportsUniformBuffers;
  36132. this._dynamic = dynamic;
  36133. this._data = data || [];
  36134. this._uniformLocations = {};
  36135. this._uniformSizes = {};
  36136. this._uniformLocationPointer = 0;
  36137. this._needSync = false;
  36138. if (this._noUBO) {
  36139. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36140. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36141. this.updateFloat = this._updateFloatForEffect;
  36142. this.updateFloat2 = this._updateFloat2ForEffect;
  36143. this.updateFloat3 = this._updateFloat3ForEffect;
  36144. this.updateFloat4 = this._updateFloat4ForEffect;
  36145. this.updateMatrix = this._updateMatrixForEffect;
  36146. this.updateVector3 = this._updateVector3ForEffect;
  36147. this.updateVector4 = this._updateVector4ForEffect;
  36148. this.updateColor3 = this._updateColor3ForEffect;
  36149. this.updateColor4 = this._updateColor4ForEffect;
  36150. }
  36151. else {
  36152. this._engine._uniformBuffers.push(this);
  36153. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36154. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36155. this.updateFloat = this._updateFloatForUniform;
  36156. this.updateFloat2 = this._updateFloat2ForUniform;
  36157. this.updateFloat3 = this._updateFloat3ForUniform;
  36158. this.updateFloat4 = this._updateFloat4ForUniform;
  36159. this.updateMatrix = this._updateMatrixForUniform;
  36160. this.updateVector3 = this._updateVector3ForUniform;
  36161. this.updateVector4 = this._updateVector4ForUniform;
  36162. this.updateColor3 = this._updateColor3ForUniform;
  36163. this.updateColor4 = this._updateColor4ForUniform;
  36164. }
  36165. }
  36166. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36167. // Properties
  36168. /**
  36169. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36170. * or just falling back on setUniformXXX calls.
  36171. */
  36172. get: function () {
  36173. return !this._noUBO;
  36174. },
  36175. enumerable: true,
  36176. configurable: true
  36177. });
  36178. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36179. /**
  36180. * Indicates if the WebGL underlying uniform buffer is in sync
  36181. * with the javascript cache data.
  36182. */
  36183. get: function () {
  36184. return !this._needSync;
  36185. },
  36186. enumerable: true,
  36187. configurable: true
  36188. });
  36189. /**
  36190. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36191. * Also, a dynamic UniformBuffer will disable cache verification and always
  36192. * update the underlying WebGL uniform buffer to the GPU.
  36193. */
  36194. UniformBuffer.prototype.isDynamic = function () {
  36195. return this._dynamic !== undefined;
  36196. };
  36197. /**
  36198. * The data cache on JS side.
  36199. */
  36200. UniformBuffer.prototype.getData = function () {
  36201. return this._bufferData;
  36202. };
  36203. /**
  36204. * The underlying WebGL Uniform buffer.
  36205. */
  36206. UniformBuffer.prototype.getBuffer = function () {
  36207. return this._buffer;
  36208. };
  36209. /**
  36210. * std140 layout specifies how to align data within an UBO structure.
  36211. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36212. * for specs.
  36213. */
  36214. UniformBuffer.prototype._fillAlignment = function (size) {
  36215. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36216. // and 4x4 matrices
  36217. // TODO : change if other types are used
  36218. var alignment;
  36219. if (size <= 2) {
  36220. alignment = size;
  36221. }
  36222. else {
  36223. alignment = 4;
  36224. }
  36225. if ((this._uniformLocationPointer % alignment) !== 0) {
  36226. var oldPointer = this._uniformLocationPointer;
  36227. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36228. var diff = this._uniformLocationPointer - oldPointer;
  36229. for (var i = 0; i < diff; i++) {
  36230. this._data.push(0);
  36231. }
  36232. }
  36233. };
  36234. /**
  36235. * Adds an uniform in the buffer.
  36236. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36237. * for the layout to be correct !
  36238. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36239. * @param {number|number[]} size Data size, or data directly.
  36240. */
  36241. UniformBuffer.prototype.addUniform = function (name, size) {
  36242. if (this._noUBO) {
  36243. return;
  36244. }
  36245. if (this._uniformLocations[name] !== undefined) {
  36246. // Already existing uniform
  36247. return;
  36248. }
  36249. // This function must be called in the order of the shader layout !
  36250. // size can be the size of the uniform, or data directly
  36251. var data;
  36252. if (size instanceof Array) {
  36253. data = size;
  36254. size = data.length;
  36255. }
  36256. else {
  36257. size = size;
  36258. data = [];
  36259. // Fill with zeros
  36260. for (var i = 0; i < size; i++) {
  36261. data.push(0);
  36262. }
  36263. }
  36264. this._fillAlignment(size);
  36265. this._uniformSizes[name] = size;
  36266. this._uniformLocations[name] = this._uniformLocationPointer;
  36267. this._uniformLocationPointer += size;
  36268. for (var i = 0; i < size; i++) {
  36269. this._data.push(data[i]);
  36270. }
  36271. this._needSync = true;
  36272. };
  36273. /**
  36274. * Wrapper for addUniform.
  36275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36276. * @param {Matrix} mat A 4x4 matrix.
  36277. */
  36278. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36279. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36280. };
  36281. /**
  36282. * Wrapper for addUniform.
  36283. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36284. * @param {number} x
  36285. * @param {number} y
  36286. */
  36287. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36288. var temp = [x, y];
  36289. this.addUniform(name, temp);
  36290. };
  36291. /**
  36292. * Wrapper for addUniform.
  36293. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36294. * @param {number} x
  36295. * @param {number} y
  36296. * @param {number} z
  36297. */
  36298. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36299. var temp = [x, y, z];
  36300. this.addUniform(name, temp);
  36301. };
  36302. /**
  36303. * Wrapper for addUniform.
  36304. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36305. * @param {Color3} color
  36306. */
  36307. UniformBuffer.prototype.addColor3 = function (name, color) {
  36308. var temp = new Array();
  36309. color.toArray(temp);
  36310. this.addUniform(name, temp);
  36311. };
  36312. /**
  36313. * Wrapper for addUniform.
  36314. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36315. * @param {Color3} color
  36316. * @param {number} alpha
  36317. */
  36318. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36319. var temp = new Array();
  36320. color.toArray(temp);
  36321. temp.push(alpha);
  36322. this.addUniform(name, temp);
  36323. };
  36324. /**
  36325. * Wrapper for addUniform.
  36326. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36327. * @param {Vector3} vector
  36328. */
  36329. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36330. var temp = new Array();
  36331. vector.toArray(temp);
  36332. this.addUniform(name, temp);
  36333. };
  36334. /**
  36335. * Wrapper for addUniform.
  36336. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36337. */
  36338. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36339. this.addUniform(name, 12);
  36340. };
  36341. /**
  36342. * Wrapper for addUniform.
  36343. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36344. */
  36345. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36346. this.addUniform(name, 8);
  36347. };
  36348. /**
  36349. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36350. */
  36351. UniformBuffer.prototype.create = function () {
  36352. if (this._noUBO) {
  36353. return;
  36354. }
  36355. if (this._buffer) {
  36356. return; // nothing to do
  36357. }
  36358. // See spec, alignment must be filled as a vec4
  36359. this._fillAlignment(4);
  36360. this._bufferData = new Float32Array(this._data);
  36361. this._rebuild();
  36362. this._needSync = true;
  36363. };
  36364. UniformBuffer.prototype._rebuild = function () {
  36365. if (this._noUBO) {
  36366. return;
  36367. }
  36368. if (this._dynamic) {
  36369. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36370. }
  36371. else {
  36372. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36373. }
  36374. };
  36375. /**
  36376. * Updates the WebGL Uniform Buffer on the GPU.
  36377. * If the `dynamic` flag is set to true, no cache comparison is done.
  36378. * Otherwise, the buffer will be updated only if the cache differs.
  36379. */
  36380. UniformBuffer.prototype.update = function () {
  36381. if (!this._buffer) {
  36382. this.create();
  36383. return;
  36384. }
  36385. if (!this._dynamic && !this._needSync) {
  36386. return;
  36387. }
  36388. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36389. this._needSync = false;
  36390. };
  36391. /**
  36392. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36393. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36394. * @param {number[]|Float32Array} data Flattened data
  36395. * @param {number} size Size of the data.
  36396. */
  36397. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36398. var location = this._uniformLocations[uniformName];
  36399. if (location === undefined) {
  36400. if (this._buffer) {
  36401. // Cannot add an uniform if the buffer is already created
  36402. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36403. return;
  36404. }
  36405. this.addUniform(uniformName, size);
  36406. location = this._uniformLocations[uniformName];
  36407. }
  36408. if (!this._buffer) {
  36409. this.create();
  36410. }
  36411. if (!this._dynamic) {
  36412. // Cache for static uniform buffers
  36413. var changed = false;
  36414. for (var i = 0; i < size; i++) {
  36415. if (this._bufferData[location + i] !== data[i]) {
  36416. changed = true;
  36417. this._bufferData[location + i] = data[i];
  36418. }
  36419. }
  36420. this._needSync = this._needSync || changed;
  36421. }
  36422. else {
  36423. // No cache for dynamic
  36424. for (var i = 0; i < size; i++) {
  36425. this._bufferData[location + i] = data[i];
  36426. }
  36427. }
  36428. };
  36429. // Update methods
  36430. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36431. // To match std140, matrix must be realigned
  36432. for (var i = 0; i < 3; i++) {
  36433. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36434. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36435. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36436. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36437. }
  36438. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36439. };
  36440. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36441. this._currentEffect.setMatrix3x3(name, matrix);
  36442. };
  36443. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36444. this._currentEffect.setMatrix2x2(name, matrix);
  36445. };
  36446. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36447. // To match std140, matrix must be realigned
  36448. for (var i = 0; i < 2; i++) {
  36449. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36450. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36451. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36452. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36453. }
  36454. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36455. };
  36456. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36457. this._currentEffect.setFloat(name, x);
  36458. };
  36459. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36460. UniformBuffer._tempBuffer[0] = x;
  36461. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36462. };
  36463. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36464. if (suffix === void 0) { suffix = ""; }
  36465. this._currentEffect.setFloat2(name + suffix, x, y);
  36466. };
  36467. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36468. if (suffix === void 0) { suffix = ""; }
  36469. UniformBuffer._tempBuffer[0] = x;
  36470. UniformBuffer._tempBuffer[1] = y;
  36471. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36472. };
  36473. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36474. if (suffix === void 0) { suffix = ""; }
  36475. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36476. };
  36477. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36478. if (suffix === void 0) { suffix = ""; }
  36479. UniformBuffer._tempBuffer[0] = x;
  36480. UniformBuffer._tempBuffer[1] = y;
  36481. UniformBuffer._tempBuffer[2] = z;
  36482. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36483. };
  36484. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36485. if (suffix === void 0) { suffix = ""; }
  36486. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36487. };
  36488. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36489. if (suffix === void 0) { suffix = ""; }
  36490. UniformBuffer._tempBuffer[0] = x;
  36491. UniformBuffer._tempBuffer[1] = y;
  36492. UniformBuffer._tempBuffer[2] = z;
  36493. UniformBuffer._tempBuffer[3] = w;
  36494. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36495. };
  36496. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36497. this._currentEffect.setMatrix(name, mat);
  36498. };
  36499. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36500. this.updateUniform(name, mat.toArray(), 16);
  36501. };
  36502. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36503. this._currentEffect.setVector3(name, vector);
  36504. };
  36505. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36506. vector.toArray(UniformBuffer._tempBuffer);
  36507. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36508. };
  36509. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36510. this._currentEffect.setVector4(name, vector);
  36511. };
  36512. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36513. vector.toArray(UniformBuffer._tempBuffer);
  36514. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36515. };
  36516. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36517. if (suffix === void 0) { suffix = ""; }
  36518. this._currentEffect.setColor3(name + suffix, color);
  36519. };
  36520. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36521. if (suffix === void 0) { suffix = ""; }
  36522. color.toArray(UniformBuffer._tempBuffer);
  36523. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36524. };
  36525. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36526. if (suffix === void 0) { suffix = ""; }
  36527. this._currentEffect.setColor4(name + suffix, color, alpha);
  36528. };
  36529. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36530. if (suffix === void 0) { suffix = ""; }
  36531. color.toArray(UniformBuffer._tempBuffer);
  36532. UniformBuffer._tempBuffer[3] = alpha;
  36533. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36534. };
  36535. /**
  36536. * Sets a sampler uniform on the effect.
  36537. * @param {string} name Name of the sampler.
  36538. * @param {Texture} texture
  36539. */
  36540. UniformBuffer.prototype.setTexture = function (name, texture) {
  36541. this._currentEffect.setTexture(name, texture);
  36542. };
  36543. /**
  36544. * Directly updates the value of the uniform in the cache AND on the GPU.
  36545. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36546. * @param {number[]|Float32Array} data Flattened data
  36547. */
  36548. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36549. this.updateUniform(uniformName, data, data.length);
  36550. this.update();
  36551. };
  36552. /**
  36553. * Binds this uniform buffer to an effect.
  36554. * @param {Effect} effect
  36555. * @param {string} name Name of the uniform block in the shader.
  36556. */
  36557. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36558. this._currentEffect = effect;
  36559. if (this._noUBO || !this._buffer) {
  36560. return;
  36561. }
  36562. effect.bindUniformBuffer(this._buffer, name);
  36563. };
  36564. /**
  36565. * Disposes the uniform buffer.
  36566. */
  36567. UniformBuffer.prototype.dispose = function () {
  36568. if (this._noUBO) {
  36569. return;
  36570. }
  36571. var index = this._engine._uniformBuffers.indexOf(this);
  36572. if (index !== -1) {
  36573. this._engine._uniformBuffers.splice(index, 1);
  36574. }
  36575. if (!this._buffer) {
  36576. return;
  36577. }
  36578. if (this._engine._releaseBuffer(this._buffer)) {
  36579. this._buffer = null;
  36580. }
  36581. };
  36582. // Pool for avoiding memory leaks
  36583. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36584. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36585. return UniformBuffer;
  36586. }());
  36587. BABYLON.UniformBuffer = UniformBuffer;
  36588. })(BABYLON || (BABYLON = {}));
  36589. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36590. var BABYLON;
  36591. (function (BABYLON) {
  36592. /**
  36593. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36594. */
  36595. var VertexData = /** @class */ (function () {
  36596. function VertexData() {
  36597. }
  36598. /**
  36599. * Uses the passed data array to set the set the values for the specified kind of data
  36600. * @param data a linear array of floating numbers
  36601. * @param kind the type of data that is being set, eg positions, colors etc
  36602. */
  36603. VertexData.prototype.set = function (data, kind) {
  36604. switch (kind) {
  36605. case BABYLON.VertexBuffer.PositionKind:
  36606. this.positions = data;
  36607. break;
  36608. case BABYLON.VertexBuffer.NormalKind:
  36609. this.normals = data;
  36610. break;
  36611. case BABYLON.VertexBuffer.TangentKind:
  36612. this.tangents = data;
  36613. break;
  36614. case BABYLON.VertexBuffer.UVKind:
  36615. this.uvs = data;
  36616. break;
  36617. case BABYLON.VertexBuffer.UV2Kind:
  36618. this.uvs2 = data;
  36619. break;
  36620. case BABYLON.VertexBuffer.UV3Kind:
  36621. this.uvs3 = data;
  36622. break;
  36623. case BABYLON.VertexBuffer.UV4Kind:
  36624. this.uvs4 = data;
  36625. break;
  36626. case BABYLON.VertexBuffer.UV5Kind:
  36627. this.uvs5 = data;
  36628. break;
  36629. case BABYLON.VertexBuffer.UV6Kind:
  36630. this.uvs6 = data;
  36631. break;
  36632. case BABYLON.VertexBuffer.ColorKind:
  36633. this.colors = data;
  36634. break;
  36635. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36636. this.matricesIndices = data;
  36637. break;
  36638. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36639. this.matricesWeights = data;
  36640. break;
  36641. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36642. this.matricesIndicesExtra = data;
  36643. break;
  36644. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36645. this.matricesWeightsExtra = data;
  36646. break;
  36647. }
  36648. };
  36649. /**
  36650. * Associates the vertexData to the passed Mesh.
  36651. * Sets it as updatable or not (default `false`)
  36652. * @param mesh the mesh the vertexData is applied to
  36653. * @param updatable when used and having the value true allows new data to update the vertexData
  36654. * @returns the VertexData
  36655. */
  36656. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36657. this._applyTo(mesh, updatable);
  36658. return this;
  36659. };
  36660. /**
  36661. * Associates the vertexData to the passed Geometry.
  36662. * Sets it as updatable or not (default `false`)
  36663. * @param geometry the geometry the vertexData is applied to
  36664. * @param updatable when used and having the value true allows new data to update the vertexData
  36665. * @returns VertexData
  36666. */
  36667. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36668. this._applyTo(geometry, updatable);
  36669. return this;
  36670. };
  36671. /**
  36672. * Updates the associated mesh
  36673. * @param mesh the mesh to be updated
  36674. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36675. * @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
  36676. * @returns VertexData
  36677. */
  36678. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36679. this._update(mesh);
  36680. return this;
  36681. };
  36682. /**
  36683. * Updates the associated geometry
  36684. * @param geometry the geometry to be updated
  36685. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36686. * @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
  36687. * @returns VertexData.
  36688. */
  36689. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36690. this._update(geometry);
  36691. return this;
  36692. };
  36693. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36694. if (updatable === void 0) { updatable = false; }
  36695. if (this.positions) {
  36696. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36697. }
  36698. if (this.normals) {
  36699. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36700. }
  36701. if (this.tangents) {
  36702. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36703. }
  36704. if (this.uvs) {
  36705. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36706. }
  36707. if (this.uvs2) {
  36708. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36709. }
  36710. if (this.uvs3) {
  36711. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36712. }
  36713. if (this.uvs4) {
  36714. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36715. }
  36716. if (this.uvs5) {
  36717. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36718. }
  36719. if (this.uvs6) {
  36720. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36721. }
  36722. if (this.colors) {
  36723. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36724. }
  36725. if (this.matricesIndices) {
  36726. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36727. }
  36728. if (this.matricesWeights) {
  36729. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36730. }
  36731. if (this.matricesIndicesExtra) {
  36732. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36733. }
  36734. if (this.matricesWeightsExtra) {
  36735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36736. }
  36737. if (this.indices) {
  36738. meshOrGeometry.setIndices(this.indices, null, updatable);
  36739. }
  36740. else {
  36741. meshOrGeometry.setIndices([], null);
  36742. }
  36743. return this;
  36744. };
  36745. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36746. if (this.positions) {
  36747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36748. }
  36749. if (this.normals) {
  36750. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36751. }
  36752. if (this.tangents) {
  36753. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36754. }
  36755. if (this.uvs) {
  36756. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36757. }
  36758. if (this.uvs2) {
  36759. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36760. }
  36761. if (this.uvs3) {
  36762. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36763. }
  36764. if (this.uvs4) {
  36765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36766. }
  36767. if (this.uvs5) {
  36768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36769. }
  36770. if (this.uvs6) {
  36771. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36772. }
  36773. if (this.colors) {
  36774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36775. }
  36776. if (this.matricesIndices) {
  36777. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36778. }
  36779. if (this.matricesWeights) {
  36780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36781. }
  36782. if (this.matricesIndicesExtra) {
  36783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36784. }
  36785. if (this.matricesWeightsExtra) {
  36786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36787. }
  36788. if (this.indices) {
  36789. meshOrGeometry.setIndices(this.indices, null);
  36790. }
  36791. return this;
  36792. };
  36793. /**
  36794. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36795. * @param matrix the transforming matrix
  36796. * @returns the VertexData
  36797. */
  36798. VertexData.prototype.transform = function (matrix) {
  36799. var transformed = BABYLON.Vector3.Zero();
  36800. var index;
  36801. if (this.positions) {
  36802. var position = BABYLON.Vector3.Zero();
  36803. for (index = 0; index < this.positions.length; index += 3) {
  36804. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36805. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36806. this.positions[index] = transformed.x;
  36807. this.positions[index + 1] = transformed.y;
  36808. this.positions[index + 2] = transformed.z;
  36809. }
  36810. }
  36811. if (this.normals) {
  36812. var normal = BABYLON.Vector3.Zero();
  36813. for (index = 0; index < this.normals.length; index += 3) {
  36814. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36815. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36816. this.normals[index] = transformed.x;
  36817. this.normals[index + 1] = transformed.y;
  36818. this.normals[index + 2] = transformed.z;
  36819. }
  36820. }
  36821. if (this.tangents) {
  36822. var tangent = BABYLON.Vector4.Zero();
  36823. var tangentTransformed = BABYLON.Vector4.Zero();
  36824. for (index = 0; index < this.tangents.length; index += 4) {
  36825. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36826. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36827. this.tangents[index] = tangentTransformed.x;
  36828. this.tangents[index + 1] = tangentTransformed.y;
  36829. this.tangents[index + 2] = tangentTransformed.z;
  36830. this.tangents[index + 3] = tangentTransformed.w;
  36831. }
  36832. }
  36833. return this;
  36834. };
  36835. /**
  36836. * Merges the passed VertexData into the current one
  36837. * @param other the VertexData to be merged into the current one
  36838. * @returns the modified VertexData
  36839. */
  36840. VertexData.prototype.merge = function (other) {
  36841. this._validate();
  36842. other._validate();
  36843. if (!this.normals !== !other.normals ||
  36844. !this.tangents !== !other.tangents ||
  36845. !this.uvs !== !other.uvs ||
  36846. !this.uvs2 !== !other.uvs2 ||
  36847. !this.uvs3 !== !other.uvs3 ||
  36848. !this.uvs4 !== !other.uvs4 ||
  36849. !this.uvs5 !== !other.uvs5 ||
  36850. !this.uvs6 !== !other.uvs6 ||
  36851. !this.colors !== !other.colors ||
  36852. !this.matricesIndices !== !other.matricesIndices ||
  36853. !this.matricesWeights !== !other.matricesWeights ||
  36854. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36855. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36856. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36857. }
  36858. if (other.indices) {
  36859. if (!this.indices) {
  36860. this.indices = [];
  36861. }
  36862. var offset = this.positions ? this.positions.length / 3 : 0;
  36863. for (var index = 0; index < other.indices.length; index++) {
  36864. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36865. this.indices.push(other.indices[index] + offset);
  36866. }
  36867. }
  36868. this.positions = this._mergeElement(this.positions, other.positions);
  36869. this.normals = this._mergeElement(this.normals, other.normals);
  36870. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36871. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36872. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36873. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36874. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36875. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36876. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36877. this.colors = this._mergeElement(this.colors, other.colors);
  36878. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36879. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36880. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36881. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36882. return this;
  36883. };
  36884. VertexData.prototype._mergeElement = function (source, other) {
  36885. if (!source) {
  36886. return other;
  36887. }
  36888. if (!other) {
  36889. return source;
  36890. }
  36891. var len = other.length + source.length;
  36892. var isSrcTypedArray = source instanceof Float32Array;
  36893. var isOthTypedArray = other instanceof Float32Array;
  36894. // use non-loop method when the source is Float32Array
  36895. if (isSrcTypedArray) {
  36896. var ret32 = new Float32Array(len);
  36897. ret32.set(source);
  36898. ret32.set(other, source.length);
  36899. return ret32;
  36900. // source is number[], when other is also use concat
  36901. }
  36902. else if (!isOthTypedArray) {
  36903. return source.concat(other);
  36904. // source is a number[], but other is a Float32Array, loop required
  36905. }
  36906. else {
  36907. var ret = source.slice(0); // copy source to a separate array
  36908. for (var i = 0, len = other.length; i < len; i++) {
  36909. ret.push(other[i]);
  36910. }
  36911. return ret;
  36912. }
  36913. };
  36914. VertexData.prototype._validate = function () {
  36915. if (!this.positions) {
  36916. throw new Error("Positions are required");
  36917. }
  36918. var getElementCount = function (kind, values) {
  36919. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36920. if ((values.length % stride) !== 0) {
  36921. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36922. }
  36923. return values.length / stride;
  36924. };
  36925. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36926. var validateElementCount = function (kind, values) {
  36927. var elementCount = getElementCount(kind, values);
  36928. if (elementCount !== positionsElementCount) {
  36929. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36930. }
  36931. };
  36932. if (this.normals)
  36933. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36934. if (this.tangents)
  36935. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36936. if (this.uvs)
  36937. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36938. if (this.uvs2)
  36939. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36940. if (this.uvs3)
  36941. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36942. if (this.uvs4)
  36943. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36944. if (this.uvs5)
  36945. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36946. if (this.uvs6)
  36947. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36948. if (this.colors)
  36949. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36950. if (this.matricesIndices)
  36951. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36952. if (this.matricesWeights)
  36953. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36954. if (this.matricesIndicesExtra)
  36955. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36956. if (this.matricesWeightsExtra)
  36957. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36958. };
  36959. /**
  36960. * Serializes the VertexData
  36961. * @returns a serialized object
  36962. */
  36963. VertexData.prototype.serialize = function () {
  36964. var serializationObject = this.serialize();
  36965. if (this.positions) {
  36966. serializationObject.positions = this.positions;
  36967. }
  36968. if (this.normals) {
  36969. serializationObject.normals = this.normals;
  36970. }
  36971. if (this.tangents) {
  36972. serializationObject.tangents = this.tangents;
  36973. }
  36974. if (this.uvs) {
  36975. serializationObject.uvs = this.uvs;
  36976. }
  36977. if (this.uvs2) {
  36978. serializationObject.uvs2 = this.uvs2;
  36979. }
  36980. if (this.uvs3) {
  36981. serializationObject.uvs3 = this.uvs3;
  36982. }
  36983. if (this.uvs4) {
  36984. serializationObject.uvs4 = this.uvs4;
  36985. }
  36986. if (this.uvs5) {
  36987. serializationObject.uvs5 = this.uvs5;
  36988. }
  36989. if (this.uvs6) {
  36990. serializationObject.uvs6 = this.uvs6;
  36991. }
  36992. if (this.colors) {
  36993. serializationObject.colors = this.colors;
  36994. }
  36995. if (this.matricesIndices) {
  36996. serializationObject.matricesIndices = this.matricesIndices;
  36997. serializationObject.matricesIndices._isExpanded = true;
  36998. }
  36999. if (this.matricesWeights) {
  37000. serializationObject.matricesWeights = this.matricesWeights;
  37001. }
  37002. if (this.matricesIndicesExtra) {
  37003. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37004. serializationObject.matricesIndicesExtra._isExpanded = true;
  37005. }
  37006. if (this.matricesWeightsExtra) {
  37007. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37008. }
  37009. serializationObject.indices = this.indices;
  37010. return serializationObject;
  37011. };
  37012. // Statics
  37013. /**
  37014. * Extracts the vertexData from a mesh
  37015. * @param mesh the mesh from which to extract the VertexData
  37016. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37017. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37018. * @returns the object VertexData associated to the passed mesh
  37019. */
  37020. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37021. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37022. };
  37023. /**
  37024. * Extracts the vertexData from the geometry
  37025. * @param geometry the geometry from which to extract the VertexData
  37026. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37027. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37028. * @returns the object VertexData associated to the passed mesh
  37029. */
  37030. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37031. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37032. };
  37033. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37034. var result = new VertexData();
  37035. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37036. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37037. }
  37038. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37039. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37040. }
  37041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37042. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37043. }
  37044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37045. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37046. }
  37047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37048. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37049. }
  37050. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37051. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37052. }
  37053. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37054. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37055. }
  37056. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37057. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37058. }
  37059. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37060. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37061. }
  37062. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37063. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37064. }
  37065. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37066. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37067. }
  37068. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37069. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37070. }
  37071. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37072. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37073. }
  37074. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37075. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37076. }
  37077. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37078. return result;
  37079. };
  37080. /**
  37081. * Creates the VertexData for a Ribbon
  37082. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37083. * * pathArray array of paths, each of which an array of successive Vector3
  37084. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37085. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37086. * * 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
  37087. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37088. * * 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)
  37089. * * 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)
  37090. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37091. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37092. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37093. * @returns the VertexData of the ribbon
  37094. */
  37095. VertexData.CreateRibbon = function (options) {
  37096. var pathArray = options.pathArray;
  37097. var closeArray = options.closeArray || false;
  37098. var closePath = options.closePath || false;
  37099. var invertUV = options.invertUV || false;
  37100. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37101. var offset = options.offset || defaultOffset;
  37102. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37103. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37104. var customUV = options.uvs;
  37105. var customColors = options.colors;
  37106. var positions = [];
  37107. var indices = [];
  37108. var normals = [];
  37109. var uvs = [];
  37110. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37111. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37112. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37113. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37114. var minlg; // minimal length among all paths from pathArray
  37115. var lg = []; // array of path lengths : nb of vertex per path
  37116. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37117. var p; // path iterator
  37118. var i; // point iterator
  37119. var j; // point iterator
  37120. // if single path in pathArray
  37121. if (pathArray.length < 2) {
  37122. var ar1 = [];
  37123. var ar2 = [];
  37124. for (i = 0; i < pathArray[0].length - offset; i++) {
  37125. ar1.push(pathArray[0][i]);
  37126. ar2.push(pathArray[0][i + offset]);
  37127. }
  37128. pathArray = [ar1, ar2];
  37129. }
  37130. // positions and horizontal distances (u)
  37131. var idc = 0;
  37132. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37133. var path;
  37134. var l;
  37135. minlg = pathArray[0].length;
  37136. var vectlg;
  37137. var dist;
  37138. for (p = 0; p < pathArray.length; p++) {
  37139. uTotalDistance[p] = 0;
  37140. us[p] = [0];
  37141. path = pathArray[p];
  37142. l = path.length;
  37143. minlg = (minlg < l) ? minlg : l;
  37144. j = 0;
  37145. while (j < l) {
  37146. positions.push(path[j].x, path[j].y, path[j].z);
  37147. if (j > 0) {
  37148. vectlg = path[j].subtract(path[j - 1]).length();
  37149. dist = vectlg + uTotalDistance[p];
  37150. us[p].push(dist);
  37151. uTotalDistance[p] = dist;
  37152. }
  37153. j++;
  37154. }
  37155. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37156. j--;
  37157. positions.push(path[0].x, path[0].y, path[0].z);
  37158. vectlg = path[j].subtract(path[0]).length();
  37159. dist = vectlg + uTotalDistance[p];
  37160. us[p].push(dist);
  37161. uTotalDistance[p] = dist;
  37162. }
  37163. lg[p] = l + closePathCorr;
  37164. idx[p] = idc;
  37165. idc += (l + closePathCorr);
  37166. }
  37167. // vertical distances (v)
  37168. var path1;
  37169. var path2;
  37170. var vertex1 = null;
  37171. var vertex2 = null;
  37172. for (i = 0; i < minlg + closePathCorr; i++) {
  37173. vTotalDistance[i] = 0;
  37174. vs[i] = [0];
  37175. for (p = 0; p < pathArray.length - 1; p++) {
  37176. path1 = pathArray[p];
  37177. path2 = pathArray[p + 1];
  37178. if (i === minlg) { // closePath
  37179. vertex1 = path1[0];
  37180. vertex2 = path2[0];
  37181. }
  37182. else {
  37183. vertex1 = path1[i];
  37184. vertex2 = path2[i];
  37185. }
  37186. vectlg = vertex2.subtract(vertex1).length();
  37187. dist = vectlg + vTotalDistance[i];
  37188. vs[i].push(dist);
  37189. vTotalDistance[i] = dist;
  37190. }
  37191. if (closeArray && vertex2 && vertex1) {
  37192. path1 = pathArray[p];
  37193. path2 = pathArray[0];
  37194. if (i === minlg) { // closePath
  37195. vertex2 = path2[0];
  37196. }
  37197. vectlg = vertex2.subtract(vertex1).length();
  37198. dist = vectlg + vTotalDistance[i];
  37199. vTotalDistance[i] = dist;
  37200. }
  37201. }
  37202. // uvs
  37203. var u;
  37204. var v;
  37205. if (customUV) {
  37206. for (p = 0; p < customUV.length; p++) {
  37207. uvs.push(customUV[p].x, customUV[p].y);
  37208. }
  37209. }
  37210. else {
  37211. for (p = 0; p < pathArray.length; p++) {
  37212. for (i = 0; i < minlg + closePathCorr; i++) {
  37213. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37214. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37215. if (invertUV) {
  37216. uvs.push(v, u);
  37217. }
  37218. else {
  37219. uvs.push(u, v);
  37220. }
  37221. }
  37222. }
  37223. }
  37224. // indices
  37225. p = 0; // path index
  37226. var pi = 0; // positions array index
  37227. var l1 = lg[p] - 1; // path1 length
  37228. var l2 = lg[p + 1] - 1; // path2 length
  37229. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37230. var shft = idx[1] - idx[0]; // shift
  37231. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37232. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37233. // 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
  37234. indices.push(pi, pi + shft, pi + 1);
  37235. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37236. pi += 1;
  37237. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37238. p++;
  37239. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37240. shft = idx[0] - idx[p];
  37241. l1 = lg[p] - 1;
  37242. l2 = lg[0] - 1;
  37243. }
  37244. else {
  37245. shft = idx[p + 1] - idx[p];
  37246. l1 = lg[p] - 1;
  37247. l2 = lg[p + 1] - 1;
  37248. }
  37249. pi = idx[p];
  37250. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37251. }
  37252. }
  37253. // normals
  37254. VertexData.ComputeNormals(positions, indices, normals);
  37255. if (closePath) { // update both the first and last vertex normals to their average value
  37256. var indexFirst = 0;
  37257. var indexLast = 0;
  37258. for (p = 0; p < pathArray.length; p++) {
  37259. indexFirst = idx[p] * 3;
  37260. if (p + 1 < pathArray.length) {
  37261. indexLast = (idx[p + 1] - 1) * 3;
  37262. }
  37263. else {
  37264. indexLast = normals.length - 3;
  37265. }
  37266. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37267. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37268. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37269. normals[indexLast] = normals[indexFirst];
  37270. normals[indexLast + 1] = normals[indexFirst + 1];
  37271. normals[indexLast + 2] = normals[indexFirst + 2];
  37272. }
  37273. }
  37274. // sides
  37275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37276. // Colors
  37277. var colors = null;
  37278. if (customColors) {
  37279. colors = new Float32Array(customColors.length * 4);
  37280. for (var c = 0; c < customColors.length; c++) {
  37281. colors[c * 4] = customColors[c].r;
  37282. colors[c * 4 + 1] = customColors[c].g;
  37283. colors[c * 4 + 2] = customColors[c].b;
  37284. colors[c * 4 + 3] = customColors[c].a;
  37285. }
  37286. }
  37287. // Result
  37288. var vertexData = new VertexData();
  37289. var positions32 = new Float32Array(positions);
  37290. var normals32 = new Float32Array(normals);
  37291. var uvs32 = new Float32Array(uvs);
  37292. vertexData.indices = indices;
  37293. vertexData.positions = positions32;
  37294. vertexData.normals = normals32;
  37295. vertexData.uvs = uvs32;
  37296. if (colors) {
  37297. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37298. }
  37299. if (closePath) {
  37300. vertexData._idx = idx;
  37301. }
  37302. return vertexData;
  37303. };
  37304. /**
  37305. * Creates the VertexData for a box
  37306. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37307. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37308. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37309. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37310. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37311. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37312. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37313. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37314. * * 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)
  37315. * * 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)
  37316. * @returns the VertexData of the box
  37317. */
  37318. VertexData.CreateBox = function (options) {
  37319. var normalsSource = [
  37320. new BABYLON.Vector3(0, 0, 1),
  37321. new BABYLON.Vector3(0, 0, -1),
  37322. new BABYLON.Vector3(1, 0, 0),
  37323. new BABYLON.Vector3(-1, 0, 0),
  37324. new BABYLON.Vector3(0, 1, 0),
  37325. new BABYLON.Vector3(0, -1, 0)
  37326. ];
  37327. var indices = [];
  37328. var positions = [];
  37329. var normals = [];
  37330. var uvs = [];
  37331. var width = options.width || options.size || 1;
  37332. var height = options.height || options.size || 1;
  37333. var depth = options.depth || options.size || 1;
  37334. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37335. var faceUV = options.faceUV || new Array(6);
  37336. var faceColors = options.faceColors;
  37337. var colors = [];
  37338. // default face colors and UV if undefined
  37339. for (var f = 0; f < 6; f++) {
  37340. if (faceUV[f] === undefined) {
  37341. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37342. }
  37343. if (faceColors && faceColors[f] === undefined) {
  37344. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37345. }
  37346. }
  37347. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37348. // Create each face in turn.
  37349. for (var index = 0; index < normalsSource.length; index++) {
  37350. var normal = normalsSource[index];
  37351. // Get two vectors perpendicular to the face normal and to each other.
  37352. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37353. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37354. // Six indices (two triangles) per face.
  37355. var verticesLength = positions.length / 3;
  37356. indices.push(verticesLength);
  37357. indices.push(verticesLength + 1);
  37358. indices.push(verticesLength + 2);
  37359. indices.push(verticesLength);
  37360. indices.push(verticesLength + 2);
  37361. indices.push(verticesLength + 3);
  37362. // Four vertices per face.
  37363. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37364. positions.push(vertex.x, vertex.y, vertex.z);
  37365. normals.push(normal.x, normal.y, normal.z);
  37366. uvs.push(faceUV[index].z, faceUV[index].w);
  37367. if (faceColors) {
  37368. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37369. }
  37370. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37371. positions.push(vertex.x, vertex.y, vertex.z);
  37372. normals.push(normal.x, normal.y, normal.z);
  37373. uvs.push(faceUV[index].x, faceUV[index].w);
  37374. if (faceColors) {
  37375. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37376. }
  37377. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37378. positions.push(vertex.x, vertex.y, vertex.z);
  37379. normals.push(normal.x, normal.y, normal.z);
  37380. uvs.push(faceUV[index].x, faceUV[index].y);
  37381. if (faceColors) {
  37382. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37383. }
  37384. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37385. positions.push(vertex.x, vertex.y, vertex.z);
  37386. normals.push(normal.x, normal.y, normal.z);
  37387. uvs.push(faceUV[index].z, faceUV[index].y);
  37388. if (faceColors) {
  37389. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37390. }
  37391. }
  37392. // sides
  37393. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37394. // Result
  37395. var vertexData = new VertexData();
  37396. vertexData.indices = indices;
  37397. vertexData.positions = positions;
  37398. vertexData.normals = normals;
  37399. vertexData.uvs = uvs;
  37400. if (faceColors) {
  37401. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37402. vertexData.colors = totalColors;
  37403. }
  37404. return vertexData;
  37405. };
  37406. /**
  37407. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37408. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37409. * * segments sets the number of horizontal strips optional, default 32
  37410. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37411. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37412. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37413. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37414. * * 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
  37415. * * 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
  37416. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37417. * * 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)
  37418. * * 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)
  37419. * @returns the VertexData of the ellipsoid
  37420. */
  37421. VertexData.CreateSphere = function (options) {
  37422. var segments = options.segments || 32;
  37423. var diameterX = options.diameterX || options.diameter || 1;
  37424. var diameterY = options.diameterY || options.diameter || 1;
  37425. var diameterZ = options.diameterZ || options.diameter || 1;
  37426. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37427. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37428. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37429. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37430. var totalZRotationSteps = 2 + segments;
  37431. var totalYRotationSteps = 2 * totalZRotationSteps;
  37432. var indices = [];
  37433. var positions = [];
  37434. var normals = [];
  37435. var uvs = [];
  37436. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37437. var normalizedZ = zRotationStep / totalZRotationSteps;
  37438. var angleZ = normalizedZ * Math.PI * slice;
  37439. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37440. var normalizedY = yRotationStep / totalYRotationSteps;
  37441. var angleY = normalizedY * Math.PI * 2 * arc;
  37442. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37443. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37444. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37445. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37446. var vertex = complete.multiply(radius);
  37447. var normal = complete.divide(radius).normalize();
  37448. positions.push(vertex.x, vertex.y, vertex.z);
  37449. normals.push(normal.x, normal.y, normal.z);
  37450. uvs.push(normalizedY, normalizedZ);
  37451. }
  37452. if (zRotationStep > 0) {
  37453. var verticesCount = positions.length / 3;
  37454. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37455. indices.push((firstIndex));
  37456. indices.push((firstIndex + 1));
  37457. indices.push(firstIndex + totalYRotationSteps + 1);
  37458. indices.push((firstIndex + totalYRotationSteps + 1));
  37459. indices.push((firstIndex + 1));
  37460. indices.push((firstIndex + totalYRotationSteps + 2));
  37461. }
  37462. }
  37463. }
  37464. // Sides
  37465. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37466. // Result
  37467. var vertexData = new VertexData();
  37468. vertexData.indices = indices;
  37469. vertexData.positions = positions;
  37470. vertexData.normals = normals;
  37471. vertexData.uvs = uvs;
  37472. return vertexData;
  37473. };
  37474. /**
  37475. * Creates the VertexData for a cylinder, cone or prism
  37476. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37477. * * height sets the height (y direction) of the cylinder, optional, default 2
  37478. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37479. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37480. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37481. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37482. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37483. * * 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
  37484. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37485. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37486. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37487. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37488. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37489. * * 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)
  37490. * * 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)
  37491. * @returns the VertexData of the cylinder, cone or prism
  37492. */
  37493. VertexData.CreateCylinder = function (options) {
  37494. var height = options.height || 2;
  37495. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37496. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37497. var tessellation = options.tessellation || 24;
  37498. var subdivisions = options.subdivisions || 1;
  37499. var hasRings = options.hasRings ? true : false;
  37500. var enclose = options.enclose ? true : false;
  37501. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37502. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37503. var faceUV = options.faceUV || new Array(3);
  37504. var faceColors = options.faceColors;
  37505. // default face colors and UV if undefined
  37506. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37507. var ringNb = (hasRings) ? subdivisions : 1;
  37508. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37509. var f;
  37510. for (f = 0; f < surfaceNb; f++) {
  37511. if (faceColors && faceColors[f] === undefined) {
  37512. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37513. }
  37514. }
  37515. for (f = 0; f < surfaceNb; f++) {
  37516. if (faceUV && faceUV[f] === undefined) {
  37517. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37518. }
  37519. }
  37520. var indices = new Array();
  37521. var positions = new Array();
  37522. var normals = new Array();
  37523. var uvs = new Array();
  37524. var colors = new Array();
  37525. var angle_step = Math.PI * 2 * arc / tessellation;
  37526. var angle;
  37527. var h;
  37528. var radius;
  37529. var tan = (diameterBottom - diameterTop) / 2 / height;
  37530. var ringVertex = BABYLON.Vector3.Zero();
  37531. var ringNormal = BABYLON.Vector3.Zero();
  37532. var ringFirstVertex = BABYLON.Vector3.Zero();
  37533. var ringFirstNormal = BABYLON.Vector3.Zero();
  37534. var quadNormal = BABYLON.Vector3.Zero();
  37535. var Y = BABYLON.Axis.Y;
  37536. // positions, normals, uvs
  37537. var i;
  37538. var j;
  37539. var r;
  37540. var ringIdx = 1;
  37541. var s = 1; // surface index
  37542. var cs = 0;
  37543. var v = 0;
  37544. for (i = 0; i <= subdivisions; i++) {
  37545. h = i / subdivisions;
  37546. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37547. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37548. for (r = 0; r < ringIdx; r++) {
  37549. if (hasRings) {
  37550. s += r;
  37551. }
  37552. if (enclose) {
  37553. s += 2 * r;
  37554. }
  37555. for (j = 0; j <= tessellation; j++) {
  37556. angle = j * angle_step;
  37557. // position
  37558. ringVertex.x = Math.cos(-angle) * radius;
  37559. ringVertex.y = -height / 2 + h * height;
  37560. ringVertex.z = Math.sin(-angle) * radius;
  37561. // normal
  37562. if (diameterTop === 0 && i === subdivisions) {
  37563. // if no top cap, reuse former normals
  37564. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37565. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37566. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37567. }
  37568. else {
  37569. ringNormal.x = ringVertex.x;
  37570. ringNormal.z = ringVertex.z;
  37571. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37572. ringNormal.normalize();
  37573. }
  37574. // keep first ring vertex values for enclose
  37575. if (j === 0) {
  37576. ringFirstVertex.copyFrom(ringVertex);
  37577. ringFirstNormal.copyFrom(ringNormal);
  37578. }
  37579. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37580. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37581. if (hasRings) {
  37582. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37583. }
  37584. else {
  37585. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37586. }
  37587. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37588. if (faceColors) {
  37589. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37590. }
  37591. }
  37592. // if enclose, add four vertices and their dedicated normals
  37593. if (arc !== 1 && enclose) {
  37594. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37595. positions.push(0, ringVertex.y, 0);
  37596. positions.push(0, ringVertex.y, 0);
  37597. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37598. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37599. quadNormal.normalize();
  37600. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37601. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37602. quadNormal.normalize();
  37603. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37604. if (hasRings) {
  37605. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37606. }
  37607. else {
  37608. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37609. }
  37610. uvs.push(faceUV[s + 1].x, v);
  37611. uvs.push(faceUV[s + 1].z, v);
  37612. if (hasRings) {
  37613. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37614. }
  37615. else {
  37616. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37617. }
  37618. uvs.push(faceUV[s + 2].x, v);
  37619. uvs.push(faceUV[s + 2].z, v);
  37620. if (faceColors) {
  37621. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37622. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37623. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37624. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37625. }
  37626. }
  37627. if (cs !== s) {
  37628. cs = s;
  37629. }
  37630. }
  37631. }
  37632. // indices
  37633. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37634. var s;
  37635. i = 0;
  37636. for (s = 0; s < subdivisions; s++) {
  37637. var i0 = 0;
  37638. var i1 = 0;
  37639. var i2 = 0;
  37640. var i3 = 0;
  37641. for (j = 0; j < tessellation; j++) {
  37642. i0 = i * (e + 1) + j;
  37643. i1 = (i + 1) * (e + 1) + j;
  37644. i2 = i * (e + 1) + (j + 1);
  37645. i3 = (i + 1) * (e + 1) + (j + 1);
  37646. indices.push(i0, i1, i2);
  37647. indices.push(i3, i2, i1);
  37648. }
  37649. if (arc !== 1 && enclose) { // if enclose, add two quads
  37650. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37651. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37652. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37653. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37654. }
  37655. i = (hasRings) ? (i + 2) : (i + 1);
  37656. }
  37657. // Caps
  37658. var createCylinderCap = function (isTop) {
  37659. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37660. if (radius === 0) {
  37661. return;
  37662. }
  37663. // Cap positions, normals & uvs
  37664. var angle;
  37665. var circleVector;
  37666. var i;
  37667. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37668. var c = null;
  37669. if (faceColors) {
  37670. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37671. }
  37672. // cap center
  37673. var vbase = positions.length / 3;
  37674. var offset = isTop ? height / 2 : -height / 2;
  37675. var center = new BABYLON.Vector3(0, offset, 0);
  37676. positions.push(center.x, center.y, center.z);
  37677. normals.push(0, isTop ? 1 : -1, 0);
  37678. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37679. if (c) {
  37680. colors.push(c.r, c.g, c.b, c.a);
  37681. }
  37682. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37683. for (i = 0; i <= tessellation; i++) {
  37684. angle = Math.PI * 2 * i * arc / tessellation;
  37685. var cos = Math.cos(-angle);
  37686. var sin = Math.sin(-angle);
  37687. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37688. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37689. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37690. normals.push(0, isTop ? 1 : -1, 0);
  37691. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37692. if (c) {
  37693. colors.push(c.r, c.g, c.b, c.a);
  37694. }
  37695. }
  37696. // Cap indices
  37697. for (i = 0; i < tessellation; i++) {
  37698. if (!isTop) {
  37699. indices.push(vbase);
  37700. indices.push(vbase + (i + 1));
  37701. indices.push(vbase + (i + 2));
  37702. }
  37703. else {
  37704. indices.push(vbase);
  37705. indices.push(vbase + (i + 2));
  37706. indices.push(vbase + (i + 1));
  37707. }
  37708. }
  37709. };
  37710. // add caps to geometry
  37711. createCylinderCap(false);
  37712. createCylinderCap(true);
  37713. // Sides
  37714. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37715. var vertexData = new VertexData();
  37716. vertexData.indices = indices;
  37717. vertexData.positions = positions;
  37718. vertexData.normals = normals;
  37719. vertexData.uvs = uvs;
  37720. if (faceColors) {
  37721. vertexData.colors = colors;
  37722. }
  37723. return vertexData;
  37724. };
  37725. /**
  37726. * Creates the VertexData for a torus
  37727. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37728. * * diameter the diameter of the torus, optional default 1
  37729. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37730. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37731. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37732. * * 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)
  37733. * * 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)
  37734. * @returns the VertexData of the torus
  37735. */
  37736. VertexData.CreateTorus = function (options) {
  37737. var indices = [];
  37738. var positions = [];
  37739. var normals = [];
  37740. var uvs = [];
  37741. var diameter = options.diameter || 1;
  37742. var thickness = options.thickness || 0.5;
  37743. var tessellation = options.tessellation || 16;
  37744. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37745. var stride = tessellation + 1;
  37746. for (var i = 0; i <= tessellation; i++) {
  37747. var u = i / tessellation;
  37748. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37749. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37750. for (var j = 0; j <= tessellation; j++) {
  37751. var v = 1 - j / tessellation;
  37752. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37753. var dx = Math.cos(innerAngle);
  37754. var dy = Math.sin(innerAngle);
  37755. // Create a vertex.
  37756. var normal = new BABYLON.Vector3(dx, dy, 0);
  37757. var position = normal.scale(thickness / 2);
  37758. var textureCoordinate = new BABYLON.Vector2(u, v);
  37759. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37760. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37761. positions.push(position.x, position.y, position.z);
  37762. normals.push(normal.x, normal.y, normal.z);
  37763. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37764. // And create indices for two triangles.
  37765. var nextI = (i + 1) % stride;
  37766. var nextJ = (j + 1) % stride;
  37767. indices.push(i * stride + j);
  37768. indices.push(i * stride + nextJ);
  37769. indices.push(nextI * stride + j);
  37770. indices.push(i * stride + nextJ);
  37771. indices.push(nextI * stride + nextJ);
  37772. indices.push(nextI * stride + j);
  37773. }
  37774. }
  37775. // Sides
  37776. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37777. // Result
  37778. var vertexData = new VertexData();
  37779. vertexData.indices = indices;
  37780. vertexData.positions = positions;
  37781. vertexData.normals = normals;
  37782. vertexData.uvs = uvs;
  37783. return vertexData;
  37784. };
  37785. /**
  37786. * Creates the VertexData of the LineSystem
  37787. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37788. * - lines an array of lines, each line being an array of successive Vector3
  37789. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37790. * @returns the VertexData of the LineSystem
  37791. */
  37792. VertexData.CreateLineSystem = function (options) {
  37793. var indices = [];
  37794. var positions = [];
  37795. var lines = options.lines;
  37796. var colors = options.colors;
  37797. var vertexColors = [];
  37798. var idx = 0;
  37799. for (var l = 0; l < lines.length; l++) {
  37800. var points = lines[l];
  37801. for (var index = 0; index < points.length; index++) {
  37802. positions.push(points[index].x, points[index].y, points[index].z);
  37803. if (colors) {
  37804. var color = colors[l];
  37805. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37806. }
  37807. if (index > 0) {
  37808. indices.push(idx - 1);
  37809. indices.push(idx);
  37810. }
  37811. idx++;
  37812. }
  37813. }
  37814. var vertexData = new VertexData();
  37815. vertexData.indices = indices;
  37816. vertexData.positions = positions;
  37817. if (colors) {
  37818. vertexData.colors = vertexColors;
  37819. }
  37820. return vertexData;
  37821. };
  37822. /**
  37823. * Create the VertexData for a DashedLines
  37824. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37825. * - points an array successive Vector3
  37826. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37827. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37828. * - dashNb the intended total number of dashes, optional, default 200
  37829. * @returns the VertexData for the DashedLines
  37830. */
  37831. VertexData.CreateDashedLines = function (options) {
  37832. var dashSize = options.dashSize || 3;
  37833. var gapSize = options.gapSize || 1;
  37834. var dashNb = options.dashNb || 200;
  37835. var points = options.points;
  37836. var positions = new Array();
  37837. var indices = new Array();
  37838. var curvect = BABYLON.Vector3.Zero();
  37839. var lg = 0;
  37840. var nb = 0;
  37841. var shft = 0;
  37842. var dashshft = 0;
  37843. var curshft = 0;
  37844. var idx = 0;
  37845. var i = 0;
  37846. for (i = 0; i < points.length - 1; i++) {
  37847. points[i + 1].subtractToRef(points[i], curvect);
  37848. lg += curvect.length();
  37849. }
  37850. shft = lg / dashNb;
  37851. dashshft = dashSize * shft / (dashSize + gapSize);
  37852. for (i = 0; i < points.length - 1; i++) {
  37853. points[i + 1].subtractToRef(points[i], curvect);
  37854. nb = Math.floor(curvect.length() / shft);
  37855. curvect.normalize();
  37856. for (var j = 0; j < nb; j++) {
  37857. curshft = shft * j;
  37858. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37859. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37860. indices.push(idx, idx + 1);
  37861. idx += 2;
  37862. }
  37863. }
  37864. // Result
  37865. var vertexData = new VertexData();
  37866. vertexData.positions = positions;
  37867. vertexData.indices = indices;
  37868. return vertexData;
  37869. };
  37870. /**
  37871. * Creates the VertexData for a Ground
  37872. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37873. * - width the width (x direction) of the ground, optional, default 1
  37874. * - height the height (z direction) of the ground, optional, default 1
  37875. * - subdivisions the number of subdivisions per side, optional, default 1
  37876. * @returns the VertexData of the Ground
  37877. */
  37878. VertexData.CreateGround = function (options) {
  37879. var indices = [];
  37880. var positions = [];
  37881. var normals = [];
  37882. var uvs = [];
  37883. var row, col;
  37884. var width = options.width || 1;
  37885. var height = options.height || 1;
  37886. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37887. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37888. for (row = 0; row <= subdivisionsY; row++) {
  37889. for (col = 0; col <= subdivisionsX; col++) {
  37890. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37891. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37892. positions.push(position.x, position.y, position.z);
  37893. normals.push(normal.x, normal.y, normal.z);
  37894. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37895. }
  37896. }
  37897. for (row = 0; row < subdivisionsY; row++) {
  37898. for (col = 0; col < subdivisionsX; col++) {
  37899. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37900. indices.push(col + 1 + row * (subdivisionsX + 1));
  37901. indices.push(col + row * (subdivisionsX + 1));
  37902. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37903. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37904. indices.push(col + row * (subdivisionsX + 1));
  37905. }
  37906. }
  37907. // Result
  37908. var vertexData = new VertexData();
  37909. vertexData.indices = indices;
  37910. vertexData.positions = positions;
  37911. vertexData.normals = normals;
  37912. vertexData.uvs = uvs;
  37913. return vertexData;
  37914. };
  37915. /**
  37916. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37917. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37918. * * xmin the ground minimum X coordinate, optional, default -1
  37919. * * zmin the ground minimum Z coordinate, optional, default -1
  37920. * * xmax the ground maximum X coordinate, optional, default 1
  37921. * * zmax the ground maximum Z coordinate, optional, default 1
  37922. * * 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}
  37923. * * 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}
  37924. * @returns the VertexData of the TiledGround
  37925. */
  37926. VertexData.CreateTiledGround = function (options) {
  37927. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37928. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37929. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37930. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37931. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37932. var precision = options.precision || { w: 1, h: 1 };
  37933. var indices = new Array();
  37934. var positions = new Array();
  37935. var normals = new Array();
  37936. var uvs = new Array();
  37937. var row, col, tileRow, tileCol;
  37938. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37939. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37940. precision.w = (precision.w < 1) ? 1 : precision.w;
  37941. precision.h = (precision.h < 1) ? 1 : precision.h;
  37942. var tileSize = {
  37943. 'w': (xmax - xmin) / subdivisions.w,
  37944. 'h': (zmax - zmin) / subdivisions.h
  37945. };
  37946. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37947. // Indices
  37948. var base = positions.length / 3;
  37949. var rowLength = precision.w + 1;
  37950. for (row = 0; row < precision.h; row++) {
  37951. for (col = 0; col < precision.w; col++) {
  37952. var square = [
  37953. base + col + row * rowLength,
  37954. base + (col + 1) + row * rowLength,
  37955. base + (col + 1) + (row + 1) * rowLength,
  37956. base + col + (row + 1) * rowLength
  37957. ];
  37958. indices.push(square[1]);
  37959. indices.push(square[2]);
  37960. indices.push(square[3]);
  37961. indices.push(square[0]);
  37962. indices.push(square[1]);
  37963. indices.push(square[3]);
  37964. }
  37965. }
  37966. // Position, normals and uvs
  37967. var position = BABYLON.Vector3.Zero();
  37968. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37969. for (row = 0; row <= precision.h; row++) {
  37970. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37971. for (col = 0; col <= precision.w; col++) {
  37972. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37973. position.y = 0;
  37974. positions.push(position.x, position.y, position.z);
  37975. normals.push(normal.x, normal.y, normal.z);
  37976. uvs.push(col / precision.w, row / precision.h);
  37977. }
  37978. }
  37979. }
  37980. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37981. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37982. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37983. }
  37984. }
  37985. // Result
  37986. var vertexData = new VertexData();
  37987. vertexData.indices = indices;
  37988. vertexData.positions = positions;
  37989. vertexData.normals = normals;
  37990. vertexData.uvs = uvs;
  37991. return vertexData;
  37992. };
  37993. /**
  37994. * Creates the VertexData of the Ground designed from a heightmap
  37995. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37996. * * width the width (x direction) of the ground
  37997. * * height the height (z direction) of the ground
  37998. * * subdivisions the number of subdivisions per side
  37999. * * minHeight the minimum altitude on the ground, optional, default 0
  38000. * * maxHeight the maximum altitude on the ground, optional default 1
  38001. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38002. * * buffer the array holding the image color data
  38003. * * bufferWidth the width of image
  38004. * * bufferHeight the height of image
  38005. * @returns the VertexData of the Ground designed from a heightmap
  38006. */
  38007. VertexData.CreateGroundFromHeightMap = function (options) {
  38008. var indices = [];
  38009. var positions = [];
  38010. var normals = [];
  38011. var uvs = [];
  38012. var row, col;
  38013. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38014. // Vertices
  38015. for (row = 0; row <= options.subdivisions; row++) {
  38016. for (col = 0; col <= options.subdivisions; col++) {
  38017. 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));
  38018. // Compute height
  38019. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38020. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38021. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38022. var r = options.buffer[pos] / 255.0;
  38023. var g = options.buffer[pos + 1] / 255.0;
  38024. var b = options.buffer[pos + 2] / 255.0;
  38025. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38026. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38027. // Add vertex
  38028. positions.push(position.x, position.y, position.z);
  38029. normals.push(0, 0, 0);
  38030. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38031. }
  38032. }
  38033. // Indices
  38034. for (row = 0; row < options.subdivisions; row++) {
  38035. for (col = 0; col < options.subdivisions; col++) {
  38036. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38037. indices.push(col + 1 + row * (options.subdivisions + 1));
  38038. indices.push(col + row * (options.subdivisions + 1));
  38039. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38040. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38041. indices.push(col + row * (options.subdivisions + 1));
  38042. }
  38043. }
  38044. // Normals
  38045. VertexData.ComputeNormals(positions, indices, normals);
  38046. // Result
  38047. var vertexData = new VertexData();
  38048. vertexData.indices = indices;
  38049. vertexData.positions = positions;
  38050. vertexData.normals = normals;
  38051. vertexData.uvs = uvs;
  38052. return vertexData;
  38053. };
  38054. /**
  38055. * Creates the VertexData for a Plane
  38056. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38057. * * size sets the width and height of the plane to the value of size, optional default 1
  38058. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38059. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38060. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38061. * * 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)
  38062. * * 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)
  38063. * @returns the VertexData of the box
  38064. */
  38065. VertexData.CreatePlane = function (options) {
  38066. var indices = [];
  38067. var positions = [];
  38068. var normals = [];
  38069. var uvs = [];
  38070. var width = options.width || options.size || 1;
  38071. var height = options.height || options.size || 1;
  38072. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38073. // Vertices
  38074. var halfWidth = width / 2.0;
  38075. var halfHeight = height / 2.0;
  38076. positions.push(-halfWidth, -halfHeight, 0);
  38077. normals.push(0, 0, -1.0);
  38078. uvs.push(0.0, 0.0);
  38079. positions.push(halfWidth, -halfHeight, 0);
  38080. normals.push(0, 0, -1.0);
  38081. uvs.push(1.0, 0.0);
  38082. positions.push(halfWidth, halfHeight, 0);
  38083. normals.push(0, 0, -1.0);
  38084. uvs.push(1.0, 1.0);
  38085. positions.push(-halfWidth, halfHeight, 0);
  38086. normals.push(0, 0, -1.0);
  38087. uvs.push(0.0, 1.0);
  38088. // Indices
  38089. indices.push(0);
  38090. indices.push(1);
  38091. indices.push(2);
  38092. indices.push(0);
  38093. indices.push(2);
  38094. indices.push(3);
  38095. // Sides
  38096. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38097. // Result
  38098. var vertexData = new VertexData();
  38099. vertexData.indices = indices;
  38100. vertexData.positions = positions;
  38101. vertexData.normals = normals;
  38102. vertexData.uvs = uvs;
  38103. return vertexData;
  38104. };
  38105. /**
  38106. * Creates the VertexData of the Disc or regular Polygon
  38107. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38108. * * radius the radius of the disc, optional default 0.5
  38109. * * tessellation the number of polygon sides, optional, default 64
  38110. * * 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
  38111. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38112. * * 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)
  38113. * * 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)
  38114. * @returns the VertexData of the box
  38115. */
  38116. VertexData.CreateDisc = function (options) {
  38117. var positions = new Array();
  38118. var indices = new Array();
  38119. var normals = new Array();
  38120. var uvs = new Array();
  38121. var radius = options.radius || 0.5;
  38122. var tessellation = options.tessellation || 64;
  38123. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38124. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38125. // positions and uvs
  38126. positions.push(0, 0, 0); // disc center first
  38127. uvs.push(0.5, 0.5);
  38128. var theta = Math.PI * 2 * arc;
  38129. var step = theta / tessellation;
  38130. for (var a = 0; a < theta; a += step) {
  38131. var x = Math.cos(a);
  38132. var y = Math.sin(a);
  38133. var u = (x + 1) / 2;
  38134. var v = (1 - y) / 2;
  38135. positions.push(radius * x, radius * y, 0);
  38136. uvs.push(u, v);
  38137. }
  38138. if (arc === 1) {
  38139. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38140. uvs.push(uvs[2], uvs[3]);
  38141. }
  38142. //indices
  38143. var vertexNb = positions.length / 3;
  38144. for (var i = 1; i < vertexNb - 1; i++) {
  38145. indices.push(i + 1, 0, i);
  38146. }
  38147. // result
  38148. VertexData.ComputeNormals(positions, indices, normals);
  38149. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38150. var vertexData = new VertexData();
  38151. vertexData.indices = indices;
  38152. vertexData.positions = positions;
  38153. vertexData.normals = normals;
  38154. vertexData.uvs = uvs;
  38155. return vertexData;
  38156. };
  38157. /**
  38158. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38159. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38160. * @param polygon a mesh built from polygonTriangulation.build()
  38161. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38162. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38163. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38164. * @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)
  38165. * @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)
  38166. * @returns the VertexData of the Polygon
  38167. */
  38168. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38169. var faceUV = fUV || new Array(3);
  38170. var faceColors = fColors;
  38171. var colors = [];
  38172. // default face colors and UV if undefined
  38173. for (var f = 0; f < 3; f++) {
  38174. if (faceUV[f] === undefined) {
  38175. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38176. }
  38177. if (faceColors && faceColors[f] === undefined) {
  38178. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38179. }
  38180. }
  38181. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38182. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38183. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38184. var indices = polygon.getIndices();
  38185. // set face colours and textures
  38186. var idx = 0;
  38187. var face = 0;
  38188. for (var index = 0; index < normals.length; index += 3) {
  38189. //Edge Face no. 1
  38190. if (Math.abs(normals[index + 1]) < 0.001) {
  38191. face = 1;
  38192. }
  38193. //Top Face no. 0
  38194. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38195. face = 0;
  38196. }
  38197. //Bottom Face no. 2
  38198. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38199. face = 2;
  38200. }
  38201. idx = index / 3;
  38202. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38203. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38204. if (faceColors) {
  38205. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38206. }
  38207. }
  38208. // sides
  38209. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38210. // Result
  38211. var vertexData = new VertexData();
  38212. vertexData.indices = indices;
  38213. vertexData.positions = positions;
  38214. vertexData.normals = normals;
  38215. vertexData.uvs = uvs;
  38216. if (faceColors) {
  38217. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38218. vertexData.colors = totalColors;
  38219. }
  38220. return vertexData;
  38221. };
  38222. /**
  38223. * Creates the VertexData of the IcoSphere
  38224. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38225. * * radius the radius of the IcoSphere, optional default 1
  38226. * * radiusX allows stretching in the x direction, optional, default radius
  38227. * * radiusY allows stretching in the y direction, optional, default radius
  38228. * * radiusZ allows stretching in the z direction, optional, default radius
  38229. * * flat when true creates a flat shaded mesh, optional, default true
  38230. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38231. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38232. * * 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)
  38233. * * 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)
  38234. * @returns the VertexData of the IcoSphere
  38235. */
  38236. VertexData.CreateIcoSphere = function (options) {
  38237. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38238. var radius = options.radius || 1;
  38239. var flat = (options.flat === undefined) ? true : options.flat;
  38240. var subdivisions = options.subdivisions || 4;
  38241. var radiusX = options.radiusX || radius;
  38242. var radiusY = options.radiusY || radius;
  38243. var radiusZ = options.radiusZ || radius;
  38244. var t = (1 + Math.sqrt(5)) / 2;
  38245. // 12 vertex x,y,z
  38246. var ico_vertices = [
  38247. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38248. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38249. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38250. ];
  38251. // index of 3 vertex makes a face of icopshere
  38252. var ico_indices = [
  38253. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38254. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38255. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38256. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38257. ];
  38258. // vertex for uv have aliased position, not for UV
  38259. var vertices_unalias_id = [
  38260. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38261. // vertex alias
  38262. 0,
  38263. 2,
  38264. 3,
  38265. 3,
  38266. 3,
  38267. 4,
  38268. 7,
  38269. 8,
  38270. 9,
  38271. 9,
  38272. 10,
  38273. 11 // 23: B + 12
  38274. ];
  38275. // uv as integer step (not pixels !)
  38276. var ico_vertexuv = [
  38277. 5, 1, 3, 1, 6, 4, 0, 0,
  38278. 5, 3, 4, 2, 2, 2, 4, 0,
  38279. 2, 0, 1, 1, 6, 0, 6, 2,
  38280. // vertex alias (for same vertex on different faces)
  38281. 0, 4,
  38282. 3, 3,
  38283. 4, 4,
  38284. 3, 1,
  38285. 4, 2,
  38286. 4, 4,
  38287. 0, 2,
  38288. 1, 1,
  38289. 2, 2,
  38290. 3, 3,
  38291. 1, 3,
  38292. 2, 4 // 23: B + 12
  38293. ];
  38294. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38295. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38296. // First island of uv mapping
  38297. // v = 4h 3+ 2
  38298. // v = 3h 9+ 4
  38299. // v = 2h 9+ 5 B
  38300. // v = 1h 9 1 0
  38301. // v = 0h 3 8 7 A
  38302. // u = 0 1 2 3 4 5 6 *a
  38303. // Second island of uv mapping
  38304. // v = 4h 0+ B+ 4+
  38305. // v = 3h A+ 2+
  38306. // v = 2h 7+ 6 3+
  38307. // v = 1h 8+ 3+
  38308. // v = 0h
  38309. // u = 0 1 2 3 4 5 6 *a
  38310. // Face layout on texture UV mapping
  38311. // ============
  38312. // \ 4 /\ 16 / ======
  38313. // \ / \ / /\ 11 /
  38314. // \/ 7 \/ / \ /
  38315. // ======= / 10 \/
  38316. // /\ 17 /\ =======
  38317. // / \ / \ \ 15 /\
  38318. // / 8 \/ 12 \ \ / \
  38319. // ============ \/ 6 \
  38320. // \ 18 /\ ============
  38321. // \ / \ \ 5 /\ 0 /
  38322. // \/ 13 \ \ / \ /
  38323. // ======= \/ 1 \/
  38324. // =============
  38325. // /\ 19 /\ 2 /\
  38326. // / \ / \ / \
  38327. // / 14 \/ 9 \/ 3 \
  38328. // ===================
  38329. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38330. var ustep = 138 / 1024;
  38331. var vstep = 239 / 1024;
  38332. var uoffset = 60 / 1024;
  38333. var voffset = 26 / 1024;
  38334. // Second island should have margin, not to touch the first island
  38335. // avoid any borderline artefact in pixel rounding
  38336. var island_u_offset = -40 / 1024;
  38337. var island_v_offset = +20 / 1024;
  38338. // face is either island 0 or 1 :
  38339. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38340. var island = [
  38341. 0, 0, 0, 0, 1,
  38342. 0, 0, 1, 1, 0,
  38343. 0, 0, 1, 1, 0,
  38344. 0, 1, 1, 1, 0 // 15 - 19
  38345. ];
  38346. var indices = new Array();
  38347. var positions = new Array();
  38348. var normals = new Array();
  38349. var uvs = new Array();
  38350. var current_indice = 0;
  38351. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38352. var face_vertex_pos = new Array(3);
  38353. var face_vertex_uv = new Array(3);
  38354. var v012;
  38355. for (v012 = 0; v012 < 3; v012++) {
  38356. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38357. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38358. }
  38359. // create all with normals
  38360. for (var face = 0; face < 20; face++) {
  38361. // 3 vertex per face
  38362. for (v012 = 0; v012 < 3; v012++) {
  38363. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38364. var v_id = ico_indices[3 * face + v012];
  38365. // vertex have 3D position (x,y,z)
  38366. 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]);
  38367. // Normalize to get normal, then scale to radius
  38368. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38369. // uv Coordinates from vertex ID
  38370. 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);
  38371. }
  38372. // Subdivide the face (interpolate pos, norm, uv)
  38373. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38374. // - norm is linear interpolation of vertex corner normal
  38375. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38376. // - uv is linear interpolation
  38377. //
  38378. // Topology is as below for sub-divide by 2
  38379. // vertex shown as v0,v1,v2
  38380. // interp index is i1 to progress in range [v0,v1[
  38381. // interp index is i2 to progress in range [v0,v2[
  38382. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38383. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38384. //
  38385. //
  38386. // i2 v2
  38387. // ^ ^
  38388. // / / \
  38389. // / / \
  38390. // / / \
  38391. // / / (0,1) \
  38392. // / #---------\
  38393. // / / \ (0,0)'/ \
  38394. // / / \ / \
  38395. // / / \ / \
  38396. // / / (0,0) \ / (1,0) \
  38397. // / #---------#---------\
  38398. // v0 v1
  38399. //
  38400. // --------------------> i1
  38401. //
  38402. // interp of (i1,i2):
  38403. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38404. // along i1 : lerp(x0,x1, i1/(S-i2))
  38405. //
  38406. // centroid of triangle is needed to get help normal computation
  38407. // (c1,c2) are used for centroid location
  38408. var interp_vertex = function (i1, i2, c1, c2) {
  38409. // vertex is interpolated from
  38410. // - face_vertex_pos[0..2]
  38411. // - face_vertex_uv[0..2]
  38412. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38413. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38414. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38415. pos_interp.normalize();
  38416. var vertex_normal;
  38417. if (flat) {
  38418. // in flat mode, recalculate normal as face centroid normal
  38419. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38420. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38421. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38422. }
  38423. else {
  38424. // in smooth mode, recalculate normal from each single vertex position
  38425. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38426. }
  38427. // Vertex normal need correction due to X,Y,Z radius scaling
  38428. vertex_normal.x /= radiusX;
  38429. vertex_normal.y /= radiusY;
  38430. vertex_normal.z /= radiusZ;
  38431. vertex_normal.normalize();
  38432. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38433. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38434. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38435. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38436. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38437. uvs.push(uv_interp.x, uv_interp.y);
  38438. // push each vertex has member of a face
  38439. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38440. indices.push(current_indice);
  38441. current_indice++;
  38442. };
  38443. for (var i2 = 0; i2 < subdivisions; i2++) {
  38444. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38445. // face : (i1,i2) for /\ :
  38446. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38447. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38448. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38449. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38450. if (i1 + i2 + 1 < subdivisions) {
  38451. // face : (i1,i2)' for \/ :
  38452. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38453. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38454. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38455. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38456. }
  38457. }
  38458. }
  38459. }
  38460. // Sides
  38461. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38462. // Result
  38463. var vertexData = new VertexData();
  38464. vertexData.indices = indices;
  38465. vertexData.positions = positions;
  38466. vertexData.normals = normals;
  38467. vertexData.uvs = uvs;
  38468. return vertexData;
  38469. };
  38470. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38471. /**
  38472. * Creates the VertexData for a Polyhedron
  38473. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38474. * * type provided types are:
  38475. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38476. * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  38477. * * size the size of the IcoSphere, optional default 1
  38478. * * sizeX allows stretching in the x direction, optional, default size
  38479. * * sizeY allows stretching in the y direction, optional, default size
  38480. * * sizeZ allows stretching in the z direction, optional, default size
  38481. * * 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
  38482. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38483. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38484. * * flat when true creates a flat shaded mesh, optional, default true
  38485. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38486. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38487. * * 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)
  38488. * * 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)
  38489. * @returns the VertexData of the Polyhedron
  38490. */
  38491. VertexData.CreatePolyhedron = function (options) {
  38492. // provided polyhedron types :
  38493. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38494. // 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)
  38495. var polyhedra = [];
  38496. 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]] };
  38497. 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]] };
  38498. polyhedra[2] = {
  38499. 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]],
  38500. 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]]
  38501. };
  38502. polyhedra[3] = {
  38503. 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]],
  38504. 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]]
  38505. };
  38506. polyhedra[4] = {
  38507. 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]],
  38508. 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]]
  38509. };
  38510. 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]] };
  38511. 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]] };
  38512. 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]] };
  38513. 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]] };
  38514. 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]] };
  38515. 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]] };
  38516. 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]] };
  38517. 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]] };
  38518. 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]] };
  38519. polyhedra[14] = {
  38520. 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]],
  38521. 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]]
  38522. };
  38523. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38524. var size = options.size;
  38525. var sizeX = options.sizeX || size || 1;
  38526. var sizeY = options.sizeY || size || 1;
  38527. var sizeZ = options.sizeZ || size || 1;
  38528. var data = options.custom || polyhedra[type];
  38529. var nbfaces = data.face.length;
  38530. var faceUV = options.faceUV || new Array(nbfaces);
  38531. var faceColors = options.faceColors;
  38532. var flat = (options.flat === undefined) ? true : options.flat;
  38533. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38534. var positions = new Array();
  38535. var indices = new Array();
  38536. var normals = new Array();
  38537. var uvs = new Array();
  38538. var colors = new Array();
  38539. var index = 0;
  38540. var faceIdx = 0; // face cursor in the array "indexes"
  38541. var indexes = new Array();
  38542. var i = 0;
  38543. var f = 0;
  38544. var u, v, ang, x, y, tmp;
  38545. // default face colors and UV if undefined
  38546. if (flat) {
  38547. for (f = 0; f < nbfaces; f++) {
  38548. if (faceColors && faceColors[f] === undefined) {
  38549. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38550. }
  38551. if (faceUV && faceUV[f] === undefined) {
  38552. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38553. }
  38554. }
  38555. }
  38556. if (!flat) {
  38557. for (i = 0; i < data.vertex.length; i++) {
  38558. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38559. uvs.push(0, 0);
  38560. }
  38561. for (f = 0; f < nbfaces; f++) {
  38562. for (i = 0; i < data.face[f].length - 2; i++) {
  38563. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38564. }
  38565. }
  38566. }
  38567. else {
  38568. for (f = 0; f < nbfaces; f++) {
  38569. var fl = data.face[f].length; // number of vertices of the current face
  38570. ang = 2 * Math.PI / fl;
  38571. x = 0.5 * Math.tan(ang / 2);
  38572. y = 0.5;
  38573. // positions, uvs, colors
  38574. for (i = 0; i < fl; i++) {
  38575. // positions
  38576. 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);
  38577. indexes.push(index);
  38578. index++;
  38579. // uvs
  38580. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38581. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38582. uvs.push(u, v);
  38583. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38584. y = x * Math.sin(ang) + y * Math.cos(ang);
  38585. x = tmp;
  38586. // colors
  38587. if (faceColors) {
  38588. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38589. }
  38590. }
  38591. // indices from indexes
  38592. for (i = 0; i < fl - 2; i++) {
  38593. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38594. }
  38595. faceIdx += fl;
  38596. }
  38597. }
  38598. VertexData.ComputeNormals(positions, indices, normals);
  38599. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38600. var vertexData = new VertexData();
  38601. vertexData.positions = positions;
  38602. vertexData.indices = indices;
  38603. vertexData.normals = normals;
  38604. vertexData.uvs = uvs;
  38605. if (faceColors && flat) {
  38606. vertexData.colors = colors;
  38607. }
  38608. return vertexData;
  38609. };
  38610. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38611. /**
  38612. * Creates the VertexData for a TorusKnot
  38613. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38614. * * radius the radius of the torus knot, optional, default 2
  38615. * * tube the thickness of the tube, optional, default 0.5
  38616. * * radialSegments the number of sides on each tube segments, optional, default 32
  38617. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38618. * * p the number of windings around the z axis, optional, default 2
  38619. * * q the number of windings around the x axis, optional, default 3
  38620. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38621. * * 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)
  38622. * * 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)
  38623. * @returns the VertexData of the Torus Knot
  38624. */
  38625. VertexData.CreateTorusKnot = function (options) {
  38626. var indices = new Array();
  38627. var positions = new Array();
  38628. var normals = new Array();
  38629. var uvs = new Array();
  38630. var radius = options.radius || 2;
  38631. var tube = options.tube || 0.5;
  38632. var radialSegments = options.radialSegments || 32;
  38633. var tubularSegments = options.tubularSegments || 32;
  38634. var p = options.p || 2;
  38635. var q = options.q || 3;
  38636. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38637. // Helper
  38638. var getPos = function (angle) {
  38639. var cu = Math.cos(angle);
  38640. var su = Math.sin(angle);
  38641. var quOverP = q / p * angle;
  38642. var cs = Math.cos(quOverP);
  38643. var tx = radius * (2 + cs) * 0.5 * cu;
  38644. var ty = radius * (2 + cs) * su * 0.5;
  38645. var tz = radius * Math.sin(quOverP) * 0.5;
  38646. return new BABYLON.Vector3(tx, ty, tz);
  38647. };
  38648. // Vertices
  38649. var i;
  38650. var j;
  38651. for (i = 0; i <= radialSegments; i++) {
  38652. var modI = i % radialSegments;
  38653. var u = modI / radialSegments * 2 * p * Math.PI;
  38654. var p1 = getPos(u);
  38655. var p2 = getPos(u + 0.01);
  38656. var tang = p2.subtract(p1);
  38657. var n = p2.add(p1);
  38658. var bitan = BABYLON.Vector3.Cross(tang, n);
  38659. n = BABYLON.Vector3.Cross(bitan, tang);
  38660. bitan.normalize();
  38661. n.normalize();
  38662. for (j = 0; j < tubularSegments; j++) {
  38663. var modJ = j % tubularSegments;
  38664. var v = modJ / tubularSegments * 2 * Math.PI;
  38665. var cx = -tube * Math.cos(v);
  38666. var cy = tube * Math.sin(v);
  38667. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38668. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38669. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38670. uvs.push(i / radialSegments);
  38671. uvs.push(j / tubularSegments);
  38672. }
  38673. }
  38674. for (i = 0; i < radialSegments; i++) {
  38675. for (j = 0; j < tubularSegments; j++) {
  38676. var jNext = (j + 1) % tubularSegments;
  38677. var a = i * tubularSegments + j;
  38678. var b = (i + 1) * tubularSegments + j;
  38679. var c = (i + 1) * tubularSegments + jNext;
  38680. var d = i * tubularSegments + jNext;
  38681. indices.push(d);
  38682. indices.push(b);
  38683. indices.push(a);
  38684. indices.push(d);
  38685. indices.push(c);
  38686. indices.push(b);
  38687. }
  38688. }
  38689. // Normals
  38690. VertexData.ComputeNormals(positions, indices, normals);
  38691. // Sides
  38692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38693. // Result
  38694. var vertexData = new VertexData();
  38695. vertexData.indices = indices;
  38696. vertexData.positions = positions;
  38697. vertexData.normals = normals;
  38698. vertexData.uvs = uvs;
  38699. return vertexData;
  38700. };
  38701. // Tools
  38702. /**
  38703. * Compute normals for given positions and indices
  38704. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38705. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38706. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38707. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38708. * * facetNormals : optional array of facet normals (vector3)
  38709. * * facetPositions : optional array of facet positions (vector3)
  38710. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38711. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38712. * * bInfo : optional bounding info, required for facetPartitioning computation
  38713. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38714. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38715. * * useRightHandedSystem: optional boolean to for right handed system computation
  38716. * * depthSort : optional boolean to enable the facet depth sort computation
  38717. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38718. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38719. */
  38720. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38721. // temporary scalar variables
  38722. var index = 0; // facet index
  38723. var p1p2x = 0.0; // p1p2 vector x coordinate
  38724. var p1p2y = 0.0; // p1p2 vector y coordinate
  38725. var p1p2z = 0.0; // p1p2 vector z coordinate
  38726. var p3p2x = 0.0; // p3p2 vector x coordinate
  38727. var p3p2y = 0.0; // p3p2 vector y coordinate
  38728. var p3p2z = 0.0; // p3p2 vector z coordinate
  38729. var faceNormalx = 0.0; // facet normal x coordinate
  38730. var faceNormaly = 0.0; // facet normal y coordinate
  38731. var faceNormalz = 0.0; // facet normal z coordinate
  38732. var length = 0.0; // facet normal length before normalization
  38733. var v1x = 0; // vector1 x index in the positions array
  38734. var v1y = 0; // vector1 y index in the positions array
  38735. var v1z = 0; // vector1 z index in the positions array
  38736. var v2x = 0; // vector2 x index in the positions array
  38737. var v2y = 0; // vector2 y index in the positions array
  38738. var v2z = 0; // vector2 z index in the positions array
  38739. var v3x = 0; // vector3 x index in the positions array
  38740. var v3y = 0; // vector3 y index in the positions array
  38741. var v3z = 0; // vector3 z index in the positions array
  38742. var computeFacetNormals = false;
  38743. var computeFacetPositions = false;
  38744. var computeFacetPartitioning = false;
  38745. var computeDepthSort = false;
  38746. var faceNormalSign = 1;
  38747. var ratio = 0;
  38748. var distanceTo = null;
  38749. if (options) {
  38750. computeFacetNormals = (options.facetNormals) ? true : false;
  38751. computeFacetPositions = (options.facetPositions) ? true : false;
  38752. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38753. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38754. ratio = options.ratio || 0;
  38755. computeDepthSort = (options.depthSort) ? true : false;
  38756. distanceTo = (options.distanceTo);
  38757. if (computeDepthSort) {
  38758. if (distanceTo === undefined) {
  38759. distanceTo = BABYLON.Vector3.Zero();
  38760. }
  38761. var depthSortedFacets = options.depthSortedFacets;
  38762. }
  38763. }
  38764. // facetPartitioning reinit if needed
  38765. var xSubRatio = 0;
  38766. var ySubRatio = 0;
  38767. var zSubRatio = 0;
  38768. var subSq = 0;
  38769. if (computeFacetPartitioning && options && options.bbSize) {
  38770. var ox = 0; // X partitioning index for facet position
  38771. var oy = 0; // Y partinioning index for facet position
  38772. var oz = 0; // Z partinioning index for facet position
  38773. var b1x = 0; // X partitioning index for facet v1 vertex
  38774. var b1y = 0; // Y partitioning index for facet v1 vertex
  38775. var b1z = 0; // z partitioning index for facet v1 vertex
  38776. var b2x = 0; // X partitioning index for facet v2 vertex
  38777. var b2y = 0; // Y partitioning index for facet v2 vertex
  38778. var b2z = 0; // Z partitioning index for facet v2 vertex
  38779. var b3x = 0; // X partitioning index for facet v3 vertex
  38780. var b3y = 0; // Y partitioning index for facet v3 vertex
  38781. var b3z = 0; // Z partitioning index for facet v3 vertex
  38782. var block_idx_o = 0; // facet barycenter block index
  38783. var block_idx_v1 = 0; // v1 vertex block index
  38784. var block_idx_v2 = 0; // v2 vertex block index
  38785. var block_idx_v3 = 0; // v3 vertex block index
  38786. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38787. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38788. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38789. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38790. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38791. subSq = options.subDiv.max * options.subDiv.max;
  38792. options.facetPartitioning.length = 0;
  38793. }
  38794. // reset the normals
  38795. for (index = 0; index < positions.length; index++) {
  38796. normals[index] = 0.0;
  38797. }
  38798. // Loop : 1 indice triplet = 1 facet
  38799. var nbFaces = (indices.length / 3) | 0;
  38800. for (index = 0; index < nbFaces; index++) {
  38801. // get the indexes of the coordinates of each vertex of the facet
  38802. v1x = indices[index * 3] * 3;
  38803. v1y = v1x + 1;
  38804. v1z = v1x + 2;
  38805. v2x = indices[index * 3 + 1] * 3;
  38806. v2y = v2x + 1;
  38807. v2z = v2x + 2;
  38808. v3x = indices[index * 3 + 2] * 3;
  38809. v3y = v3x + 1;
  38810. v3z = v3x + 2;
  38811. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38812. p1p2y = positions[v1y] - positions[v2y];
  38813. p1p2z = positions[v1z] - positions[v2z];
  38814. p3p2x = positions[v3x] - positions[v2x];
  38815. p3p2y = positions[v3y] - positions[v2y];
  38816. p3p2z = positions[v3z] - positions[v2z];
  38817. // compute the face normal with the cross product
  38818. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38819. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38820. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38821. // normalize this normal and store it in the array facetData
  38822. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38823. length = (length === 0) ? 1.0 : length;
  38824. faceNormalx /= length;
  38825. faceNormaly /= length;
  38826. faceNormalz /= length;
  38827. if (computeFacetNormals && options) {
  38828. options.facetNormals[index].x = faceNormalx;
  38829. options.facetNormals[index].y = faceNormaly;
  38830. options.facetNormals[index].z = faceNormalz;
  38831. }
  38832. if (computeFacetPositions && options) {
  38833. // compute and the facet barycenter coordinates in the array facetPositions
  38834. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38835. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38836. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38837. }
  38838. if (computeFacetPartitioning && options) {
  38839. // store the facet indexes in arrays in the main facetPartitioning array :
  38840. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38841. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38842. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38843. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38844. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38845. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38846. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38847. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38848. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38849. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38850. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38851. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38852. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38853. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38854. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38855. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38856. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38857. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38858. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38859. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38860. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38861. // push each facet index in each block containing the vertex
  38862. options.facetPartitioning[block_idx_v1].push(index);
  38863. if (block_idx_v2 != block_idx_v1) {
  38864. options.facetPartitioning[block_idx_v2].push(index);
  38865. }
  38866. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38867. options.facetPartitioning[block_idx_v3].push(index);
  38868. }
  38869. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38870. options.facetPartitioning[block_idx_o].push(index);
  38871. }
  38872. }
  38873. if (computeDepthSort && options && options.facetPositions) {
  38874. var dsf = depthSortedFacets[index];
  38875. dsf.ind = index * 3;
  38876. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38877. }
  38878. // compute the normals anyway
  38879. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38880. normals[v1y] += faceNormaly;
  38881. normals[v1z] += faceNormalz;
  38882. normals[v2x] += faceNormalx;
  38883. normals[v2y] += faceNormaly;
  38884. normals[v2z] += faceNormalz;
  38885. normals[v3x] += faceNormalx;
  38886. normals[v3y] += faceNormaly;
  38887. normals[v3z] += faceNormalz;
  38888. }
  38889. // last normalization of each normal
  38890. for (index = 0; index < normals.length / 3; index++) {
  38891. faceNormalx = normals[index * 3];
  38892. faceNormaly = normals[index * 3 + 1];
  38893. faceNormalz = normals[index * 3 + 2];
  38894. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38895. length = (length === 0) ? 1.0 : length;
  38896. faceNormalx /= length;
  38897. faceNormaly /= length;
  38898. faceNormalz /= length;
  38899. normals[index * 3] = faceNormalx;
  38900. normals[index * 3 + 1] = faceNormaly;
  38901. normals[index * 3 + 2] = faceNormalz;
  38902. }
  38903. };
  38904. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38905. var li = indices.length;
  38906. var ln = normals.length;
  38907. var i;
  38908. var n;
  38909. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38910. switch (sideOrientation) {
  38911. case BABYLON.Mesh.FRONTSIDE:
  38912. // nothing changed
  38913. break;
  38914. case BABYLON.Mesh.BACKSIDE:
  38915. var tmp;
  38916. // indices
  38917. for (i = 0; i < li; i += 3) {
  38918. tmp = indices[i];
  38919. indices[i] = indices[i + 2];
  38920. indices[i + 2] = tmp;
  38921. }
  38922. // normals
  38923. for (n = 0; n < ln; n++) {
  38924. normals[n] = -normals[n];
  38925. }
  38926. break;
  38927. case BABYLON.Mesh.DOUBLESIDE:
  38928. // positions
  38929. var lp = positions.length;
  38930. var l = lp / 3;
  38931. for (var p = 0; p < lp; p++) {
  38932. positions[lp + p] = positions[p];
  38933. }
  38934. // indices
  38935. for (i = 0; i < li; i += 3) {
  38936. indices[i + li] = indices[i + 2] + l;
  38937. indices[i + 1 + li] = indices[i + 1] + l;
  38938. indices[i + 2 + li] = indices[i] + l;
  38939. }
  38940. // normals
  38941. for (n = 0; n < ln; n++) {
  38942. normals[ln + n] = -normals[n];
  38943. }
  38944. // uvs
  38945. var lu = uvs.length;
  38946. var u = 0;
  38947. for (u = 0; u < lu; u++) {
  38948. uvs[u + lu] = uvs[u];
  38949. }
  38950. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38951. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38952. u = 0;
  38953. for (i = 0; i < lu / 2; i++) {
  38954. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38955. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38956. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38957. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38958. u += 2;
  38959. }
  38960. break;
  38961. }
  38962. };
  38963. /**
  38964. * Applies VertexData created from the imported parameters to the geometry
  38965. * @param parsedVertexData the parsed data from an imported file
  38966. * @param geometry the geometry to apply the VertexData to
  38967. */
  38968. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38969. var vertexData = new VertexData();
  38970. // positions
  38971. var positions = parsedVertexData.positions;
  38972. if (positions) {
  38973. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38974. }
  38975. // normals
  38976. var normals = parsedVertexData.normals;
  38977. if (normals) {
  38978. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38979. }
  38980. // tangents
  38981. var tangents = parsedVertexData.tangents;
  38982. if (tangents) {
  38983. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38984. }
  38985. // uvs
  38986. var uvs = parsedVertexData.uvs;
  38987. if (uvs) {
  38988. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38989. }
  38990. // uv2s
  38991. var uv2s = parsedVertexData.uv2s;
  38992. if (uv2s) {
  38993. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38994. }
  38995. // uv3s
  38996. var uv3s = parsedVertexData.uv3s;
  38997. if (uv3s) {
  38998. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38999. }
  39000. // uv4s
  39001. var uv4s = parsedVertexData.uv4s;
  39002. if (uv4s) {
  39003. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39004. }
  39005. // uv5s
  39006. var uv5s = parsedVertexData.uv5s;
  39007. if (uv5s) {
  39008. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39009. }
  39010. // uv6s
  39011. var uv6s = parsedVertexData.uv6s;
  39012. if (uv6s) {
  39013. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39014. }
  39015. // colors
  39016. var colors = parsedVertexData.colors;
  39017. if (colors) {
  39018. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39019. }
  39020. // matricesIndices
  39021. var matricesIndices = parsedVertexData.matricesIndices;
  39022. if (matricesIndices) {
  39023. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39024. }
  39025. // matricesWeights
  39026. var matricesWeights = parsedVertexData.matricesWeights;
  39027. if (matricesWeights) {
  39028. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39029. }
  39030. // indices
  39031. var indices = parsedVertexData.indices;
  39032. if (indices) {
  39033. vertexData.indices = indices;
  39034. }
  39035. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39036. };
  39037. return VertexData;
  39038. }());
  39039. BABYLON.VertexData = VertexData;
  39040. })(BABYLON || (BABYLON = {}));
  39041. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39042. var BABYLON;
  39043. (function (BABYLON) {
  39044. /**
  39045. * Class used to store geometry data (vertex buffers + index buffer)
  39046. */
  39047. var Geometry = /** @class */ (function () {
  39048. /**
  39049. * Creates a new geometry
  39050. * @param id defines the unique ID
  39051. * @param scene defines the hosting scene
  39052. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39053. * @param updatable defines if geometry must be updatable (false by default)
  39054. * @param mesh defines the mesh that will be associated with the geometry
  39055. */
  39056. function Geometry(id, scene, vertexData, updatable, mesh) {
  39057. if (updatable === void 0) { updatable = false; }
  39058. if (mesh === void 0) { mesh = null; }
  39059. /**
  39060. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39061. */
  39062. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39063. this._totalVertices = 0;
  39064. this._isDisposed = false;
  39065. this._indexBufferIsUpdatable = false;
  39066. this.id = id;
  39067. this._engine = scene.getEngine();
  39068. this._meshes = [];
  39069. this._scene = scene;
  39070. //Init vertex buffer cache
  39071. this._vertexBuffers = {};
  39072. this._indices = [];
  39073. this._updatable = updatable;
  39074. // vertexData
  39075. if (vertexData) {
  39076. this.setAllVerticesData(vertexData, updatable);
  39077. }
  39078. else {
  39079. this._totalVertices = 0;
  39080. this._indices = [];
  39081. }
  39082. if (this._engine.getCaps().vertexArrayObject) {
  39083. this._vertexArrayObjects = {};
  39084. }
  39085. // applyToMesh
  39086. if (mesh) {
  39087. if (mesh.getClassName() === "LinesMesh") {
  39088. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39089. this._updateExtend();
  39090. }
  39091. this.applyToMesh(mesh);
  39092. mesh.computeWorldMatrix(true);
  39093. }
  39094. }
  39095. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39096. /**
  39097. * 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
  39098. */
  39099. get: function () {
  39100. return this._boundingBias;
  39101. },
  39102. /**
  39103. * 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
  39104. */
  39105. set: function (value) {
  39106. if (this._boundingBias && this._boundingBias.equals(value)) {
  39107. return;
  39108. }
  39109. this._boundingBias = value.clone();
  39110. this._updateBoundingInfo(true, null);
  39111. },
  39112. enumerable: true,
  39113. configurable: true
  39114. });
  39115. /**
  39116. * Static function used to attach a new empty geometry to a mesh
  39117. * @param mesh defines the mesh to attach the geometry to
  39118. * @returns the new {BABYLON.Geometry}
  39119. */
  39120. Geometry.CreateGeometryForMesh = function (mesh) {
  39121. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39122. geometry.applyToMesh(mesh);
  39123. return geometry;
  39124. };
  39125. Object.defineProperty(Geometry.prototype, "extend", {
  39126. /**
  39127. * Gets the current extend of the geometry
  39128. */
  39129. get: function () {
  39130. return this._extend;
  39131. },
  39132. enumerable: true,
  39133. configurable: true
  39134. });
  39135. /**
  39136. * Gets the hosting scene
  39137. * @returns the hosting {BABYLON.Scene}
  39138. */
  39139. Geometry.prototype.getScene = function () {
  39140. return this._scene;
  39141. };
  39142. /**
  39143. * Gets the hosting engine
  39144. * @returns the hosting {BABYLON.Engine}
  39145. */
  39146. Geometry.prototype.getEngine = function () {
  39147. return this._engine;
  39148. };
  39149. /**
  39150. * Defines if the geometry is ready to use
  39151. * @returns true if the geometry is ready to be used
  39152. */
  39153. Geometry.prototype.isReady = function () {
  39154. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39155. };
  39156. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39157. /**
  39158. * Gets a value indicating that the geometry should not be serialized
  39159. */
  39160. get: function () {
  39161. for (var index = 0; index < this._meshes.length; index++) {
  39162. if (!this._meshes[index].doNotSerialize) {
  39163. return false;
  39164. }
  39165. }
  39166. return true;
  39167. },
  39168. enumerable: true,
  39169. configurable: true
  39170. });
  39171. /** @hidden */
  39172. Geometry.prototype._rebuild = function () {
  39173. if (this._vertexArrayObjects) {
  39174. this._vertexArrayObjects = {};
  39175. }
  39176. // Index buffer
  39177. if (this._meshes.length !== 0 && this._indices) {
  39178. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39179. }
  39180. // Vertex buffers
  39181. for (var key in this._vertexBuffers) {
  39182. var vertexBuffer = this._vertexBuffers[key];
  39183. vertexBuffer._rebuild();
  39184. }
  39185. };
  39186. /**
  39187. * Affects all gemetry data in one call
  39188. * @param vertexData defines the geometry data
  39189. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39190. */
  39191. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39192. vertexData.applyToGeometry(this, updatable);
  39193. this.notifyUpdate();
  39194. };
  39195. /**
  39196. * Set specific vertex data
  39197. * @param kind defines the data kind (Position, normal, etc...)
  39198. * @param data defines the vertex data to use
  39199. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39200. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39201. */
  39202. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39203. if (updatable === void 0) { updatable = false; }
  39204. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39205. this.setVerticesBuffer(buffer);
  39206. };
  39207. /**
  39208. * Removes a specific vertex data
  39209. * @param kind defines the data kind (Position, normal, etc...)
  39210. */
  39211. Geometry.prototype.removeVerticesData = function (kind) {
  39212. if (this._vertexBuffers[kind]) {
  39213. this._vertexBuffers[kind].dispose();
  39214. delete this._vertexBuffers[kind];
  39215. }
  39216. };
  39217. /**
  39218. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39219. * @param buffer defines the vertex buffer to use
  39220. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39221. */
  39222. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39223. if (totalVertices === void 0) { totalVertices = null; }
  39224. var kind = buffer.getKind();
  39225. if (this._vertexBuffers[kind]) {
  39226. this._vertexBuffers[kind].dispose();
  39227. }
  39228. this._vertexBuffers[kind] = buffer;
  39229. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39230. var data = buffer.getData();
  39231. if (totalVertices != null) {
  39232. this._totalVertices = totalVertices;
  39233. }
  39234. else {
  39235. if (data != null) {
  39236. this._totalVertices = data.length / (buffer.byteStride / 4);
  39237. }
  39238. }
  39239. this._updateExtend(data);
  39240. this._resetPointsArrayCache();
  39241. var meshes = this._meshes;
  39242. var numOfMeshes = meshes.length;
  39243. for (var index = 0; index < numOfMeshes; index++) {
  39244. var mesh = meshes[index];
  39245. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39246. mesh._createGlobalSubMesh(false);
  39247. mesh.computeWorldMatrix(true);
  39248. }
  39249. }
  39250. this.notifyUpdate(kind);
  39251. if (this._vertexArrayObjects) {
  39252. this._disposeVertexArrayObjects();
  39253. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39254. }
  39255. };
  39256. /**
  39257. * Update a specific vertex buffer
  39258. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39259. * It will do nothing if the buffer is not updatable
  39260. * @param kind defines the data kind (Position, normal, etc...)
  39261. * @param data defines the data to use
  39262. * @param offset defines the offset in the target buffer where to store the data
  39263. * @param useBytes set to true if the offset is in bytes
  39264. */
  39265. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39266. if (useBytes === void 0) { useBytes = false; }
  39267. var vertexBuffer = this.getVertexBuffer(kind);
  39268. if (!vertexBuffer) {
  39269. return;
  39270. }
  39271. vertexBuffer.updateDirectly(data, offset, useBytes);
  39272. this.notifyUpdate(kind);
  39273. };
  39274. /**
  39275. * Update a specific vertex buffer
  39276. * This function will create a new buffer if the current one is not updatable
  39277. * @param kind defines the data kind (Position, normal, etc...)
  39278. * @param data defines the data to use
  39279. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39280. */
  39281. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39282. if (updateExtends === void 0) { updateExtends = false; }
  39283. var vertexBuffer = this.getVertexBuffer(kind);
  39284. if (!vertexBuffer) {
  39285. return;
  39286. }
  39287. vertexBuffer.update(data);
  39288. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39289. this._updateBoundingInfo(updateExtends, data);
  39290. }
  39291. this.notifyUpdate(kind);
  39292. };
  39293. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39294. if (updateExtends) {
  39295. this._updateExtend(data);
  39296. }
  39297. var meshes = this._meshes;
  39298. var numOfMeshes = meshes.length;
  39299. this._resetPointsArrayCache();
  39300. for (var index = 0; index < numOfMeshes; index++) {
  39301. var mesh = meshes[index];
  39302. if (updateExtends) {
  39303. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39304. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39305. var subMesh = mesh.subMeshes[subIndex];
  39306. subMesh.refreshBoundingInfo();
  39307. }
  39308. }
  39309. }
  39310. };
  39311. /** @hidden */
  39312. Geometry.prototype._bind = function (effect, indexToBind) {
  39313. if (!effect) {
  39314. return;
  39315. }
  39316. if (indexToBind === undefined) {
  39317. indexToBind = this._indexBuffer;
  39318. }
  39319. var vbs = this.getVertexBuffers();
  39320. if (!vbs) {
  39321. return;
  39322. }
  39323. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39324. this._engine.bindBuffers(vbs, indexToBind, effect);
  39325. return;
  39326. }
  39327. // Using VAO
  39328. if (!this._vertexArrayObjects[effect.key]) {
  39329. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39330. }
  39331. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39332. };
  39333. /**
  39334. * Gets total number of vertices
  39335. * @returns the total number of vertices
  39336. */
  39337. Geometry.prototype.getTotalVertices = function () {
  39338. if (!this.isReady()) {
  39339. return 0;
  39340. }
  39341. return this._totalVertices;
  39342. };
  39343. /**
  39344. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39345. * @param kind defines the data kind (Position, normal, etc...)
  39346. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39347. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39348. * @returns a float array containing vertex data
  39349. */
  39350. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39351. var vertexBuffer = this.getVertexBuffer(kind);
  39352. if (!vertexBuffer) {
  39353. return null;
  39354. }
  39355. var data = vertexBuffer.getData();
  39356. if (!data) {
  39357. return null;
  39358. }
  39359. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39360. var count = this._totalVertices * vertexBuffer.getSize();
  39361. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39362. var copy_1 = new Array(count);
  39363. vertexBuffer.forEach(count, function (value, index) {
  39364. copy_1[index] = value;
  39365. });
  39366. return copy_1;
  39367. }
  39368. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39369. if (data instanceof Array) {
  39370. var offset = vertexBuffer.byteOffset / 4;
  39371. return BABYLON.Tools.Slice(data, offset, offset + count);
  39372. }
  39373. else if (data instanceof ArrayBuffer) {
  39374. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39375. }
  39376. else {
  39377. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39378. }
  39379. }
  39380. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39381. return BABYLON.Tools.Slice(data);
  39382. }
  39383. return data;
  39384. };
  39385. /**
  39386. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39387. * @param kind defines the data kind (Position, normal, etc...)
  39388. * @returns true if the vertex buffer with the specified kind is updatable
  39389. */
  39390. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39391. var vb = this._vertexBuffers[kind];
  39392. if (!vb) {
  39393. return false;
  39394. }
  39395. return vb.isUpdatable();
  39396. };
  39397. /**
  39398. * Gets a specific vertex buffer
  39399. * @param kind defines the data kind (Position, normal, etc...)
  39400. * @returns a {BABYLON.VertexBuffer}
  39401. */
  39402. Geometry.prototype.getVertexBuffer = function (kind) {
  39403. if (!this.isReady()) {
  39404. return null;
  39405. }
  39406. return this._vertexBuffers[kind];
  39407. };
  39408. /**
  39409. * Returns all vertex buffers
  39410. * @return an object holding all vertex buffers indexed by kind
  39411. */
  39412. Geometry.prototype.getVertexBuffers = function () {
  39413. if (!this.isReady()) {
  39414. return null;
  39415. }
  39416. return this._vertexBuffers;
  39417. };
  39418. /**
  39419. * Gets a boolean indicating if specific vertex buffer is present
  39420. * @param kind defines the data kind (Position, normal, etc...)
  39421. * @returns true if data is present
  39422. */
  39423. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39424. if (!this._vertexBuffers) {
  39425. if (this._delayInfo) {
  39426. return this._delayInfo.indexOf(kind) !== -1;
  39427. }
  39428. return false;
  39429. }
  39430. return this._vertexBuffers[kind] !== undefined;
  39431. };
  39432. /**
  39433. * Gets a list of all attached data kinds (Position, normal, etc...)
  39434. * @returns a list of string containing all kinds
  39435. */
  39436. Geometry.prototype.getVerticesDataKinds = function () {
  39437. var result = [];
  39438. var kind;
  39439. if (!this._vertexBuffers && this._delayInfo) {
  39440. for (kind in this._delayInfo) {
  39441. result.push(kind);
  39442. }
  39443. }
  39444. else {
  39445. for (kind in this._vertexBuffers) {
  39446. result.push(kind);
  39447. }
  39448. }
  39449. return result;
  39450. };
  39451. /**
  39452. * Update index buffer
  39453. * @param indices defines the indices to store in the index buffer
  39454. * @param offset defines the offset in the target buffer where to store the data
  39455. */
  39456. Geometry.prototype.updateIndices = function (indices, offset) {
  39457. if (!this._indexBuffer) {
  39458. return;
  39459. }
  39460. if (!this._indexBufferIsUpdatable) {
  39461. this.setIndices(indices, null, true);
  39462. }
  39463. else {
  39464. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39465. }
  39466. };
  39467. /**
  39468. * Creates a new index buffer
  39469. * @param indices defines the indices to store in the index buffer
  39470. * @param totalVertices defines the total number of vertices (could be null)
  39471. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39472. */
  39473. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39474. if (totalVertices === void 0) { totalVertices = null; }
  39475. if (updatable === void 0) { updatable = false; }
  39476. if (this._indexBuffer) {
  39477. this._engine._releaseBuffer(this._indexBuffer);
  39478. }
  39479. this._disposeVertexArrayObjects();
  39480. this._indices = indices;
  39481. this._indexBufferIsUpdatable = updatable;
  39482. if (this._meshes.length !== 0 && this._indices) {
  39483. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39484. }
  39485. if (totalVertices != undefined) { // including null and undefined
  39486. this._totalVertices = totalVertices;
  39487. }
  39488. var meshes = this._meshes;
  39489. var numOfMeshes = meshes.length;
  39490. for (var index = 0; index < numOfMeshes; index++) {
  39491. meshes[index]._createGlobalSubMesh(true);
  39492. }
  39493. this.notifyUpdate();
  39494. };
  39495. /**
  39496. * Return the total number of indices
  39497. * @returns the total number of indices
  39498. */
  39499. Geometry.prototype.getTotalIndices = function () {
  39500. if (!this.isReady()) {
  39501. return 0;
  39502. }
  39503. return this._indices.length;
  39504. };
  39505. /**
  39506. * Gets the index buffer array
  39507. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39508. * @returns the index buffer array
  39509. */
  39510. Geometry.prototype.getIndices = function (copyWhenShared) {
  39511. if (!this.isReady()) {
  39512. return null;
  39513. }
  39514. var orig = this._indices;
  39515. if (!copyWhenShared || this._meshes.length === 1) {
  39516. return orig;
  39517. }
  39518. else {
  39519. var len = orig.length;
  39520. var copy = [];
  39521. for (var i = 0; i < len; i++) {
  39522. copy.push(orig[i]);
  39523. }
  39524. return copy;
  39525. }
  39526. };
  39527. /**
  39528. * Gets the index buffer
  39529. * @return the index buffer
  39530. */
  39531. Geometry.prototype.getIndexBuffer = function () {
  39532. if (!this.isReady()) {
  39533. return null;
  39534. }
  39535. return this._indexBuffer;
  39536. };
  39537. /** @hidden */
  39538. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39539. if (effect === void 0) { effect = null; }
  39540. if (!effect || !this._vertexArrayObjects) {
  39541. return;
  39542. }
  39543. if (this._vertexArrayObjects[effect.key]) {
  39544. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39545. delete this._vertexArrayObjects[effect.key];
  39546. }
  39547. };
  39548. /**
  39549. * Release the associated resources for a specific mesh
  39550. * @param mesh defines the source mesh
  39551. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39552. */
  39553. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39554. var meshes = this._meshes;
  39555. var index = meshes.indexOf(mesh);
  39556. if (index === -1) {
  39557. return;
  39558. }
  39559. meshes.splice(index, 1);
  39560. mesh._geometry = null;
  39561. if (meshes.length === 0 && shouldDispose) {
  39562. this.dispose();
  39563. }
  39564. };
  39565. /**
  39566. * Apply current geometry to a given mesh
  39567. * @param mesh defines the mesh to apply geometry to
  39568. */
  39569. Geometry.prototype.applyToMesh = function (mesh) {
  39570. if (mesh._geometry === this) {
  39571. return;
  39572. }
  39573. var previousGeometry = mesh._geometry;
  39574. if (previousGeometry) {
  39575. previousGeometry.releaseForMesh(mesh);
  39576. }
  39577. var meshes = this._meshes;
  39578. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39579. mesh._geometry = this;
  39580. this._scene.pushGeometry(this);
  39581. meshes.push(mesh);
  39582. if (this.isReady()) {
  39583. this._applyToMesh(mesh);
  39584. }
  39585. else {
  39586. mesh._boundingInfo = this._boundingInfo;
  39587. }
  39588. };
  39589. Geometry.prototype._updateExtend = function (data) {
  39590. if (data === void 0) { data = null; }
  39591. if (!data) {
  39592. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39593. }
  39594. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39595. };
  39596. Geometry.prototype._applyToMesh = function (mesh) {
  39597. var numOfMeshes = this._meshes.length;
  39598. // vertexBuffers
  39599. for (var kind in this._vertexBuffers) {
  39600. if (numOfMeshes === 1) {
  39601. this._vertexBuffers[kind].create();
  39602. }
  39603. var buffer = this._vertexBuffers[kind].getBuffer();
  39604. if (buffer)
  39605. buffer.references = numOfMeshes;
  39606. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39607. if (!this._extend) {
  39608. this._updateExtend();
  39609. }
  39610. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39611. mesh._createGlobalSubMesh(false);
  39612. //bounding info was just created again, world matrix should be applied again.
  39613. mesh._updateBoundingInfo();
  39614. }
  39615. }
  39616. // indexBuffer
  39617. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39618. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39619. }
  39620. if (this._indexBuffer) {
  39621. this._indexBuffer.references = numOfMeshes;
  39622. }
  39623. };
  39624. Geometry.prototype.notifyUpdate = function (kind) {
  39625. if (this.onGeometryUpdated) {
  39626. this.onGeometryUpdated(this, kind);
  39627. }
  39628. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39629. var mesh = _a[_i];
  39630. mesh._markSubMeshesAsAttributesDirty();
  39631. }
  39632. };
  39633. /**
  39634. * Load the geometry if it was flagged as delay loaded
  39635. * @param scene defines the hosting scene
  39636. * @param onLoaded defines a callback called when the geometry is loaded
  39637. */
  39638. Geometry.prototype.load = function (scene, onLoaded) {
  39639. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39640. return;
  39641. }
  39642. if (this.isReady()) {
  39643. if (onLoaded) {
  39644. onLoaded();
  39645. }
  39646. return;
  39647. }
  39648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39649. this._queueLoad(scene, onLoaded);
  39650. };
  39651. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39652. var _this = this;
  39653. if (!this.delayLoadingFile) {
  39654. return;
  39655. }
  39656. scene._addPendingData(this);
  39657. scene._loadFile(this.delayLoadingFile, function (data) {
  39658. if (!_this._delayLoadingFunction) {
  39659. return;
  39660. }
  39661. _this._delayLoadingFunction(JSON.parse(data), _this);
  39662. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39663. _this._delayInfo = [];
  39664. scene._removePendingData(_this);
  39665. var meshes = _this._meshes;
  39666. var numOfMeshes = meshes.length;
  39667. for (var index = 0; index < numOfMeshes; index++) {
  39668. _this._applyToMesh(meshes[index]);
  39669. }
  39670. if (onLoaded) {
  39671. onLoaded();
  39672. }
  39673. }, undefined, true);
  39674. };
  39675. /**
  39676. * Invert the geometry to move from a right handed system to a left handed one.
  39677. */
  39678. Geometry.prototype.toLeftHanded = function () {
  39679. // Flip faces
  39680. var tIndices = this.getIndices(false);
  39681. if (tIndices != null && tIndices.length > 0) {
  39682. for (var i = 0; i < tIndices.length; i += 3) {
  39683. var tTemp = tIndices[i + 0];
  39684. tIndices[i + 0] = tIndices[i + 2];
  39685. tIndices[i + 2] = tTemp;
  39686. }
  39687. this.setIndices(tIndices);
  39688. }
  39689. // Negate position.z
  39690. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39691. if (tPositions != null && tPositions.length > 0) {
  39692. for (var i = 0; i < tPositions.length; i += 3) {
  39693. tPositions[i + 2] = -tPositions[i + 2];
  39694. }
  39695. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39696. }
  39697. // Negate normal.z
  39698. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39699. if (tNormals != null && tNormals.length > 0) {
  39700. for (var i = 0; i < tNormals.length; i += 3) {
  39701. tNormals[i + 2] = -tNormals[i + 2];
  39702. }
  39703. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39704. }
  39705. };
  39706. // Cache
  39707. /** @hidden */
  39708. Geometry.prototype._resetPointsArrayCache = function () {
  39709. this._positions = null;
  39710. };
  39711. /** @hidden */
  39712. Geometry.prototype._generatePointsArray = function () {
  39713. if (this._positions)
  39714. return true;
  39715. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39716. if (!data || data.length === 0) {
  39717. return false;
  39718. }
  39719. this._positions = [];
  39720. for (var index = 0; index < data.length; index += 3) {
  39721. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39722. }
  39723. return true;
  39724. };
  39725. /**
  39726. * Gets a value indicating if the geometry is disposed
  39727. * @returns true if the geometry was disposed
  39728. */
  39729. Geometry.prototype.isDisposed = function () {
  39730. return this._isDisposed;
  39731. };
  39732. Geometry.prototype._disposeVertexArrayObjects = function () {
  39733. if (this._vertexArrayObjects) {
  39734. for (var kind in this._vertexArrayObjects) {
  39735. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39736. }
  39737. this._vertexArrayObjects = {};
  39738. }
  39739. };
  39740. /**
  39741. * Free all associated resources
  39742. */
  39743. Geometry.prototype.dispose = function () {
  39744. var meshes = this._meshes;
  39745. var numOfMeshes = meshes.length;
  39746. var index;
  39747. for (index = 0; index < numOfMeshes; index++) {
  39748. this.releaseForMesh(meshes[index]);
  39749. }
  39750. this._meshes = [];
  39751. this._disposeVertexArrayObjects();
  39752. for (var kind in this._vertexBuffers) {
  39753. this._vertexBuffers[kind].dispose();
  39754. }
  39755. this._vertexBuffers = {};
  39756. this._totalVertices = 0;
  39757. if (this._indexBuffer) {
  39758. this._engine._releaseBuffer(this._indexBuffer);
  39759. }
  39760. this._indexBuffer = null;
  39761. this._indices = [];
  39762. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39763. this.delayLoadingFile = null;
  39764. this._delayLoadingFunction = null;
  39765. this._delayInfo = [];
  39766. this._boundingInfo = null;
  39767. this._scene.removeGeometry(this);
  39768. this._isDisposed = true;
  39769. };
  39770. /**
  39771. * Clone the current geometry into a new geometry
  39772. * @param id defines the unique ID of the new geometry
  39773. * @returns a new geometry object
  39774. */
  39775. Geometry.prototype.copy = function (id) {
  39776. var vertexData = new BABYLON.VertexData();
  39777. vertexData.indices = [];
  39778. var indices = this.getIndices();
  39779. if (indices) {
  39780. for (var index = 0; index < indices.length; index++) {
  39781. vertexData.indices.push(indices[index]);
  39782. }
  39783. }
  39784. var updatable = false;
  39785. var stopChecking = false;
  39786. var kind;
  39787. for (kind in this._vertexBuffers) {
  39788. // using slice() to make a copy of the array and not just reference it
  39789. var data = this.getVerticesData(kind);
  39790. if (data instanceof Float32Array) {
  39791. vertexData.set(new Float32Array(data), kind);
  39792. }
  39793. else {
  39794. vertexData.set(data.slice(0), kind);
  39795. }
  39796. if (!stopChecking) {
  39797. var vb = this.getVertexBuffer(kind);
  39798. if (vb) {
  39799. updatable = vb.isUpdatable();
  39800. stopChecking = !updatable;
  39801. }
  39802. }
  39803. }
  39804. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39805. geometry.delayLoadState = this.delayLoadState;
  39806. geometry.delayLoadingFile = this.delayLoadingFile;
  39807. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39808. for (kind in this._delayInfo) {
  39809. geometry._delayInfo = geometry._delayInfo || [];
  39810. geometry._delayInfo.push(kind);
  39811. }
  39812. // Bounding info
  39813. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39814. return geometry;
  39815. };
  39816. /**
  39817. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39818. * @return a JSON representation of the current geometry data (without the vertices data)
  39819. */
  39820. Geometry.prototype.serialize = function () {
  39821. var serializationObject = {};
  39822. serializationObject.id = this.id;
  39823. serializationObject.updatable = this._updatable;
  39824. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39825. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39826. }
  39827. return serializationObject;
  39828. };
  39829. Geometry.prototype.toNumberArray = function (origin) {
  39830. if (Array.isArray(origin)) {
  39831. return origin;
  39832. }
  39833. else {
  39834. return Array.prototype.slice.call(origin);
  39835. }
  39836. };
  39837. /**
  39838. * Serialize all vertices data into a JSON oject
  39839. * @returns a JSON representation of the current geometry data
  39840. */
  39841. Geometry.prototype.serializeVerticeData = function () {
  39842. var serializationObject = this.serialize();
  39843. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39844. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39845. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39846. serializationObject.positions._updatable = true;
  39847. }
  39848. }
  39849. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39850. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39851. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39852. serializationObject.normals._updatable = true;
  39853. }
  39854. }
  39855. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39856. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39857. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39858. serializationObject.tangets._updatable = true;
  39859. }
  39860. }
  39861. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39862. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39863. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39864. serializationObject.uvs._updatable = true;
  39865. }
  39866. }
  39867. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39868. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39869. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39870. serializationObject.uv2s._updatable = true;
  39871. }
  39872. }
  39873. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39874. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39875. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39876. serializationObject.uv3s._updatable = true;
  39877. }
  39878. }
  39879. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39880. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39881. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39882. serializationObject.uv4s._updatable = true;
  39883. }
  39884. }
  39885. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39886. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39887. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39888. serializationObject.uv5s._updatable = true;
  39889. }
  39890. }
  39891. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39892. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39893. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39894. serializationObject.uv6s._updatable = true;
  39895. }
  39896. }
  39897. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39898. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39899. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39900. serializationObject.colors._updatable = true;
  39901. }
  39902. }
  39903. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39904. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39905. serializationObject.matricesIndices._isExpanded = true;
  39906. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39907. serializationObject.matricesIndices._updatable = true;
  39908. }
  39909. }
  39910. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39911. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39912. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39913. serializationObject.matricesWeights._updatable = true;
  39914. }
  39915. }
  39916. serializationObject.indices = this.toNumberArray(this.getIndices());
  39917. return serializationObject;
  39918. };
  39919. // Statics
  39920. /**
  39921. * Extracts a clone of a mesh geometry
  39922. * @param mesh defines the source mesh
  39923. * @param id defines the unique ID of the new geometry object
  39924. * @returns the new geometry object
  39925. */
  39926. Geometry.ExtractFromMesh = function (mesh, id) {
  39927. var geometry = mesh._geometry;
  39928. if (!geometry) {
  39929. return null;
  39930. }
  39931. return geometry.copy(id);
  39932. };
  39933. /**
  39934. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39935. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39936. * Be aware Math.random() could cause collisions, but:
  39937. * "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"
  39938. * @returns a string containing a new GUID
  39939. */
  39940. Geometry.RandomId = function () {
  39941. return BABYLON.Tools.RandomId();
  39942. };
  39943. /** @hidden */
  39944. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39945. var scene = mesh.getScene();
  39946. // Geometry
  39947. var geometryId = parsedGeometry.geometryId;
  39948. if (geometryId) {
  39949. var geometry = scene.getGeometryByID(geometryId);
  39950. if (geometry) {
  39951. geometry.applyToMesh(mesh);
  39952. }
  39953. }
  39954. else if (parsedGeometry instanceof ArrayBuffer) {
  39955. var binaryInfo = mesh._binaryInfo;
  39956. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39957. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39958. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39959. }
  39960. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39961. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39963. }
  39964. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39965. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39966. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39967. }
  39968. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39969. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39971. }
  39972. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39973. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39974. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39975. }
  39976. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39977. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39978. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39979. }
  39980. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39981. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39982. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39983. }
  39984. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39985. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39986. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39987. }
  39988. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39989. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39990. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39991. }
  39992. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39993. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39994. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39995. }
  39996. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39997. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39998. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39999. }
  40000. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40001. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40002. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40003. }
  40004. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40005. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40006. mesh.setIndices(indicesData, null);
  40007. }
  40008. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40009. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40010. mesh.subMeshes = [];
  40011. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40012. var materialIndex = subMeshesData[(i * 5) + 0];
  40013. var verticesStart = subMeshesData[(i * 5) + 1];
  40014. var verticesCount = subMeshesData[(i * 5) + 2];
  40015. var indexStart = subMeshesData[(i * 5) + 3];
  40016. var indexCount = subMeshesData[(i * 5) + 4];
  40017. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40018. }
  40019. }
  40020. }
  40021. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40022. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40023. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40024. if (parsedGeometry.tangents) {
  40025. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40026. }
  40027. if (parsedGeometry.uvs) {
  40028. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40029. }
  40030. if (parsedGeometry.uvs2) {
  40031. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40032. }
  40033. if (parsedGeometry.uvs3) {
  40034. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40035. }
  40036. if (parsedGeometry.uvs4) {
  40037. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40038. }
  40039. if (parsedGeometry.uvs5) {
  40040. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40041. }
  40042. if (parsedGeometry.uvs6) {
  40043. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40044. }
  40045. if (parsedGeometry.colors) {
  40046. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40047. }
  40048. if (parsedGeometry.matricesIndices) {
  40049. if (!parsedGeometry.matricesIndices._isExpanded) {
  40050. var floatIndices = [];
  40051. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40052. var matricesIndex = parsedGeometry.matricesIndices[i];
  40053. floatIndices.push(matricesIndex & 0x000000FF);
  40054. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40055. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40056. floatIndices.push(matricesIndex >> 24);
  40057. }
  40058. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40059. }
  40060. else {
  40061. delete parsedGeometry.matricesIndices._isExpanded;
  40062. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40063. }
  40064. }
  40065. if (parsedGeometry.matricesIndicesExtra) {
  40066. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40067. var floatIndices = [];
  40068. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40069. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40070. floatIndices.push(matricesIndex & 0x000000FF);
  40071. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40072. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40073. floatIndices.push(matricesIndex >> 24);
  40074. }
  40075. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40076. }
  40077. else {
  40078. delete parsedGeometry.matricesIndices._isExpanded;
  40079. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40080. }
  40081. }
  40082. if (parsedGeometry.matricesWeights) {
  40083. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40084. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40085. }
  40086. if (parsedGeometry.matricesWeightsExtra) {
  40087. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40088. }
  40089. mesh.setIndices(parsedGeometry.indices, null);
  40090. }
  40091. // SubMeshes
  40092. if (parsedGeometry.subMeshes) {
  40093. mesh.subMeshes = [];
  40094. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40095. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40096. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40097. }
  40098. }
  40099. // Flat shading
  40100. if (mesh._shouldGenerateFlatShading) {
  40101. mesh.convertToFlatShadedMesh();
  40102. delete mesh._shouldGenerateFlatShading;
  40103. }
  40104. // Update
  40105. mesh.computeWorldMatrix(true);
  40106. // Octree
  40107. var sceneOctree = scene.selectionOctree;
  40108. if (sceneOctree !== undefined && sceneOctree !== null) {
  40109. sceneOctree.addMesh(mesh);
  40110. }
  40111. };
  40112. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40113. var epsilon = 1e-3;
  40114. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40115. return;
  40116. }
  40117. var noInfluenceBoneIndex = 0.0;
  40118. if (parsedGeometry.skeletonId > -1) {
  40119. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40120. if (!skeleton) {
  40121. return;
  40122. }
  40123. noInfluenceBoneIndex = skeleton.bones.length;
  40124. }
  40125. else {
  40126. return;
  40127. }
  40128. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40129. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40130. var matricesWeights = parsedGeometry.matricesWeights;
  40131. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40132. var influencers = parsedGeometry.numBoneInfluencer;
  40133. var size = matricesWeights.length;
  40134. for (var i = 0; i < size; i += 4) {
  40135. var weight = 0.0;
  40136. var firstZeroWeight = -1;
  40137. for (var j = 0; j < 4; j++) {
  40138. var w = matricesWeights[i + j];
  40139. weight += w;
  40140. if (w < epsilon && firstZeroWeight < 0) {
  40141. firstZeroWeight = j;
  40142. }
  40143. }
  40144. if (matricesWeightsExtra) {
  40145. for (var j = 0; j < 4; j++) {
  40146. var w = matricesWeightsExtra[i + j];
  40147. weight += w;
  40148. if (w < epsilon && firstZeroWeight < 0) {
  40149. firstZeroWeight = j + 4;
  40150. }
  40151. }
  40152. }
  40153. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40154. firstZeroWeight = influencers - 1;
  40155. }
  40156. if (weight > epsilon) {
  40157. var mweight = 1.0 / weight;
  40158. for (var j = 0; j < 4; j++) {
  40159. matricesWeights[i + j] *= mweight;
  40160. }
  40161. if (matricesWeightsExtra) {
  40162. for (var j = 0; j < 4; j++) {
  40163. matricesWeightsExtra[i + j] *= mweight;
  40164. }
  40165. }
  40166. }
  40167. else {
  40168. if (firstZeroWeight >= 4) {
  40169. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40170. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40171. }
  40172. else {
  40173. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40174. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40175. }
  40176. }
  40177. }
  40178. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40179. if (parsedGeometry.matricesWeightsExtra) {
  40180. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40181. }
  40182. };
  40183. /**
  40184. * Create a new geometry from persisted data (Using .babylon file format)
  40185. * @param parsedVertexData defines the persisted data
  40186. * @param scene defines the hosting scene
  40187. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40188. * @returns the new geometry object
  40189. */
  40190. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40191. if (scene.getGeometryByID(parsedVertexData.id)) {
  40192. return null; // null since geometry could be something else than a box...
  40193. }
  40194. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40195. if (BABYLON.Tags) {
  40196. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40197. }
  40198. if (parsedVertexData.delayLoadingFile) {
  40199. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40200. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40201. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40202. geometry._delayInfo = [];
  40203. if (parsedVertexData.hasUVs) {
  40204. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40205. }
  40206. if (parsedVertexData.hasUVs2) {
  40207. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40208. }
  40209. if (parsedVertexData.hasUVs3) {
  40210. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40211. }
  40212. if (parsedVertexData.hasUVs4) {
  40213. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40214. }
  40215. if (parsedVertexData.hasUVs5) {
  40216. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40217. }
  40218. if (parsedVertexData.hasUVs6) {
  40219. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40220. }
  40221. if (parsedVertexData.hasColors) {
  40222. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40223. }
  40224. if (parsedVertexData.hasMatricesIndices) {
  40225. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40226. }
  40227. if (parsedVertexData.hasMatricesWeights) {
  40228. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40229. }
  40230. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40231. }
  40232. else {
  40233. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40234. }
  40235. scene.pushGeometry(geometry, true);
  40236. return geometry;
  40237. };
  40238. return Geometry;
  40239. }());
  40240. BABYLON.Geometry = Geometry;
  40241. // Primitives
  40242. /// Abstract class
  40243. /**
  40244. * Abstract class used to provide common services for all typed geometries
  40245. * @hidden
  40246. */
  40247. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40248. __extends(_PrimitiveGeometry, _super);
  40249. /**
  40250. * Creates a new typed geometry
  40251. * @param id defines the unique ID of the geometry
  40252. * @param scene defines the hosting scene
  40253. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40254. * @param mesh defines the hosting mesh (can be null)
  40255. */
  40256. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40257. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40258. if (mesh === void 0) { mesh = null; }
  40259. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40260. _this._canBeRegenerated = _canBeRegenerated;
  40261. _this._beingRegenerated = true;
  40262. _this.regenerate();
  40263. _this._beingRegenerated = false;
  40264. return _this;
  40265. }
  40266. /**
  40267. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40268. * @returns true if the geometry can be regenerated
  40269. */
  40270. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40271. return this._canBeRegenerated;
  40272. };
  40273. /**
  40274. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40275. */
  40276. _PrimitiveGeometry.prototype.regenerate = function () {
  40277. if (!this._canBeRegenerated) {
  40278. return;
  40279. }
  40280. this._beingRegenerated = true;
  40281. this.setAllVerticesData(this._regenerateVertexData(), false);
  40282. this._beingRegenerated = false;
  40283. };
  40284. /**
  40285. * Clone the geometry
  40286. * @param id defines the unique ID of the new geometry
  40287. * @returns the new geometry
  40288. */
  40289. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40290. return _super.prototype.copy.call(this, id);
  40291. };
  40292. // overrides
  40293. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40294. if (!this._beingRegenerated) {
  40295. return;
  40296. }
  40297. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40298. };
  40299. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40300. if (!this._beingRegenerated) {
  40301. return;
  40302. }
  40303. _super.prototype.setVerticesData.call(this, kind, data, false);
  40304. };
  40305. // to override
  40306. /** @hidden */
  40307. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40308. throw new Error("Abstract method");
  40309. };
  40310. _PrimitiveGeometry.prototype.copy = function (id) {
  40311. throw new Error("Must be overriden in sub-classes.");
  40312. };
  40313. _PrimitiveGeometry.prototype.serialize = function () {
  40314. var serializationObject = _super.prototype.serialize.call(this);
  40315. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40316. return serializationObject;
  40317. };
  40318. return _PrimitiveGeometry;
  40319. }(Geometry));
  40320. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40321. /**
  40322. * Creates a ribbon geometry
  40323. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40324. */
  40325. var RibbonGeometry = /** @class */ (function (_super) {
  40326. __extends(RibbonGeometry, _super);
  40327. /**
  40328. * Creates a ribbon geometry
  40329. * @param id defines the unique ID of the geometry
  40330. * @param scene defines the hosting scene
  40331. * @param pathArray defines the array of paths to use
  40332. * @param closeArray defines if the last path and the first path must be joined
  40333. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40334. * @param offset defines the offset between points
  40335. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40336. * @param mesh defines the hosting mesh (can be null)
  40337. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40338. */
  40339. function RibbonGeometry(id, scene,
  40340. /**
  40341. * Defines the array of paths to use
  40342. */
  40343. pathArray,
  40344. /**
  40345. * Defines if the last and first points of each path in your pathArray must be joined
  40346. */
  40347. closeArray,
  40348. /**
  40349. * Defines if the last and first points of each path in your pathArray must be joined
  40350. */
  40351. closePath,
  40352. /**
  40353. * Defines the offset between points
  40354. */
  40355. offset, canBeRegenerated, mesh,
  40356. /**
  40357. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40358. */
  40359. side) {
  40360. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40361. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40362. _this.pathArray = pathArray;
  40363. _this.closeArray = closeArray;
  40364. _this.closePath = closePath;
  40365. _this.offset = offset;
  40366. _this.side = side;
  40367. return _this;
  40368. }
  40369. /** @hidden */
  40370. RibbonGeometry.prototype._regenerateVertexData = function () {
  40371. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40372. };
  40373. RibbonGeometry.prototype.copy = function (id) {
  40374. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40375. };
  40376. return RibbonGeometry;
  40377. }(_PrimitiveGeometry));
  40378. BABYLON.RibbonGeometry = RibbonGeometry;
  40379. /**
  40380. * Creates a box geometry
  40381. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40382. */
  40383. var BoxGeometry = /** @class */ (function (_super) {
  40384. __extends(BoxGeometry, _super);
  40385. /**
  40386. * Creates a box geometry
  40387. * @param id defines the unique ID of the geometry
  40388. * @param scene defines the hosting scene
  40389. * @param size defines the zise of the box (width, height and depth are the same)
  40390. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40391. * @param mesh defines the hosting mesh (can be null)
  40392. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40393. */
  40394. function BoxGeometry(id, scene,
  40395. /**
  40396. * Defines the zise of the box (width, height and depth are the same)
  40397. */
  40398. size, canBeRegenerated, mesh,
  40399. /**
  40400. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40401. */
  40402. side) {
  40403. if (mesh === void 0) { mesh = null; }
  40404. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40405. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40406. _this.size = size;
  40407. _this.side = side;
  40408. return _this;
  40409. }
  40410. BoxGeometry.prototype._regenerateVertexData = function () {
  40411. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40412. };
  40413. BoxGeometry.prototype.copy = function (id) {
  40414. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40415. };
  40416. BoxGeometry.prototype.serialize = function () {
  40417. var serializationObject = _super.prototype.serialize.call(this);
  40418. serializationObject.size = this.size;
  40419. return serializationObject;
  40420. };
  40421. BoxGeometry.Parse = function (parsedBox, scene) {
  40422. if (scene.getGeometryByID(parsedBox.id)) {
  40423. return null; // null since geometry could be something else than a box...
  40424. }
  40425. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40426. if (BABYLON.Tags) {
  40427. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40428. }
  40429. scene.pushGeometry(box, true);
  40430. return box;
  40431. };
  40432. return BoxGeometry;
  40433. }(_PrimitiveGeometry));
  40434. BABYLON.BoxGeometry = BoxGeometry;
  40435. /**
  40436. * Creates a sphere geometry
  40437. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40438. */
  40439. var SphereGeometry = /** @class */ (function (_super) {
  40440. __extends(SphereGeometry, _super);
  40441. /**
  40442. * Create a new sphere geometry
  40443. * @param id defines the unique ID of the geometry
  40444. * @param scene defines the hosting scene
  40445. * @param segments defines the number of segments to use to create the sphere
  40446. * @param diameter defines the diameter of the sphere
  40447. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40448. * @param mesh defines the hosting mesh (can be null)
  40449. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40450. */
  40451. function SphereGeometry(id, scene,
  40452. /**
  40453. * Defines the number of segments to use to create the sphere
  40454. */
  40455. segments,
  40456. /**
  40457. * Defines the diameter of the sphere
  40458. */
  40459. diameter, canBeRegenerated, mesh,
  40460. /**
  40461. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40462. */
  40463. side) {
  40464. if (mesh === void 0) { mesh = null; }
  40465. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40466. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40467. _this.segments = segments;
  40468. _this.diameter = diameter;
  40469. _this.side = side;
  40470. return _this;
  40471. }
  40472. SphereGeometry.prototype._regenerateVertexData = function () {
  40473. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40474. };
  40475. SphereGeometry.prototype.copy = function (id) {
  40476. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40477. };
  40478. SphereGeometry.prototype.serialize = function () {
  40479. var serializationObject = _super.prototype.serialize.call(this);
  40480. serializationObject.segments = this.segments;
  40481. serializationObject.diameter = this.diameter;
  40482. return serializationObject;
  40483. };
  40484. SphereGeometry.Parse = function (parsedSphere, scene) {
  40485. if (scene.getGeometryByID(parsedSphere.id)) {
  40486. return null; // null since geometry could be something else than a sphere...
  40487. }
  40488. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40489. if (BABYLON.Tags) {
  40490. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40491. }
  40492. scene.pushGeometry(sphere, true);
  40493. return sphere;
  40494. };
  40495. return SphereGeometry;
  40496. }(_PrimitiveGeometry));
  40497. BABYLON.SphereGeometry = SphereGeometry;
  40498. /**
  40499. * Creates a disc geometry
  40500. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40501. */
  40502. var DiscGeometry = /** @class */ (function (_super) {
  40503. __extends(DiscGeometry, _super);
  40504. /**
  40505. * Creates a new disc geometry
  40506. * @param id defines the unique ID of the geometry
  40507. * @param scene defines the hosting scene
  40508. * @param radius defines the radius of the disc
  40509. * @param tessellation defines the tesselation factor to apply to the disc
  40510. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40511. * @param mesh defines the hosting mesh (can be null)
  40512. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40513. */
  40514. function DiscGeometry(id, scene,
  40515. /**
  40516. * Defines the radius of the disc
  40517. */
  40518. radius,
  40519. /**
  40520. * Defines the tesselation factor to apply to the disc
  40521. */
  40522. tessellation, canBeRegenerated, mesh,
  40523. /**
  40524. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40525. */
  40526. side) {
  40527. if (mesh === void 0) { mesh = null; }
  40528. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40529. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40530. _this.radius = radius;
  40531. _this.tessellation = tessellation;
  40532. _this.side = side;
  40533. return _this;
  40534. }
  40535. DiscGeometry.prototype._regenerateVertexData = function () {
  40536. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40537. };
  40538. DiscGeometry.prototype.copy = function (id) {
  40539. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40540. };
  40541. return DiscGeometry;
  40542. }(_PrimitiveGeometry));
  40543. BABYLON.DiscGeometry = DiscGeometry;
  40544. /**
  40545. * Creates a new cylinder geometry
  40546. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40547. */
  40548. var CylinderGeometry = /** @class */ (function (_super) {
  40549. __extends(CylinderGeometry, _super);
  40550. /**
  40551. * Creates a new cylinder geometry
  40552. * @param id defines the unique ID of the geometry
  40553. * @param scene defines the hosting scene
  40554. * @param height defines the height of the cylinder
  40555. * @param diameterTop defines the diameter of the cylinder's top cap
  40556. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40557. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40558. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40559. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40560. * @param mesh defines the hosting mesh (can be null)
  40561. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40562. */
  40563. function CylinderGeometry(id, scene,
  40564. /**
  40565. * Defines the height of the cylinder
  40566. */
  40567. height,
  40568. /**
  40569. * Defines the diameter of the cylinder's top cap
  40570. */
  40571. diameterTop,
  40572. /**
  40573. * Defines the diameter of the cylinder's bottom cap
  40574. */
  40575. diameterBottom,
  40576. /**
  40577. * Defines the tessellation factor to apply to the cylinder
  40578. */
  40579. tessellation,
  40580. /**
  40581. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40582. */
  40583. subdivisions, canBeRegenerated, mesh,
  40584. /**
  40585. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40586. */
  40587. side) {
  40588. if (subdivisions === void 0) { subdivisions = 1; }
  40589. if (mesh === void 0) { mesh = null; }
  40590. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40591. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40592. _this.height = height;
  40593. _this.diameterTop = diameterTop;
  40594. _this.diameterBottom = diameterBottom;
  40595. _this.tessellation = tessellation;
  40596. _this.subdivisions = subdivisions;
  40597. _this.side = side;
  40598. return _this;
  40599. }
  40600. CylinderGeometry.prototype._regenerateVertexData = function () {
  40601. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40602. };
  40603. CylinderGeometry.prototype.copy = function (id) {
  40604. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40605. };
  40606. CylinderGeometry.prototype.serialize = function () {
  40607. var serializationObject = _super.prototype.serialize.call(this);
  40608. serializationObject.height = this.height;
  40609. serializationObject.diameterTop = this.diameterTop;
  40610. serializationObject.diameterBottom = this.diameterBottom;
  40611. serializationObject.tessellation = this.tessellation;
  40612. return serializationObject;
  40613. };
  40614. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40615. if (scene.getGeometryByID(parsedCylinder.id)) {
  40616. return null; // null since geometry could be something else than a cylinder...
  40617. }
  40618. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40619. if (BABYLON.Tags) {
  40620. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40621. }
  40622. scene.pushGeometry(cylinder, true);
  40623. return cylinder;
  40624. };
  40625. return CylinderGeometry;
  40626. }(_PrimitiveGeometry));
  40627. BABYLON.CylinderGeometry = CylinderGeometry;
  40628. /**
  40629. * Creates a new torus geometry
  40630. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40631. */
  40632. var TorusGeometry = /** @class */ (function (_super) {
  40633. __extends(TorusGeometry, _super);
  40634. /**
  40635. * Creates a new torus geometry
  40636. * @param id defines the unique ID of the geometry
  40637. * @param scene defines the hosting scene
  40638. * @param diameter defines the diameter of the torus
  40639. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40640. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40641. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40642. * @param mesh defines the hosting mesh (can be null)
  40643. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40644. */
  40645. function TorusGeometry(id, scene,
  40646. /**
  40647. * Defines the diameter of the torus
  40648. */
  40649. diameter,
  40650. /**
  40651. * Defines the thickness of the torus (ie. internal diameter)
  40652. */
  40653. thickness,
  40654. /**
  40655. * Defines the tesselation factor to apply to the torus
  40656. */
  40657. tessellation, canBeRegenerated, mesh,
  40658. /**
  40659. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40660. */
  40661. side) {
  40662. if (mesh === void 0) { mesh = null; }
  40663. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40664. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40665. _this.diameter = diameter;
  40666. _this.thickness = thickness;
  40667. _this.tessellation = tessellation;
  40668. _this.side = side;
  40669. return _this;
  40670. }
  40671. TorusGeometry.prototype._regenerateVertexData = function () {
  40672. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40673. };
  40674. TorusGeometry.prototype.copy = function (id) {
  40675. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40676. };
  40677. TorusGeometry.prototype.serialize = function () {
  40678. var serializationObject = _super.prototype.serialize.call(this);
  40679. serializationObject.diameter = this.diameter;
  40680. serializationObject.thickness = this.thickness;
  40681. serializationObject.tessellation = this.tessellation;
  40682. return serializationObject;
  40683. };
  40684. TorusGeometry.Parse = function (parsedTorus, scene) {
  40685. if (scene.getGeometryByID(parsedTorus.id)) {
  40686. return null; // null since geometry could be something else than a torus...
  40687. }
  40688. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40689. if (BABYLON.Tags) {
  40690. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40691. }
  40692. scene.pushGeometry(torus, true);
  40693. return torus;
  40694. };
  40695. return TorusGeometry;
  40696. }(_PrimitiveGeometry));
  40697. BABYLON.TorusGeometry = TorusGeometry;
  40698. /**
  40699. * Creates a new ground geometry
  40700. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40701. */
  40702. var GroundGeometry = /** @class */ (function (_super) {
  40703. __extends(GroundGeometry, _super);
  40704. /**
  40705. * Creates a new ground geometry
  40706. * @param id defines the unique ID of the geometry
  40707. * @param scene defines the hosting scene
  40708. * @param width defines the width of the ground
  40709. * @param height defines the height of the ground
  40710. * @param subdivisions defines the subdivisions to apply to the ground
  40711. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40712. * @param mesh defines the hosting mesh (can be null)
  40713. */
  40714. function GroundGeometry(id, scene,
  40715. /**
  40716. * Defines the width of the ground
  40717. */
  40718. width,
  40719. /**
  40720. * Defines the height of the ground
  40721. */
  40722. height,
  40723. /**
  40724. * Defines the subdivisions to apply to the ground
  40725. */
  40726. subdivisions, canBeRegenerated, mesh) {
  40727. if (mesh === void 0) { mesh = null; }
  40728. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40729. _this.width = width;
  40730. _this.height = height;
  40731. _this.subdivisions = subdivisions;
  40732. return _this;
  40733. }
  40734. GroundGeometry.prototype._regenerateVertexData = function () {
  40735. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40736. };
  40737. GroundGeometry.prototype.copy = function (id) {
  40738. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40739. };
  40740. GroundGeometry.prototype.serialize = function () {
  40741. var serializationObject = _super.prototype.serialize.call(this);
  40742. serializationObject.width = this.width;
  40743. serializationObject.height = this.height;
  40744. serializationObject.subdivisions = this.subdivisions;
  40745. return serializationObject;
  40746. };
  40747. GroundGeometry.Parse = function (parsedGround, scene) {
  40748. if (scene.getGeometryByID(parsedGround.id)) {
  40749. return null; // null since geometry could be something else than a ground...
  40750. }
  40751. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40752. if (BABYLON.Tags) {
  40753. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40754. }
  40755. scene.pushGeometry(ground, true);
  40756. return ground;
  40757. };
  40758. return GroundGeometry;
  40759. }(_PrimitiveGeometry));
  40760. BABYLON.GroundGeometry = GroundGeometry;
  40761. /**
  40762. * Creates a tiled ground geometry
  40763. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40764. */
  40765. var TiledGroundGeometry = /** @class */ (function (_super) {
  40766. __extends(TiledGroundGeometry, _super);
  40767. /**
  40768. * Creates a tiled ground geometry
  40769. * @param id defines the unique ID of the geometry
  40770. * @param scene defines the hosting scene
  40771. * @param xmin defines the minimum value on X axis
  40772. * @param zmin defines the minimum value on Z axis
  40773. * @param xmax defines the maximum value on X axis
  40774. * @param zmax defines the maximum value on Z axis
  40775. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40776. * @param precision defines the precision to use when computing the tiles
  40777. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40778. * @param mesh defines the hosting mesh (can be null)
  40779. */
  40780. function TiledGroundGeometry(id, scene,
  40781. /**
  40782. * Defines the minimum value on X axis
  40783. */
  40784. xmin,
  40785. /**
  40786. * Defines the minimum value on Z axis
  40787. */
  40788. zmin,
  40789. /**
  40790. * Defines the maximum value on X axis
  40791. */
  40792. xmax,
  40793. /**
  40794. * Defines the maximum value on Z axis
  40795. */
  40796. zmax,
  40797. /**
  40798. * Defines the subdivisions to apply to the ground
  40799. */
  40800. subdivisions,
  40801. /**
  40802. * Defines the precision to use when computing the tiles
  40803. */
  40804. precision, canBeRegenerated, mesh) {
  40805. if (mesh === void 0) { mesh = null; }
  40806. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40807. _this.xmin = xmin;
  40808. _this.zmin = zmin;
  40809. _this.xmax = xmax;
  40810. _this.zmax = zmax;
  40811. _this.subdivisions = subdivisions;
  40812. _this.precision = precision;
  40813. return _this;
  40814. }
  40815. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40816. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40817. };
  40818. TiledGroundGeometry.prototype.copy = function (id) {
  40819. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40820. };
  40821. return TiledGroundGeometry;
  40822. }(_PrimitiveGeometry));
  40823. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40824. /**
  40825. * Creates a plane geometry
  40826. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40827. */
  40828. var PlaneGeometry = /** @class */ (function (_super) {
  40829. __extends(PlaneGeometry, _super);
  40830. /**
  40831. * Creates a plane geometry
  40832. * @param id defines the unique ID of the geometry
  40833. * @param scene defines the hosting scene
  40834. * @param size defines the size of the plane (width === height)
  40835. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40836. * @param mesh defines the hosting mesh (can be null)
  40837. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40838. */
  40839. function PlaneGeometry(id, scene,
  40840. /**
  40841. * Defines the size of the plane (width === height)
  40842. */
  40843. size, canBeRegenerated, mesh,
  40844. /**
  40845. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40846. */
  40847. side) {
  40848. if (mesh === void 0) { mesh = null; }
  40849. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40850. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40851. _this.size = size;
  40852. _this.side = side;
  40853. return _this;
  40854. }
  40855. PlaneGeometry.prototype._regenerateVertexData = function () {
  40856. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40857. };
  40858. PlaneGeometry.prototype.copy = function (id) {
  40859. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40860. };
  40861. PlaneGeometry.prototype.serialize = function () {
  40862. var serializationObject = _super.prototype.serialize.call(this);
  40863. serializationObject.size = this.size;
  40864. return serializationObject;
  40865. };
  40866. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40867. if (scene.getGeometryByID(parsedPlane.id)) {
  40868. return null; // null since geometry could be something else than a ground...
  40869. }
  40870. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40871. if (BABYLON.Tags) {
  40872. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40873. }
  40874. scene.pushGeometry(plane, true);
  40875. return plane;
  40876. };
  40877. return PlaneGeometry;
  40878. }(_PrimitiveGeometry));
  40879. BABYLON.PlaneGeometry = PlaneGeometry;
  40880. /**
  40881. * Creates a torus knot geometry
  40882. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40883. */
  40884. var TorusKnotGeometry = /** @class */ (function (_super) {
  40885. __extends(TorusKnotGeometry, _super);
  40886. /**
  40887. * Creates a torus knot geometry
  40888. * @param id defines the unique ID of the geometry
  40889. * @param scene defines the hosting scene
  40890. * @param radius defines the radius of the torus knot
  40891. * @param tube defines the thickness of the torus knot tube
  40892. * @param radialSegments defines the number of radial segments
  40893. * @param tubularSegments defines the number of tubular segments
  40894. * @param p defines the first number of windings
  40895. * @param q defines the second number of windings
  40896. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40897. * @param mesh defines the hosting mesh (can be null)
  40898. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40899. */
  40900. function TorusKnotGeometry(id, scene,
  40901. /**
  40902. * Defines the radius of the torus knot
  40903. */
  40904. radius,
  40905. /**
  40906. * Defines the thickness of the torus knot tube
  40907. */
  40908. tube,
  40909. /**
  40910. * Defines the number of radial segments
  40911. */
  40912. radialSegments,
  40913. /**
  40914. * Defines the number of tubular segments
  40915. */
  40916. tubularSegments,
  40917. /**
  40918. * Defines the first number of windings
  40919. */
  40920. p,
  40921. /**
  40922. * Defines the second number of windings
  40923. */
  40924. q, canBeRegenerated, mesh,
  40925. /**
  40926. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40927. */
  40928. side) {
  40929. if (mesh === void 0) { mesh = null; }
  40930. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40931. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40932. _this.radius = radius;
  40933. _this.tube = tube;
  40934. _this.radialSegments = radialSegments;
  40935. _this.tubularSegments = tubularSegments;
  40936. _this.p = p;
  40937. _this.q = q;
  40938. _this.side = side;
  40939. return _this;
  40940. }
  40941. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40942. 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 });
  40943. };
  40944. TorusKnotGeometry.prototype.copy = function (id) {
  40945. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40946. };
  40947. TorusKnotGeometry.prototype.serialize = function () {
  40948. var serializationObject = _super.prototype.serialize.call(this);
  40949. serializationObject.radius = this.radius;
  40950. serializationObject.tube = this.tube;
  40951. serializationObject.radialSegments = this.radialSegments;
  40952. serializationObject.tubularSegments = this.tubularSegments;
  40953. serializationObject.p = this.p;
  40954. serializationObject.q = this.q;
  40955. return serializationObject;
  40956. };
  40957. ;
  40958. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40959. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40960. return null; // null since geometry could be something else than a ground...
  40961. }
  40962. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40963. if (BABYLON.Tags) {
  40964. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40965. }
  40966. scene.pushGeometry(torusKnot, true);
  40967. return torusKnot;
  40968. };
  40969. return TorusKnotGeometry;
  40970. }(_PrimitiveGeometry));
  40971. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40972. //}
  40973. })(BABYLON || (BABYLON = {}));
  40974. //# sourceMappingURL=babylon.geometry.js.map
  40975. var BABYLON;
  40976. (function (BABYLON) {
  40977. /**
  40978. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40979. */
  40980. var PerformanceMonitor = /** @class */ (function () {
  40981. /**
  40982. * constructor
  40983. * @param frameSampleSize The number of samples required to saturate the sliding window
  40984. */
  40985. function PerformanceMonitor(frameSampleSize) {
  40986. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40987. this._enabled = true;
  40988. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40989. }
  40990. /**
  40991. * Samples current frame
  40992. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40993. */
  40994. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40995. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40996. if (!this._enabled)
  40997. return;
  40998. if (this._lastFrameTimeMs != null) {
  40999. var dt = timeMs - this._lastFrameTimeMs;
  41000. this._rollingFrameTime.add(dt);
  41001. }
  41002. this._lastFrameTimeMs = timeMs;
  41003. };
  41004. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41005. /**
  41006. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41007. * @return Average frame time in milliseconds
  41008. */
  41009. get: function () {
  41010. return this._rollingFrameTime.average;
  41011. },
  41012. enumerable: true,
  41013. configurable: true
  41014. });
  41015. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41016. /**
  41017. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41018. * @return Frame time variance in milliseconds squared
  41019. */
  41020. get: function () {
  41021. return this._rollingFrameTime.variance;
  41022. },
  41023. enumerable: true,
  41024. configurable: true
  41025. });
  41026. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41027. /**
  41028. * Returns the frame time of the most recent frame
  41029. * @return Frame time in milliseconds
  41030. */
  41031. get: function () {
  41032. return this._rollingFrameTime.history(0);
  41033. },
  41034. enumerable: true,
  41035. configurable: true
  41036. });
  41037. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41038. /**
  41039. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41040. * @return Framerate in frames per second
  41041. */
  41042. get: function () {
  41043. return 1000.0 / this._rollingFrameTime.average;
  41044. },
  41045. enumerable: true,
  41046. configurable: true
  41047. });
  41048. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41049. /**
  41050. * Returns the average framerate in frames per second using the most recent frame time
  41051. * @return Framerate in frames per second
  41052. */
  41053. get: function () {
  41054. var history = this._rollingFrameTime.history(0);
  41055. if (history === 0) {
  41056. return 0;
  41057. }
  41058. return 1000.0 / history;
  41059. },
  41060. enumerable: true,
  41061. configurable: true
  41062. });
  41063. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41064. /**
  41065. * Returns true if enough samples have been taken to completely fill the sliding window
  41066. * @return true if saturated
  41067. */
  41068. get: function () {
  41069. return this._rollingFrameTime.isSaturated();
  41070. },
  41071. enumerable: true,
  41072. configurable: true
  41073. });
  41074. /**
  41075. * Enables contributions to the sliding window sample set
  41076. */
  41077. PerformanceMonitor.prototype.enable = function () {
  41078. this._enabled = true;
  41079. };
  41080. /**
  41081. * Disables contributions to the sliding window sample set
  41082. * Samples will not be interpolated over the disabled period
  41083. */
  41084. PerformanceMonitor.prototype.disable = function () {
  41085. this._enabled = false;
  41086. //clear last sample to avoid interpolating over the disabled period when next enabled
  41087. this._lastFrameTimeMs = null;
  41088. };
  41089. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41090. /**
  41091. * Returns true if sampling is enabled
  41092. * @return true if enabled
  41093. */
  41094. get: function () {
  41095. return this._enabled;
  41096. },
  41097. enumerable: true,
  41098. configurable: true
  41099. });
  41100. /**
  41101. * Resets performance monitor
  41102. */
  41103. PerformanceMonitor.prototype.reset = function () {
  41104. //clear last sample to avoid interpolating over the disabled period when next enabled
  41105. this._lastFrameTimeMs = null;
  41106. //wipe record
  41107. this._rollingFrameTime.reset();
  41108. };
  41109. return PerformanceMonitor;
  41110. }());
  41111. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41112. /**
  41113. * RollingAverage
  41114. *
  41115. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41116. */
  41117. var RollingAverage = /** @class */ (function () {
  41118. /**
  41119. * constructor
  41120. * @param length The number of samples required to saturate the sliding window
  41121. */
  41122. function RollingAverage(length) {
  41123. this._samples = new Array(length);
  41124. this.reset();
  41125. }
  41126. /**
  41127. * Adds a sample to the sample set
  41128. * @param v The sample value
  41129. */
  41130. RollingAverage.prototype.add = function (v) {
  41131. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41132. var delta;
  41133. //we need to check if we've already wrapped round
  41134. if (this.isSaturated()) {
  41135. //remove bottom of stack from mean
  41136. var bottomValue = this._samples[this._pos];
  41137. delta = bottomValue - this.average;
  41138. this.average -= delta / (this._sampleCount - 1);
  41139. this._m2 -= delta * (bottomValue - this.average);
  41140. }
  41141. else {
  41142. this._sampleCount++;
  41143. }
  41144. //add new value to mean
  41145. delta = v - this.average;
  41146. this.average += delta / (this._sampleCount);
  41147. this._m2 += delta * (v - this.average);
  41148. //set the new variance
  41149. this.variance = this._m2 / (this._sampleCount - 1);
  41150. this._samples[this._pos] = v;
  41151. this._pos++;
  41152. this._pos %= this._samples.length; //positive wrap around
  41153. };
  41154. /**
  41155. * Returns previously added values or null if outside of history or outside the sliding window domain
  41156. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41157. * @return Value previously recorded with add() or null if outside of range
  41158. */
  41159. RollingAverage.prototype.history = function (i) {
  41160. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41161. return 0;
  41162. }
  41163. var i0 = this._wrapPosition(this._pos - 1.0);
  41164. return this._samples[this._wrapPosition(i0 - i)];
  41165. };
  41166. /**
  41167. * Returns true if enough samples have been taken to completely fill the sliding window
  41168. * @return true if sample-set saturated
  41169. */
  41170. RollingAverage.prototype.isSaturated = function () {
  41171. return this._sampleCount >= this._samples.length;
  41172. };
  41173. /**
  41174. * Resets the rolling average (equivalent to 0 samples taken so far)
  41175. */
  41176. RollingAverage.prototype.reset = function () {
  41177. this.average = 0;
  41178. this.variance = 0;
  41179. this._sampleCount = 0;
  41180. this._pos = 0;
  41181. this._m2 = 0;
  41182. };
  41183. /**
  41184. * Wraps a value around the sample range boundaries
  41185. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41186. * @return Wrapped position in sample range
  41187. */
  41188. RollingAverage.prototype._wrapPosition = function (i) {
  41189. var max = this._samples.length;
  41190. return ((i % max) + max) % max;
  41191. };
  41192. return RollingAverage;
  41193. }());
  41194. BABYLON.RollingAverage = RollingAverage;
  41195. })(BABYLON || (BABYLON = {}));
  41196. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41197. var BABYLON;
  41198. (function (BABYLON) {
  41199. /**
  41200. * "Static Class" containing the most commonly used helper while dealing with material for
  41201. * rendering purpose.
  41202. *
  41203. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41204. *
  41205. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41206. */
  41207. var MaterialHelper = /** @class */ (function () {
  41208. function MaterialHelper() {
  41209. }
  41210. /**
  41211. * Bind the current view position to an effect.
  41212. * @param effect The effect to be bound
  41213. * @param scene The scene the eyes position is used from
  41214. */
  41215. MaterialHelper.BindEyePosition = function (effect, scene) {
  41216. if (scene._forcedViewPosition) {
  41217. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41218. return;
  41219. }
  41220. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41221. };
  41222. /**
  41223. * Helps preparing the defines values about the UVs in used in the effect.
  41224. * UVs are shared as much as we can accross chanels in the shaders.
  41225. * @param texture The texture we are preparing the UVs for
  41226. * @param defines The defines to update
  41227. * @param key The chanel key "diffuse", "specular"... used in the shader
  41228. */
  41229. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41230. defines._needUVs = true;
  41231. defines[key] = true;
  41232. if (texture.getTextureMatrix().isIdentity(true)) {
  41233. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41234. if (texture.coordinatesIndex === 0) {
  41235. defines["MAINUV1"] = true;
  41236. }
  41237. else {
  41238. defines["MAINUV2"] = true;
  41239. }
  41240. }
  41241. else {
  41242. defines[key + "DIRECTUV"] = 0;
  41243. }
  41244. };
  41245. /**
  41246. * Binds a texture matrix value to its corrsponding uniform
  41247. * @param texture The texture to bind the matrix for
  41248. * @param uniformBuffer The uniform buffer receivin the data
  41249. * @param key The chanel key "diffuse", "specular"... used in the shader
  41250. */
  41251. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41252. var matrix = texture.getTextureMatrix();
  41253. if (!matrix.isIdentity(true)) {
  41254. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41255. }
  41256. };
  41257. /**
  41258. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41259. * @param mesh defines the current mesh
  41260. * @param scene defines the current scene
  41261. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41262. * @param pointsCloud defines if point cloud rendering has to be turned on
  41263. * @param fogEnabled defines if fog has to be turned on
  41264. * @param alphaTest defines if alpha testing has to be turned on
  41265. * @param defines defines the current list of defines
  41266. */
  41267. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41268. if (defines._areMiscDirty) {
  41269. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41270. defines["POINTSIZE"] = pointsCloud;
  41271. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41272. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41273. defines["ALPHATEST"] = alphaTest;
  41274. }
  41275. };
  41276. /**
  41277. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41278. * @param scene defines the current scene
  41279. * @param engine defines the current engine
  41280. * @param defines specifies the list of active defines
  41281. * @param useInstances defines if instances have to be turned on
  41282. * @param useClipPlane defines if clip plane have to be turned on
  41283. */
  41284. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41285. if (useClipPlane === void 0) { useClipPlane = null; }
  41286. var changed = false;
  41287. if (useClipPlane == null) {
  41288. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41289. }
  41290. if (defines["CLIPPLANE"] !== useClipPlane) {
  41291. defines["CLIPPLANE"] = useClipPlane;
  41292. changed = true;
  41293. }
  41294. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41295. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41296. changed = true;
  41297. }
  41298. if (defines["INSTANCES"] !== useInstances) {
  41299. defines["INSTANCES"] = useInstances;
  41300. changed = true;
  41301. }
  41302. if (changed) {
  41303. defines.markAsUnprocessed();
  41304. }
  41305. };
  41306. /**
  41307. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41308. * @param mesh The mesh containing the geometry data we will draw
  41309. * @param defines The defines to update
  41310. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41311. * @param useBones Precise whether bones should be used or not (override mesh info)
  41312. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41313. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41314. * @returns false if defines are considered not dirty and have not been checked
  41315. */
  41316. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41317. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41318. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41319. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41320. return false;
  41321. }
  41322. defines._normals = defines._needNormals;
  41323. defines._uvs = defines._needUVs;
  41324. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41325. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41326. defines["TANGENT"] = true;
  41327. }
  41328. if (defines._needUVs) {
  41329. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41330. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41331. }
  41332. else {
  41333. defines["UV1"] = false;
  41334. defines["UV2"] = false;
  41335. }
  41336. if (useVertexColor) {
  41337. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41338. defines["VERTEXCOLOR"] = hasVertexColors;
  41339. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41340. }
  41341. if (useBones) {
  41342. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41343. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41344. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41345. }
  41346. else {
  41347. defines["NUM_BONE_INFLUENCERS"] = 0;
  41348. defines["BonesPerMesh"] = 0;
  41349. }
  41350. }
  41351. if (useMorphTargets) {
  41352. var manager = mesh.morphTargetManager;
  41353. if (manager) {
  41354. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41355. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41356. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41357. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41358. }
  41359. else {
  41360. defines["MORPHTARGETS_TANGENT"] = false;
  41361. defines["MORPHTARGETS_NORMAL"] = false;
  41362. defines["MORPHTARGETS"] = false;
  41363. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41364. }
  41365. }
  41366. return true;
  41367. };
  41368. /**
  41369. * Prepares the defines related to the light information passed in parameter
  41370. * @param scene The scene we are intending to draw
  41371. * @param mesh The mesh the effect is compiling for
  41372. * @param defines The defines to update
  41373. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41374. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41375. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41376. * @returns true if normals will be required for the rest of the effect
  41377. */
  41378. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41379. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41380. if (disableLighting === void 0) { disableLighting = false; }
  41381. if (!defines._areLightsDirty) {
  41382. return defines._needNormals;
  41383. }
  41384. var lightIndex = 0;
  41385. var needNormals = false;
  41386. var needRebuild = false;
  41387. var lightmapMode = false;
  41388. var shadowEnabled = false;
  41389. var specularEnabled = false;
  41390. if (scene.lightsEnabled && !disableLighting) {
  41391. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41392. var light = _a[_i];
  41393. needNormals = true;
  41394. if (defines["LIGHT" + lightIndex] === undefined) {
  41395. needRebuild = true;
  41396. }
  41397. defines["LIGHT" + lightIndex] = true;
  41398. defines["SPOTLIGHT" + lightIndex] = false;
  41399. defines["HEMILIGHT" + lightIndex] = false;
  41400. defines["POINTLIGHT" + lightIndex] = false;
  41401. defines["DIRLIGHT" + lightIndex] = false;
  41402. var type;
  41403. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41404. type = "SPOTLIGHT" + lightIndex;
  41405. var spotLight = light;
  41406. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41407. }
  41408. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41409. type = "HEMILIGHT" + lightIndex;
  41410. }
  41411. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41412. type = "POINTLIGHT" + lightIndex;
  41413. }
  41414. else {
  41415. type = "DIRLIGHT" + lightIndex;
  41416. }
  41417. defines[type] = true;
  41418. // Specular
  41419. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41420. specularEnabled = true;
  41421. }
  41422. // Shadows
  41423. defines["SHADOW" + lightIndex] = false;
  41424. defines["SHADOWPCF" + lightIndex] = false;
  41425. defines["SHADOWPCSS" + lightIndex] = false;
  41426. defines["SHADOWPOISSON" + lightIndex] = false;
  41427. defines["SHADOWESM" + lightIndex] = false;
  41428. defines["SHADOWCUBE" + lightIndex] = false;
  41429. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41430. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41431. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41432. var shadowGenerator = light.getShadowGenerator();
  41433. if (shadowGenerator) {
  41434. shadowEnabled = true;
  41435. shadowGenerator.prepareDefines(defines, lightIndex);
  41436. }
  41437. }
  41438. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41439. lightmapMode = true;
  41440. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41441. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41442. }
  41443. else {
  41444. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41445. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41446. }
  41447. lightIndex++;
  41448. if (lightIndex === maxSimultaneousLights)
  41449. break;
  41450. }
  41451. }
  41452. defines["SPECULARTERM"] = specularEnabled;
  41453. defines["SHADOWS"] = shadowEnabled;
  41454. // Resetting all other lights if any
  41455. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41456. if (defines["LIGHT" + index] !== undefined) {
  41457. defines["LIGHT" + index] = false;
  41458. defines["HEMILIGHT" + lightIndex] = false;
  41459. defines["POINTLIGHT" + lightIndex] = false;
  41460. defines["DIRLIGHT" + lightIndex] = false;
  41461. defines["SPOTLIGHT" + lightIndex] = false;
  41462. defines["SHADOW" + lightIndex] = false;
  41463. }
  41464. }
  41465. var caps = scene.getEngine().getCaps();
  41466. if (defines["SHADOWFLOAT"] === undefined) {
  41467. needRebuild = true;
  41468. }
  41469. defines["SHADOWFLOAT"] = shadowEnabled &&
  41470. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41471. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41472. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41473. if (needRebuild) {
  41474. defines.rebuild();
  41475. }
  41476. return needNormals;
  41477. };
  41478. /**
  41479. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41480. * that won t be acctive due to defines being turned off.
  41481. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41482. * @param samplersList The samplers list
  41483. * @param defines The defines helping in the list generation
  41484. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41485. */
  41486. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41487. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41488. var uniformsList;
  41489. var uniformBuffersList = null;
  41490. if (uniformsListOrOptions.uniformsNames) {
  41491. var options = uniformsListOrOptions;
  41492. uniformsList = options.uniformsNames;
  41493. uniformBuffersList = options.uniformBuffersNames;
  41494. samplersList = options.samplers;
  41495. defines = options.defines;
  41496. maxSimultaneousLights = options.maxSimultaneousLights;
  41497. }
  41498. else {
  41499. uniformsList = uniformsListOrOptions;
  41500. if (!samplersList) {
  41501. samplersList = [];
  41502. }
  41503. }
  41504. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41505. if (!defines["LIGHT" + lightIndex]) {
  41506. break;
  41507. }
  41508. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41509. if (uniformBuffersList) {
  41510. uniformBuffersList.push("Light" + lightIndex);
  41511. }
  41512. samplersList.push("shadowSampler" + lightIndex);
  41513. samplersList.push("depthSampler" + lightIndex);
  41514. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41515. samplersList.push("projectionLightSampler" + lightIndex);
  41516. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41517. }
  41518. }
  41519. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41520. uniformsList.push("morphTargetInfluences");
  41521. }
  41522. };
  41523. /**
  41524. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41525. * @param defines The defines to update while falling back
  41526. * @param fallbacks The authorized effect fallbacks
  41527. * @param maxSimultaneousLights The maximum number of lights allowed
  41528. * @param rank the current rank of the Effect
  41529. * @returns The newly affected rank
  41530. */
  41531. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41532. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41533. if (rank === void 0) { rank = 0; }
  41534. var lightFallbackRank = 0;
  41535. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41536. if (!defines["LIGHT" + lightIndex]) {
  41537. break;
  41538. }
  41539. if (lightIndex > 0) {
  41540. lightFallbackRank = rank + lightIndex;
  41541. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41542. }
  41543. if (!defines["SHADOWS"]) {
  41544. if (defines["SHADOW" + lightIndex]) {
  41545. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41546. }
  41547. if (defines["SHADOWPCF" + lightIndex]) {
  41548. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41549. }
  41550. if (defines["SHADOWPCSS" + lightIndex]) {
  41551. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41552. }
  41553. if (defines["SHADOWPOISSON" + lightIndex]) {
  41554. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41555. }
  41556. if (defines["SHADOWESM" + lightIndex]) {
  41557. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41558. }
  41559. }
  41560. }
  41561. return lightFallbackRank++;
  41562. };
  41563. /**
  41564. * Prepares the list of attributes required for morph targets according to the effect defines.
  41565. * @param attribs The current list of supported attribs
  41566. * @param mesh The mesh to prepare the morph targets attributes for
  41567. * @param defines The current Defines of the effect
  41568. */
  41569. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41570. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41571. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41572. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41573. var manager = mesh.morphTargetManager;
  41574. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41575. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41576. for (var index = 0; index < influencers; index++) {
  41577. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41578. if (normal) {
  41579. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41580. }
  41581. if (tangent) {
  41582. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41583. }
  41584. if (attribs.length > maxAttributesCount) {
  41585. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41586. }
  41587. }
  41588. }
  41589. };
  41590. /**
  41591. * Prepares the list of attributes required for bones according to the effect defines.
  41592. * @param attribs The current list of supported attribs
  41593. * @param mesh The mesh to prepare the bones attributes for
  41594. * @param defines The current Defines of the effect
  41595. * @param fallbacks The current efffect fallback strategy
  41596. */
  41597. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41598. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41599. fallbacks.addCPUSkinningFallback(0, mesh);
  41600. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41601. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41602. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41603. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41604. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41605. }
  41606. }
  41607. };
  41608. /**
  41609. * Prepares the list of attributes required for instances according to the effect defines.
  41610. * @param attribs The current list of supported attribs
  41611. * @param defines The current Defines of the effect
  41612. */
  41613. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41614. if (defines["INSTANCES"]) {
  41615. attribs.push("world0");
  41616. attribs.push("world1");
  41617. attribs.push("world2");
  41618. attribs.push("world3");
  41619. }
  41620. };
  41621. /**
  41622. * Binds the light shadow information to the effect for the given mesh.
  41623. * @param light The light containing the generator
  41624. * @param scene The scene the lights belongs to
  41625. * @param mesh The mesh we are binding the information to render
  41626. * @param lightIndex The light index in the effect used to render the mesh
  41627. * @param effect The effect we are binding the data to
  41628. */
  41629. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41630. if (light.shadowEnabled && mesh.receiveShadows) {
  41631. var shadowGenerator = light.getShadowGenerator();
  41632. if (shadowGenerator) {
  41633. shadowGenerator.bindShadowLight(lightIndex, effect);
  41634. }
  41635. }
  41636. };
  41637. /**
  41638. * Binds the light information to the effect.
  41639. * @param light The light containing the generator
  41640. * @param effect The effect we are binding the data to
  41641. * @param lightIndex The light index in the effect used to render
  41642. */
  41643. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41644. light.transferToEffect(effect, lightIndex + "");
  41645. };
  41646. /**
  41647. * Binds the lights information from the scene to the effect for the given mesh.
  41648. * @param scene The scene the lights belongs to
  41649. * @param mesh The mesh we are binding the information to render
  41650. * @param effect The effect we are binding the data to
  41651. * @param defines The generated defines for the effect
  41652. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41653. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41654. */
  41655. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41656. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41657. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41658. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41659. for (var i = 0; i < len; i++) {
  41660. var light = mesh._lightSources[i];
  41661. var iAsString = i.toString();
  41662. var scaledIntensity = light.getScaledIntensity();
  41663. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41664. MaterialHelper.BindLightProperties(light, effect, i);
  41665. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41666. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41667. if (defines["SPECULARTERM"]) {
  41668. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41669. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41670. }
  41671. // Shadows
  41672. if (scene.shadowsEnabled) {
  41673. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41674. }
  41675. light._uniformBuffer.update();
  41676. }
  41677. };
  41678. /**
  41679. * Binds the fog information from the scene to the effect for the given mesh.
  41680. * @param scene The scene the lights belongs to
  41681. * @param mesh The mesh we are binding the information to render
  41682. * @param effect The effect we are binding the data to
  41683. */
  41684. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41685. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41686. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41687. effect.setColor3("vFogColor", scene.fogColor);
  41688. }
  41689. };
  41690. /**
  41691. * Binds the bones information from the mesh to the effect.
  41692. * @param mesh The mesh we are binding the information to render
  41693. * @param effect The effect we are binding the data to
  41694. */
  41695. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41696. if (!effect || !mesh) {
  41697. return;
  41698. }
  41699. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41700. mesh.computeBonesUsingShaders = false;
  41701. }
  41702. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41703. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41704. if (matrices) {
  41705. effect.setMatrices("mBones", matrices);
  41706. }
  41707. }
  41708. };
  41709. /**
  41710. * Binds the morph targets information from the mesh to the effect.
  41711. * @param abstractMesh The mesh we are binding the information to render
  41712. * @param effect The effect we are binding the data to
  41713. */
  41714. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41715. var manager = abstractMesh.morphTargetManager;
  41716. if (!abstractMesh || !manager) {
  41717. return;
  41718. }
  41719. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41720. };
  41721. /**
  41722. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41723. * @param defines The generated defines used in the effect
  41724. * @param effect The effect we are binding the data to
  41725. * @param scene The scene we are willing to render with logarithmic scale for
  41726. */
  41727. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41728. if (defines["LOGARITHMICDEPTH"]) {
  41729. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41730. }
  41731. };
  41732. /**
  41733. * Binds the clip plane information from the scene to the effect.
  41734. * @param scene The scene the clip plane information are extracted from
  41735. * @param effect The effect we are binding the data to
  41736. */
  41737. MaterialHelper.BindClipPlane = function (effect, scene) {
  41738. if (scene.clipPlane) {
  41739. var clipPlane = scene.clipPlane;
  41740. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41741. }
  41742. };
  41743. return MaterialHelper;
  41744. }());
  41745. BABYLON.MaterialHelper = MaterialHelper;
  41746. })(BABYLON || (BABYLON = {}));
  41747. //# sourceMappingURL=babylon.materialHelper.js.map
  41748. var BABYLON;
  41749. (function (BABYLON) {
  41750. var PushMaterial = /** @class */ (function (_super) {
  41751. __extends(PushMaterial, _super);
  41752. function PushMaterial(name, scene) {
  41753. var _this = _super.call(this, name, scene) || this;
  41754. _this._normalMatrix = new BABYLON.Matrix();
  41755. _this.storeEffectOnSubMeshes = true;
  41756. return _this;
  41757. }
  41758. PushMaterial.prototype.getEffect = function () {
  41759. return this._activeEffect;
  41760. };
  41761. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41762. if (!mesh) {
  41763. return false;
  41764. }
  41765. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41766. return true;
  41767. }
  41768. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41769. };
  41770. /**
  41771. * Binds the given world matrix to the active effect
  41772. *
  41773. * @param world the matrix to bind
  41774. */
  41775. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41776. this._activeEffect.setMatrix("world", world);
  41777. };
  41778. /**
  41779. * Binds the given normal matrix to the active effect
  41780. *
  41781. * @param normalMatrix the matrix to bind
  41782. */
  41783. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41784. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41785. };
  41786. PushMaterial.prototype.bind = function (world, mesh) {
  41787. if (!mesh) {
  41788. return;
  41789. }
  41790. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41791. };
  41792. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41793. if (effect === void 0) { effect = null; }
  41794. _super.prototype._afterBind.call(this, mesh);
  41795. this.getScene()._cachedEffect = effect;
  41796. };
  41797. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41798. if (visibility === void 0) { visibility = 1; }
  41799. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41800. };
  41801. return PushMaterial;
  41802. }(BABYLON.Material));
  41803. BABYLON.PushMaterial = PushMaterial;
  41804. })(BABYLON || (BABYLON = {}));
  41805. //# sourceMappingURL=babylon.pushMaterial.js.map
  41806. var BABYLON;
  41807. (function (BABYLON) {
  41808. /** @hidden */
  41809. var StandardMaterialDefines = /** @class */ (function (_super) {
  41810. __extends(StandardMaterialDefines, _super);
  41811. function StandardMaterialDefines() {
  41812. var _this = _super.call(this) || this;
  41813. _this.MAINUV1 = false;
  41814. _this.MAINUV2 = false;
  41815. _this.DIFFUSE = false;
  41816. _this.DIFFUSEDIRECTUV = 0;
  41817. _this.AMBIENT = false;
  41818. _this.AMBIENTDIRECTUV = 0;
  41819. _this.OPACITY = false;
  41820. _this.OPACITYDIRECTUV = 0;
  41821. _this.OPACITYRGB = false;
  41822. _this.REFLECTION = false;
  41823. _this.EMISSIVE = false;
  41824. _this.EMISSIVEDIRECTUV = 0;
  41825. _this.SPECULAR = false;
  41826. _this.SPECULARDIRECTUV = 0;
  41827. _this.BUMP = false;
  41828. _this.BUMPDIRECTUV = 0;
  41829. _this.PARALLAX = false;
  41830. _this.PARALLAXOCCLUSION = false;
  41831. _this.SPECULAROVERALPHA = false;
  41832. _this.CLIPPLANE = false;
  41833. _this.ALPHATEST = false;
  41834. _this.DEPTHPREPASS = false;
  41835. _this.ALPHAFROMDIFFUSE = false;
  41836. _this.POINTSIZE = false;
  41837. _this.FOG = false;
  41838. _this.SPECULARTERM = false;
  41839. _this.DIFFUSEFRESNEL = false;
  41840. _this.OPACITYFRESNEL = false;
  41841. _this.REFLECTIONFRESNEL = false;
  41842. _this.REFRACTIONFRESNEL = false;
  41843. _this.EMISSIVEFRESNEL = false;
  41844. _this.FRESNEL = false;
  41845. _this.NORMAL = false;
  41846. _this.UV1 = false;
  41847. _this.UV2 = false;
  41848. _this.VERTEXCOLOR = false;
  41849. _this.VERTEXALPHA = false;
  41850. _this.NUM_BONE_INFLUENCERS = 0;
  41851. _this.BonesPerMesh = 0;
  41852. _this.INSTANCES = false;
  41853. _this.GLOSSINESS = false;
  41854. _this.ROUGHNESS = false;
  41855. _this.EMISSIVEASILLUMINATION = false;
  41856. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41857. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41858. _this.LIGHTMAP = false;
  41859. _this.LIGHTMAPDIRECTUV = 0;
  41860. _this.OBJECTSPACE_NORMALMAP = false;
  41861. _this.USELIGHTMAPASSHADOWMAP = false;
  41862. _this.REFLECTIONMAP_3D = false;
  41863. _this.REFLECTIONMAP_SPHERICAL = false;
  41864. _this.REFLECTIONMAP_PLANAR = false;
  41865. _this.REFLECTIONMAP_CUBIC = false;
  41866. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41867. _this.REFLECTIONMAP_PROJECTION = false;
  41868. _this.REFLECTIONMAP_SKYBOX = false;
  41869. _this.REFLECTIONMAP_EXPLICIT = false;
  41870. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41871. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41872. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41873. _this.INVERTCUBICMAP = false;
  41874. _this.LOGARITHMICDEPTH = false;
  41875. _this.REFRACTION = false;
  41876. _this.REFRACTIONMAP_3D = false;
  41877. _this.REFLECTIONOVERALPHA = false;
  41878. _this.TWOSIDEDLIGHTING = false;
  41879. _this.SHADOWFLOAT = false;
  41880. _this.MORPHTARGETS = false;
  41881. _this.MORPHTARGETS_NORMAL = false;
  41882. _this.MORPHTARGETS_TANGENT = false;
  41883. _this.NUM_MORPH_INFLUENCERS = 0;
  41884. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41885. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41886. _this.IMAGEPROCESSING = false;
  41887. _this.VIGNETTE = false;
  41888. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41889. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41890. _this.TONEMAPPING = false;
  41891. _this.CONTRAST = false;
  41892. _this.COLORCURVES = false;
  41893. _this.COLORGRADING = false;
  41894. _this.COLORGRADING3D = false;
  41895. _this.SAMPLER3DGREENDEPTH = false;
  41896. _this.SAMPLER3DBGRMAP = false;
  41897. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41898. /**
  41899. * If the reflection texture on this material is in linear color space
  41900. * @hidden
  41901. */
  41902. _this.IS_REFLECTION_LINEAR = false;
  41903. /**
  41904. * If the refraction texture on this material is in linear color space
  41905. * @hidden
  41906. */
  41907. _this.IS_REFRACTION_LINEAR = false;
  41908. _this.EXPOSURE = false;
  41909. _this.rebuild();
  41910. return _this;
  41911. }
  41912. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41913. var modes = [
  41914. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41915. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41916. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41917. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41918. ];
  41919. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41920. var mode = modes_1[_i];
  41921. this[mode] = (mode === modeToEnable);
  41922. }
  41923. };
  41924. return StandardMaterialDefines;
  41925. }(BABYLON.MaterialDefines));
  41926. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41927. var StandardMaterial = /** @class */ (function (_super) {
  41928. __extends(StandardMaterial, _super);
  41929. function StandardMaterial(name, scene) {
  41930. var _this = _super.call(this, name, scene) || this;
  41931. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41932. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41933. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41934. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41935. _this.specularPower = 64;
  41936. _this._useAlphaFromDiffuseTexture = false;
  41937. _this._useEmissiveAsIllumination = false;
  41938. _this._linkEmissiveWithDiffuse = false;
  41939. _this._useSpecularOverAlpha = false;
  41940. _this._useReflectionOverAlpha = false;
  41941. _this._disableLighting = false;
  41942. _this._useObjectSpaceNormalMap = false;
  41943. _this._useParallax = false;
  41944. _this._useParallaxOcclusion = false;
  41945. _this.parallaxScaleBias = 0.05;
  41946. _this._roughness = 0;
  41947. _this.indexOfRefraction = 0.98;
  41948. _this.invertRefractionY = true;
  41949. /**
  41950. * Defines the alpha limits in alpha test mode
  41951. */
  41952. _this.alphaCutOff = 0.4;
  41953. _this._useLightmapAsShadowmap = false;
  41954. _this._useReflectionFresnelFromSpecular = false;
  41955. _this._useGlossinessFromSpecularMapAlpha = false;
  41956. _this._maxSimultaneousLights = 4;
  41957. /**
  41958. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41959. */
  41960. _this._invertNormalMapX = false;
  41961. /**
  41962. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41963. */
  41964. _this._invertNormalMapY = false;
  41965. /**
  41966. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41967. */
  41968. _this._twoSidedLighting = false;
  41969. _this._renderTargets = new BABYLON.SmartArray(16);
  41970. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41971. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41972. // Setup the default processing configuration to the scene.
  41973. _this._attachImageProcessingConfiguration(null);
  41974. _this.getRenderTargetTextures = function () {
  41975. _this._renderTargets.reset();
  41976. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41977. _this._renderTargets.push(_this._reflectionTexture);
  41978. }
  41979. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41980. _this._renderTargets.push(_this._refractionTexture);
  41981. }
  41982. return _this._renderTargets;
  41983. };
  41984. return _this;
  41985. }
  41986. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41987. /**
  41988. * Gets the image processing configuration used either in this material.
  41989. */
  41990. get: function () {
  41991. return this._imageProcessingConfiguration;
  41992. },
  41993. /**
  41994. * Sets the Default image processing configuration used either in the this material.
  41995. *
  41996. * If sets to null, the scene one is in use.
  41997. */
  41998. set: function (value) {
  41999. this._attachImageProcessingConfiguration(value);
  42000. // Ensure the effect will be rebuilt.
  42001. this._markAllSubMeshesAsTexturesDirty();
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. /**
  42007. * Attaches a new image processing configuration to the Standard Material.
  42008. * @param configuration
  42009. */
  42010. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42011. var _this = this;
  42012. if (configuration === this._imageProcessingConfiguration) {
  42013. return;
  42014. }
  42015. // Detaches observer.
  42016. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42017. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42018. }
  42019. // Pick the scene configuration if needed.
  42020. if (!configuration) {
  42021. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42022. }
  42023. else {
  42024. this._imageProcessingConfiguration = configuration;
  42025. }
  42026. // Attaches observer.
  42027. if (this._imageProcessingConfiguration) {
  42028. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42029. _this._markAllSubMeshesAsImageProcessingDirty();
  42030. });
  42031. }
  42032. };
  42033. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42034. /**
  42035. * Gets wether the color curves effect is enabled.
  42036. */
  42037. get: function () {
  42038. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42039. },
  42040. /**
  42041. * Sets wether the color curves effect is enabled.
  42042. */
  42043. set: function (value) {
  42044. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42045. },
  42046. enumerable: true,
  42047. configurable: true
  42048. });
  42049. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42050. /**
  42051. * Gets wether the color grading effect is enabled.
  42052. */
  42053. get: function () {
  42054. return this.imageProcessingConfiguration.colorGradingEnabled;
  42055. },
  42056. /**
  42057. * Gets wether the color grading effect is enabled.
  42058. */
  42059. set: function (value) {
  42060. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42061. },
  42062. enumerable: true,
  42063. configurable: true
  42064. });
  42065. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42066. /**
  42067. * Gets wether tonemapping is enabled or not.
  42068. */
  42069. get: function () {
  42070. return this._imageProcessingConfiguration.toneMappingEnabled;
  42071. },
  42072. /**
  42073. * Sets wether tonemapping is enabled or not
  42074. */
  42075. set: function (value) {
  42076. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42077. },
  42078. enumerable: true,
  42079. configurable: true
  42080. });
  42081. ;
  42082. ;
  42083. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42084. /**
  42085. * The camera exposure used on this material.
  42086. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42087. * This corresponds to a photographic exposure.
  42088. */
  42089. get: function () {
  42090. return this._imageProcessingConfiguration.exposure;
  42091. },
  42092. /**
  42093. * The camera exposure used on this material.
  42094. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42095. * This corresponds to a photographic exposure.
  42096. */
  42097. set: function (value) {
  42098. this._imageProcessingConfiguration.exposure = value;
  42099. },
  42100. enumerable: true,
  42101. configurable: true
  42102. });
  42103. ;
  42104. ;
  42105. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42106. /**
  42107. * Gets The camera contrast used on this material.
  42108. */
  42109. get: function () {
  42110. return this._imageProcessingConfiguration.contrast;
  42111. },
  42112. /**
  42113. * Sets The camera contrast used on this material.
  42114. */
  42115. set: function (value) {
  42116. this._imageProcessingConfiguration.contrast = value;
  42117. },
  42118. enumerable: true,
  42119. configurable: true
  42120. });
  42121. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42122. /**
  42123. * Gets the Color Grading 2D Lookup Texture.
  42124. */
  42125. get: function () {
  42126. return this._imageProcessingConfiguration.colorGradingTexture;
  42127. },
  42128. /**
  42129. * Sets the Color Grading 2D Lookup Texture.
  42130. */
  42131. set: function (value) {
  42132. this._imageProcessingConfiguration.colorGradingTexture = value;
  42133. },
  42134. enumerable: true,
  42135. configurable: true
  42136. });
  42137. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42138. /**
  42139. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42140. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42141. * 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;
  42142. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42143. */
  42144. get: function () {
  42145. return this._imageProcessingConfiguration.colorCurves;
  42146. },
  42147. /**
  42148. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42149. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42150. * 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;
  42151. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42152. */
  42153. set: function (value) {
  42154. this._imageProcessingConfiguration.colorCurves = value;
  42155. },
  42156. enumerable: true,
  42157. configurable: true
  42158. });
  42159. StandardMaterial.prototype.getClassName = function () {
  42160. return "StandardMaterial";
  42161. };
  42162. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42163. get: function () {
  42164. return this._useLogarithmicDepth;
  42165. },
  42166. set: function (value) {
  42167. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42168. this._markAllSubMeshesAsMiscDirty();
  42169. },
  42170. enumerable: true,
  42171. configurable: true
  42172. });
  42173. StandardMaterial.prototype.needAlphaBlending = function () {
  42174. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42175. };
  42176. StandardMaterial.prototype.needAlphaTesting = function () {
  42177. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42178. };
  42179. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42180. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42181. };
  42182. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42183. return this._diffuseTexture;
  42184. };
  42185. /**
  42186. * Child classes can use it to update shaders
  42187. */
  42188. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42189. if (useInstances === void 0) { useInstances = false; }
  42190. if (subMesh.effect && this.isFrozen) {
  42191. if (this._wasPreviouslyReady && subMesh.effect) {
  42192. return true;
  42193. }
  42194. }
  42195. if (!subMesh._materialDefines) {
  42196. subMesh._materialDefines = new StandardMaterialDefines();
  42197. }
  42198. var scene = this.getScene();
  42199. var defines = subMesh._materialDefines;
  42200. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42201. if (defines._renderId === scene.getRenderId()) {
  42202. return true;
  42203. }
  42204. }
  42205. var engine = scene.getEngine();
  42206. // Lights
  42207. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42208. // Textures
  42209. if (defines._areTexturesDirty) {
  42210. defines._needUVs = false;
  42211. defines.MAINUV1 = false;
  42212. defines.MAINUV2 = false;
  42213. if (scene.texturesEnabled) {
  42214. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42215. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42216. return false;
  42217. }
  42218. else {
  42219. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42220. }
  42221. }
  42222. else {
  42223. defines.DIFFUSE = false;
  42224. }
  42225. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42226. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42227. return false;
  42228. }
  42229. else {
  42230. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42231. }
  42232. }
  42233. else {
  42234. defines.AMBIENT = false;
  42235. }
  42236. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42237. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42238. return false;
  42239. }
  42240. else {
  42241. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42242. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42243. }
  42244. }
  42245. else {
  42246. defines.OPACITY = false;
  42247. }
  42248. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42249. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42250. return false;
  42251. }
  42252. else {
  42253. defines._needNormals = true;
  42254. defines.REFLECTION = true;
  42255. defines.ROUGHNESS = (this._roughness > 0);
  42256. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42257. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42258. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42259. switch (this._reflectionTexture.coordinatesMode) {
  42260. case BABYLON.Texture.EXPLICIT_MODE:
  42261. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42262. break;
  42263. case BABYLON.Texture.PLANAR_MODE:
  42264. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42265. break;
  42266. case BABYLON.Texture.PROJECTION_MODE:
  42267. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42268. break;
  42269. case BABYLON.Texture.SKYBOX_MODE:
  42270. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42271. break;
  42272. case BABYLON.Texture.SPHERICAL_MODE:
  42273. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42274. break;
  42275. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42276. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42277. break;
  42278. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42279. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42280. break;
  42281. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42282. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42283. break;
  42284. case BABYLON.Texture.CUBIC_MODE:
  42285. case BABYLON.Texture.INVCUBIC_MODE:
  42286. default:
  42287. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42288. break;
  42289. }
  42290. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42291. }
  42292. }
  42293. else {
  42294. defines.REFLECTION = false;
  42295. }
  42296. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42297. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42298. return false;
  42299. }
  42300. else {
  42301. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42302. }
  42303. }
  42304. else {
  42305. defines.EMISSIVE = false;
  42306. }
  42307. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42308. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42309. return false;
  42310. }
  42311. else {
  42312. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42313. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42314. }
  42315. }
  42316. else {
  42317. defines.LIGHTMAP = false;
  42318. }
  42319. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42320. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42321. return false;
  42322. }
  42323. else {
  42324. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42325. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42326. }
  42327. }
  42328. else {
  42329. defines.SPECULAR = false;
  42330. }
  42331. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42332. // Bump texure can not be not blocking.
  42333. if (!this._bumpTexture.isReady()) {
  42334. return false;
  42335. }
  42336. else {
  42337. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42338. defines.PARALLAX = this._useParallax;
  42339. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42340. }
  42341. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42342. }
  42343. else {
  42344. defines.BUMP = false;
  42345. }
  42346. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42347. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42348. return false;
  42349. }
  42350. else {
  42351. defines._needUVs = true;
  42352. defines.REFRACTION = true;
  42353. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42354. }
  42355. }
  42356. else {
  42357. defines.REFRACTION = false;
  42358. }
  42359. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42360. }
  42361. else {
  42362. defines.DIFFUSE = false;
  42363. defines.AMBIENT = false;
  42364. defines.OPACITY = false;
  42365. defines.REFLECTION = false;
  42366. defines.EMISSIVE = false;
  42367. defines.LIGHTMAP = false;
  42368. defines.BUMP = false;
  42369. defines.REFRACTION = false;
  42370. }
  42371. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42372. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42373. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42374. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42375. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42376. }
  42377. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42378. if (!this._imageProcessingConfiguration.isReady()) {
  42379. return false;
  42380. }
  42381. this._imageProcessingConfiguration.prepareDefines(defines);
  42382. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42383. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42384. }
  42385. if (defines._areFresnelDirty) {
  42386. if (StandardMaterial.FresnelEnabled) {
  42387. // Fresnel
  42388. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42389. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42390. this._reflectionFresnelParameters) {
  42391. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42392. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42393. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42394. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42395. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42396. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42397. defines._needNormals = true;
  42398. defines.FRESNEL = true;
  42399. }
  42400. }
  42401. else {
  42402. defines.FRESNEL = false;
  42403. }
  42404. }
  42405. // Misc.
  42406. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42407. // Attribs
  42408. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42409. // Values that need to be evaluated on every frame
  42410. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42411. // Get correct effect
  42412. if (defines.isDirty) {
  42413. defines.markAsProcessed();
  42414. scene.resetCachedMaterial();
  42415. // Fallbacks
  42416. var fallbacks = new BABYLON.EffectFallbacks();
  42417. if (defines.REFLECTION) {
  42418. fallbacks.addFallback(0, "REFLECTION");
  42419. }
  42420. if (defines.SPECULAR) {
  42421. fallbacks.addFallback(0, "SPECULAR");
  42422. }
  42423. if (defines.BUMP) {
  42424. fallbacks.addFallback(0, "BUMP");
  42425. }
  42426. if (defines.PARALLAX) {
  42427. fallbacks.addFallback(1, "PARALLAX");
  42428. }
  42429. if (defines.PARALLAXOCCLUSION) {
  42430. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42431. }
  42432. if (defines.SPECULAROVERALPHA) {
  42433. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42434. }
  42435. if (defines.FOG) {
  42436. fallbacks.addFallback(1, "FOG");
  42437. }
  42438. if (defines.POINTSIZE) {
  42439. fallbacks.addFallback(0, "POINTSIZE");
  42440. }
  42441. if (defines.LOGARITHMICDEPTH) {
  42442. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42443. }
  42444. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42445. if (defines.SPECULARTERM) {
  42446. fallbacks.addFallback(0, "SPECULARTERM");
  42447. }
  42448. if (defines.DIFFUSEFRESNEL) {
  42449. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42450. }
  42451. if (defines.OPACITYFRESNEL) {
  42452. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42453. }
  42454. if (defines.REFLECTIONFRESNEL) {
  42455. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42456. }
  42457. if (defines.EMISSIVEFRESNEL) {
  42458. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42459. }
  42460. if (defines.FRESNEL) {
  42461. fallbacks.addFallback(4, "FRESNEL");
  42462. }
  42463. //Attributes
  42464. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42465. if (defines.NORMAL) {
  42466. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42467. }
  42468. if (defines.UV1) {
  42469. attribs.push(BABYLON.VertexBuffer.UVKind);
  42470. }
  42471. if (defines.UV2) {
  42472. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42473. }
  42474. if (defines.VERTEXCOLOR) {
  42475. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42476. }
  42477. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42478. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42479. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42480. var shaderName = "default";
  42481. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42482. "vFogInfos", "vFogColor", "pointSize",
  42483. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42484. "mBones",
  42485. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42486. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42487. "vReflectionPosition", "vReflectionSize",
  42488. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42489. ];
  42490. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42491. var uniformBuffers = ["Material", "Scene"];
  42492. if (BABYLON.ImageProcessingConfiguration) {
  42493. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42494. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42495. }
  42496. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42497. uniformsNames: uniforms,
  42498. uniformBuffersNames: uniformBuffers,
  42499. samplers: samplers,
  42500. defines: defines,
  42501. maxSimultaneousLights: this._maxSimultaneousLights
  42502. });
  42503. if (this.customShaderNameResolve) {
  42504. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42505. }
  42506. var join = defines.toString();
  42507. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42508. attributes: attribs,
  42509. uniformsNames: uniforms,
  42510. uniformBuffersNames: uniformBuffers,
  42511. samplers: samplers,
  42512. defines: join,
  42513. fallbacks: fallbacks,
  42514. onCompiled: this.onCompiled,
  42515. onError: this.onError,
  42516. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42517. }, engine), defines);
  42518. this.buildUniformLayout();
  42519. }
  42520. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42521. return false;
  42522. }
  42523. defines._renderId = scene.getRenderId();
  42524. this._wasPreviouslyReady = true;
  42525. return true;
  42526. };
  42527. StandardMaterial.prototype.buildUniformLayout = function () {
  42528. // Order is important !
  42529. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42530. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42531. this._uniformBuffer.addUniform("opacityParts", 4);
  42532. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42533. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42534. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42535. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42536. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42537. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42538. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42539. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42540. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42541. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42542. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42543. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42544. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42545. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42546. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42547. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42548. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42549. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42550. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42551. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42552. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42553. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42554. this._uniformBuffer.addUniform("specularMatrix", 16);
  42555. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42556. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42557. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42558. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42559. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42560. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42561. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42562. this._uniformBuffer.addUniform("pointSize", 1);
  42563. this._uniformBuffer.create();
  42564. };
  42565. StandardMaterial.prototype.unbind = function () {
  42566. if (this._activeEffect) {
  42567. var needFlag = false;
  42568. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42569. this._activeEffect.setTexture("reflection2DSampler", null);
  42570. needFlag = true;
  42571. }
  42572. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42573. this._activeEffect.setTexture("refraction2DSampler", null);
  42574. needFlag = true;
  42575. }
  42576. if (needFlag) {
  42577. this._markAllSubMeshesAsTexturesDirty();
  42578. }
  42579. }
  42580. _super.prototype.unbind.call(this);
  42581. };
  42582. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42583. var scene = this.getScene();
  42584. var defines = subMesh._materialDefines;
  42585. if (!defines) {
  42586. return;
  42587. }
  42588. var effect = subMesh.effect;
  42589. if (!effect) {
  42590. return;
  42591. }
  42592. this._activeEffect = effect;
  42593. // Matrices
  42594. this.bindOnlyWorldMatrix(world);
  42595. // Normal Matrix
  42596. if (defines.OBJECTSPACE_NORMALMAP) {
  42597. world.toNormalMatrix(this._normalMatrix);
  42598. this.bindOnlyNormalMatrix(this._normalMatrix);
  42599. }
  42600. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42601. // Bones
  42602. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42603. if (mustRebind) {
  42604. this._uniformBuffer.bindToEffect(effect, "Material");
  42605. this.bindViewProjection(effect);
  42606. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42607. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42608. // Fresnel
  42609. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42610. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42611. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42612. }
  42613. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42614. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42615. }
  42616. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42617. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42618. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42619. }
  42620. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42621. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42622. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42623. }
  42624. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42625. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42626. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42627. }
  42628. }
  42629. // Textures
  42630. if (scene.texturesEnabled) {
  42631. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42632. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42633. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42634. if (this._diffuseTexture.hasAlpha) {
  42635. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42636. }
  42637. }
  42638. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42639. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42640. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42641. }
  42642. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42643. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42644. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42645. }
  42646. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42647. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42648. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42649. if (this._reflectionTexture.boundingBoxSize) {
  42650. var cubeTexture = this._reflectionTexture;
  42651. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42652. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42653. }
  42654. }
  42655. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42656. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42657. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42658. }
  42659. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42660. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42661. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42662. }
  42663. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42664. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42665. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42666. }
  42667. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42668. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42669. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42670. if (scene._mirroredCameraPosition) {
  42671. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42672. }
  42673. else {
  42674. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42675. }
  42676. }
  42677. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42678. var depth = 1.0;
  42679. if (!this._refractionTexture.isCube) {
  42680. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42681. if (this._refractionTexture.depth) {
  42682. depth = this._refractionTexture.depth;
  42683. }
  42684. }
  42685. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42686. }
  42687. }
  42688. // Point size
  42689. if (this.pointsCloud) {
  42690. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42691. }
  42692. if (defines.SPECULARTERM) {
  42693. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42694. }
  42695. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42696. // Diffuse
  42697. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42698. }
  42699. // Textures
  42700. if (scene.texturesEnabled) {
  42701. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42702. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42703. }
  42704. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42705. effect.setTexture("ambientSampler", this._ambientTexture);
  42706. }
  42707. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42708. effect.setTexture("opacitySampler", this._opacityTexture);
  42709. }
  42710. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42711. if (this._reflectionTexture.isCube) {
  42712. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42713. }
  42714. else {
  42715. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42716. }
  42717. }
  42718. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42719. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42720. }
  42721. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42722. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42723. }
  42724. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42725. effect.setTexture("specularSampler", this._specularTexture);
  42726. }
  42727. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42728. effect.setTexture("bumpSampler", this._bumpTexture);
  42729. }
  42730. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42731. var depth = 1.0;
  42732. if (this._refractionTexture.isCube) {
  42733. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42734. }
  42735. else {
  42736. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42737. }
  42738. }
  42739. }
  42740. // Clip plane
  42741. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42742. // Colors
  42743. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42744. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42745. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42746. }
  42747. if (mustRebind || !this.isFrozen) {
  42748. // Lights
  42749. if (scene.lightsEnabled && !this._disableLighting) {
  42750. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42751. }
  42752. // View
  42753. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42754. this.bindView(effect);
  42755. }
  42756. // Fog
  42757. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42758. // Morph targets
  42759. if (defines.NUM_MORPH_INFLUENCERS) {
  42760. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42761. }
  42762. // Log. depth
  42763. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42764. // image processing
  42765. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42766. this._imageProcessingConfiguration.bind(this._activeEffect);
  42767. }
  42768. }
  42769. this._uniformBuffer.update();
  42770. this._afterBind(mesh, this._activeEffect);
  42771. };
  42772. StandardMaterial.prototype.getAnimatables = function () {
  42773. var results = [];
  42774. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42775. results.push(this._diffuseTexture);
  42776. }
  42777. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42778. results.push(this._ambientTexture);
  42779. }
  42780. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42781. results.push(this._opacityTexture);
  42782. }
  42783. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42784. results.push(this._reflectionTexture);
  42785. }
  42786. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42787. results.push(this._emissiveTexture);
  42788. }
  42789. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42790. results.push(this._specularTexture);
  42791. }
  42792. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42793. results.push(this._bumpTexture);
  42794. }
  42795. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42796. results.push(this._lightmapTexture);
  42797. }
  42798. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42799. results.push(this._refractionTexture);
  42800. }
  42801. return results;
  42802. };
  42803. StandardMaterial.prototype.getActiveTextures = function () {
  42804. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42805. if (this._diffuseTexture) {
  42806. activeTextures.push(this._diffuseTexture);
  42807. }
  42808. if (this._ambientTexture) {
  42809. activeTextures.push(this._ambientTexture);
  42810. }
  42811. if (this._opacityTexture) {
  42812. activeTextures.push(this._opacityTexture);
  42813. }
  42814. if (this._reflectionTexture) {
  42815. activeTextures.push(this._reflectionTexture);
  42816. }
  42817. if (this._emissiveTexture) {
  42818. activeTextures.push(this._emissiveTexture);
  42819. }
  42820. if (this._specularTexture) {
  42821. activeTextures.push(this._specularTexture);
  42822. }
  42823. if (this._bumpTexture) {
  42824. activeTextures.push(this._bumpTexture);
  42825. }
  42826. if (this._lightmapTexture) {
  42827. activeTextures.push(this._lightmapTexture);
  42828. }
  42829. if (this._refractionTexture) {
  42830. activeTextures.push(this._refractionTexture);
  42831. }
  42832. return activeTextures;
  42833. };
  42834. StandardMaterial.prototype.hasTexture = function (texture) {
  42835. if (_super.prototype.hasTexture.call(this, texture)) {
  42836. return true;
  42837. }
  42838. if (this._diffuseTexture === texture) {
  42839. return true;
  42840. }
  42841. if (this._ambientTexture === texture) {
  42842. return true;
  42843. }
  42844. if (this._opacityTexture === texture) {
  42845. return true;
  42846. }
  42847. if (this._reflectionTexture === texture) {
  42848. return true;
  42849. }
  42850. if (this._emissiveTexture === texture) {
  42851. return true;
  42852. }
  42853. if (this._specularTexture === texture) {
  42854. return true;
  42855. }
  42856. if (this._bumpTexture === texture) {
  42857. return true;
  42858. }
  42859. if (this._lightmapTexture === texture) {
  42860. return true;
  42861. }
  42862. if (this._refractionTexture === texture) {
  42863. return true;
  42864. }
  42865. return false;
  42866. };
  42867. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42868. if (forceDisposeTextures) {
  42869. if (this._diffuseTexture) {
  42870. this._diffuseTexture.dispose();
  42871. }
  42872. if (this._ambientTexture) {
  42873. this._ambientTexture.dispose();
  42874. }
  42875. if (this._opacityTexture) {
  42876. this._opacityTexture.dispose();
  42877. }
  42878. if (this._reflectionTexture) {
  42879. this._reflectionTexture.dispose();
  42880. }
  42881. if (this._emissiveTexture) {
  42882. this._emissiveTexture.dispose();
  42883. }
  42884. if (this._specularTexture) {
  42885. this._specularTexture.dispose();
  42886. }
  42887. if (this._bumpTexture) {
  42888. this._bumpTexture.dispose();
  42889. }
  42890. if (this._lightmapTexture) {
  42891. this._lightmapTexture.dispose();
  42892. }
  42893. if (this._refractionTexture) {
  42894. this._refractionTexture.dispose();
  42895. }
  42896. }
  42897. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42898. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42899. }
  42900. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42901. };
  42902. StandardMaterial.prototype.clone = function (name) {
  42903. var _this = this;
  42904. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42905. result.name = name;
  42906. result.id = name;
  42907. return result;
  42908. };
  42909. StandardMaterial.prototype.serialize = function () {
  42910. return BABYLON.SerializationHelper.Serialize(this);
  42911. };
  42912. // Statics
  42913. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42914. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42915. };
  42916. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42917. get: function () {
  42918. return StandardMaterial._DiffuseTextureEnabled;
  42919. },
  42920. set: function (value) {
  42921. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42922. return;
  42923. }
  42924. StandardMaterial._DiffuseTextureEnabled = value;
  42925. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42926. },
  42927. enumerable: true,
  42928. configurable: true
  42929. });
  42930. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42931. get: function () {
  42932. return StandardMaterial._AmbientTextureEnabled;
  42933. },
  42934. set: function (value) {
  42935. if (StandardMaterial._AmbientTextureEnabled === value) {
  42936. return;
  42937. }
  42938. StandardMaterial._AmbientTextureEnabled = value;
  42939. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42940. },
  42941. enumerable: true,
  42942. configurable: true
  42943. });
  42944. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42945. get: function () {
  42946. return StandardMaterial._OpacityTextureEnabled;
  42947. },
  42948. set: function (value) {
  42949. if (StandardMaterial._OpacityTextureEnabled === value) {
  42950. return;
  42951. }
  42952. StandardMaterial._OpacityTextureEnabled = value;
  42953. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42954. },
  42955. enumerable: true,
  42956. configurable: true
  42957. });
  42958. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42959. get: function () {
  42960. return StandardMaterial._ReflectionTextureEnabled;
  42961. },
  42962. set: function (value) {
  42963. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42964. return;
  42965. }
  42966. StandardMaterial._ReflectionTextureEnabled = value;
  42967. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42968. },
  42969. enumerable: true,
  42970. configurable: true
  42971. });
  42972. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42973. get: function () {
  42974. return StandardMaterial._EmissiveTextureEnabled;
  42975. },
  42976. set: function (value) {
  42977. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42978. return;
  42979. }
  42980. StandardMaterial._EmissiveTextureEnabled = value;
  42981. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42982. },
  42983. enumerable: true,
  42984. configurable: true
  42985. });
  42986. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42987. get: function () {
  42988. return StandardMaterial._SpecularTextureEnabled;
  42989. },
  42990. set: function (value) {
  42991. if (StandardMaterial._SpecularTextureEnabled === value) {
  42992. return;
  42993. }
  42994. StandardMaterial._SpecularTextureEnabled = value;
  42995. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42996. },
  42997. enumerable: true,
  42998. configurable: true
  42999. });
  43000. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43001. get: function () {
  43002. return StandardMaterial._BumpTextureEnabled;
  43003. },
  43004. set: function (value) {
  43005. if (StandardMaterial._BumpTextureEnabled === value) {
  43006. return;
  43007. }
  43008. StandardMaterial._BumpTextureEnabled = value;
  43009. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43010. },
  43011. enumerable: true,
  43012. configurable: true
  43013. });
  43014. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43015. get: function () {
  43016. return StandardMaterial._LightmapTextureEnabled;
  43017. },
  43018. set: function (value) {
  43019. if (StandardMaterial._LightmapTextureEnabled === value) {
  43020. return;
  43021. }
  43022. StandardMaterial._LightmapTextureEnabled = value;
  43023. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43024. },
  43025. enumerable: true,
  43026. configurable: true
  43027. });
  43028. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43029. get: function () {
  43030. return StandardMaterial._RefractionTextureEnabled;
  43031. },
  43032. set: function (value) {
  43033. if (StandardMaterial._RefractionTextureEnabled === value) {
  43034. return;
  43035. }
  43036. StandardMaterial._RefractionTextureEnabled = value;
  43037. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43038. },
  43039. enumerable: true,
  43040. configurable: true
  43041. });
  43042. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43043. get: function () {
  43044. return StandardMaterial._ColorGradingTextureEnabled;
  43045. },
  43046. set: function (value) {
  43047. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43048. return;
  43049. }
  43050. StandardMaterial._ColorGradingTextureEnabled = value;
  43051. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43052. },
  43053. enumerable: true,
  43054. configurable: true
  43055. });
  43056. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43057. get: function () {
  43058. return StandardMaterial._FresnelEnabled;
  43059. },
  43060. set: function (value) {
  43061. if (StandardMaterial._FresnelEnabled === value) {
  43062. return;
  43063. }
  43064. StandardMaterial._FresnelEnabled = value;
  43065. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43066. },
  43067. enumerable: true,
  43068. configurable: true
  43069. });
  43070. // Flags used to enable or disable a type of texture for all Standard Materials
  43071. StandardMaterial._DiffuseTextureEnabled = true;
  43072. StandardMaterial._AmbientTextureEnabled = true;
  43073. StandardMaterial._OpacityTextureEnabled = true;
  43074. StandardMaterial._ReflectionTextureEnabled = true;
  43075. StandardMaterial._EmissiveTextureEnabled = true;
  43076. StandardMaterial._SpecularTextureEnabled = true;
  43077. StandardMaterial._BumpTextureEnabled = true;
  43078. StandardMaterial._LightmapTextureEnabled = true;
  43079. StandardMaterial._RefractionTextureEnabled = true;
  43080. StandardMaterial._ColorGradingTextureEnabled = true;
  43081. StandardMaterial._FresnelEnabled = true;
  43082. __decorate([
  43083. BABYLON.serializeAsTexture("diffuseTexture")
  43084. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43085. __decorate([
  43086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43087. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43088. __decorate([
  43089. BABYLON.serializeAsTexture("ambientTexture")
  43090. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43091. __decorate([
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43094. __decorate([
  43095. BABYLON.serializeAsTexture("opacityTexture")
  43096. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43097. __decorate([
  43098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43099. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43100. __decorate([
  43101. BABYLON.serializeAsTexture("reflectionTexture")
  43102. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43103. __decorate([
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43106. __decorate([
  43107. BABYLON.serializeAsTexture("emissiveTexture")
  43108. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43109. __decorate([
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43111. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43112. __decorate([
  43113. BABYLON.serializeAsTexture("specularTexture")
  43114. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43115. __decorate([
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], StandardMaterial.prototype, "specularTexture", void 0);
  43118. __decorate([
  43119. BABYLON.serializeAsTexture("bumpTexture")
  43120. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43121. __decorate([
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43123. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43124. __decorate([
  43125. BABYLON.serializeAsTexture("lightmapTexture")
  43126. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43127. __decorate([
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43130. __decorate([
  43131. BABYLON.serializeAsTexture("refractionTexture")
  43132. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43133. __decorate([
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43135. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43136. __decorate([
  43137. BABYLON.serializeAsColor3("ambient")
  43138. ], StandardMaterial.prototype, "ambientColor", void 0);
  43139. __decorate([
  43140. BABYLON.serializeAsColor3("diffuse")
  43141. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43142. __decorate([
  43143. BABYLON.serializeAsColor3("specular")
  43144. ], StandardMaterial.prototype, "specularColor", void 0);
  43145. __decorate([
  43146. BABYLON.serializeAsColor3("emissive")
  43147. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43148. __decorate([
  43149. BABYLON.serialize()
  43150. ], StandardMaterial.prototype, "specularPower", void 0);
  43151. __decorate([
  43152. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43153. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43154. __decorate([
  43155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43156. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43157. __decorate([
  43158. BABYLON.serialize("useEmissiveAsIllumination")
  43159. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43160. __decorate([
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43162. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43163. __decorate([
  43164. BABYLON.serialize("linkEmissiveWithDiffuse")
  43165. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43166. __decorate([
  43167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43168. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43169. __decorate([
  43170. BABYLON.serialize("useSpecularOverAlpha")
  43171. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43172. __decorate([
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43174. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43175. __decorate([
  43176. BABYLON.serialize("useReflectionOverAlpha")
  43177. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43178. __decorate([
  43179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43180. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43181. __decorate([
  43182. BABYLON.serialize("disableLighting")
  43183. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43184. __decorate([
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43186. ], StandardMaterial.prototype, "disableLighting", void 0);
  43187. __decorate([
  43188. BABYLON.serialize("useObjectSpaceNormalMap")
  43189. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43190. __decorate([
  43191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43192. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43193. __decorate([
  43194. BABYLON.serialize("useParallax")
  43195. ], StandardMaterial.prototype, "_useParallax", void 0);
  43196. __decorate([
  43197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43198. ], StandardMaterial.prototype, "useParallax", void 0);
  43199. __decorate([
  43200. BABYLON.serialize("useParallaxOcclusion")
  43201. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43202. __decorate([
  43203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43204. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43205. __decorate([
  43206. BABYLON.serialize()
  43207. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43208. __decorate([
  43209. BABYLON.serialize("roughness")
  43210. ], StandardMaterial.prototype, "_roughness", void 0);
  43211. __decorate([
  43212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43213. ], StandardMaterial.prototype, "roughness", void 0);
  43214. __decorate([
  43215. BABYLON.serialize()
  43216. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43217. __decorate([
  43218. BABYLON.serialize()
  43219. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43220. __decorate([
  43221. BABYLON.serialize()
  43222. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43223. __decorate([
  43224. BABYLON.serialize("useLightmapAsShadowmap")
  43225. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43226. __decorate([
  43227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43228. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43229. __decorate([
  43230. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43231. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43232. __decorate([
  43233. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43234. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43235. __decorate([
  43236. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43237. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43238. __decorate([
  43239. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43240. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43241. __decorate([
  43242. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43243. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43244. __decorate([
  43245. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43246. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43247. __decorate([
  43248. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43249. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43250. __decorate([
  43251. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43252. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43253. __decorate([
  43254. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43255. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43256. __decorate([
  43257. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43258. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43259. __decorate([
  43260. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43261. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43262. __decorate([
  43263. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43264. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43265. __decorate([
  43266. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43267. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43268. __decorate([
  43269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43270. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43271. __decorate([
  43272. BABYLON.serialize("maxSimultaneousLights")
  43273. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43274. __decorate([
  43275. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43276. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43277. __decorate([
  43278. BABYLON.serialize("invertNormalMapX")
  43279. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43280. __decorate([
  43281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43282. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43283. __decorate([
  43284. BABYLON.serialize("invertNormalMapY")
  43285. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43286. __decorate([
  43287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43288. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43289. __decorate([
  43290. BABYLON.serialize("twoSidedLighting")
  43291. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43292. __decorate([
  43293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43294. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43295. __decorate([
  43296. BABYLON.serialize()
  43297. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43298. return StandardMaterial;
  43299. }(BABYLON.PushMaterial));
  43300. BABYLON.StandardMaterial = StandardMaterial;
  43301. })(BABYLON || (BABYLON = {}));
  43302. //# sourceMappingURL=babylon.standardMaterial.js.map
  43303. var BABYLON;
  43304. (function (BABYLON) {
  43305. /**
  43306. * Manages the defines for the PBR Material.
  43307. * @hiddenChildren
  43308. */
  43309. var PBRMaterialDefines = /** @class */ (function (_super) {
  43310. __extends(PBRMaterialDefines, _super);
  43311. /**
  43312. * Initializes the PBR Material defines.
  43313. */
  43314. function PBRMaterialDefines() {
  43315. var _this = _super.call(this) || this;
  43316. _this.PBR = true;
  43317. _this.MAINUV1 = false;
  43318. _this.MAINUV2 = false;
  43319. _this.UV1 = false;
  43320. _this.UV2 = false;
  43321. _this.ALBEDO = false;
  43322. _this.ALBEDODIRECTUV = 0;
  43323. _this.VERTEXCOLOR = false;
  43324. _this.AMBIENT = false;
  43325. _this.AMBIENTDIRECTUV = 0;
  43326. _this.AMBIENTINGRAYSCALE = false;
  43327. _this.OPACITY = false;
  43328. _this.VERTEXALPHA = false;
  43329. _this.OPACITYDIRECTUV = 0;
  43330. _this.OPACITYRGB = false;
  43331. _this.ALPHATEST = false;
  43332. _this.DEPTHPREPASS = false;
  43333. _this.ALPHABLEND = false;
  43334. _this.ALPHAFROMALBEDO = false;
  43335. _this.ALPHATESTVALUE = "0.5";
  43336. _this.SPECULAROVERALPHA = false;
  43337. _this.RADIANCEOVERALPHA = false;
  43338. _this.ALPHAFRESNEL = false;
  43339. _this.LINEARALPHAFRESNEL = false;
  43340. _this.PREMULTIPLYALPHA = false;
  43341. _this.EMISSIVE = false;
  43342. _this.EMISSIVEDIRECTUV = 0;
  43343. _this.REFLECTIVITY = false;
  43344. _this.REFLECTIVITYDIRECTUV = 0;
  43345. _this.SPECULARTERM = false;
  43346. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43347. _this.MICROSURFACEAUTOMATIC = false;
  43348. _this.LODBASEDMICROSFURACE = false;
  43349. _this.MICROSURFACEMAP = false;
  43350. _this.MICROSURFACEMAPDIRECTUV = 0;
  43351. _this.METALLICWORKFLOW = false;
  43352. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43353. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43354. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43355. _this.AOSTOREINMETALMAPRED = false;
  43356. _this.ENVIRONMENTBRDF = false;
  43357. _this.NORMAL = false;
  43358. _this.TANGENT = false;
  43359. _this.BUMP = false;
  43360. _this.BUMPDIRECTUV = 0;
  43361. _this.OBJECTSPACE_NORMALMAP = false;
  43362. _this.PARALLAX = false;
  43363. _this.PARALLAXOCCLUSION = false;
  43364. _this.NORMALXYSCALE = true;
  43365. _this.LIGHTMAP = false;
  43366. _this.LIGHTMAPDIRECTUV = 0;
  43367. _this.USELIGHTMAPASSHADOWMAP = false;
  43368. _this.GAMMALIGHTMAP = false;
  43369. _this.REFLECTION = false;
  43370. _this.REFLECTIONMAP_3D = false;
  43371. _this.REFLECTIONMAP_SPHERICAL = false;
  43372. _this.REFLECTIONMAP_PLANAR = false;
  43373. _this.REFLECTIONMAP_CUBIC = false;
  43374. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43375. _this.REFLECTIONMAP_PROJECTION = false;
  43376. _this.REFLECTIONMAP_SKYBOX = false;
  43377. _this.REFLECTIONMAP_EXPLICIT = false;
  43378. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43379. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43380. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43381. _this.INVERTCUBICMAP = false;
  43382. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43383. _this.USESPHERICALINVERTEX = false;
  43384. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43385. _this.LODINREFLECTIONALPHA = false;
  43386. _this.GAMMAREFLECTION = false;
  43387. _this.RGBDREFLECTION = false;
  43388. _this.RADIANCEOCCLUSION = false;
  43389. _this.HORIZONOCCLUSION = false;
  43390. _this.REFRACTION = false;
  43391. _this.REFRACTIONMAP_3D = false;
  43392. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43393. _this.LODINREFRACTIONALPHA = false;
  43394. _this.GAMMAREFRACTION = false;
  43395. _this.RGBDREFRACTION = false;
  43396. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43397. _this.INSTANCES = false;
  43398. _this.NUM_BONE_INFLUENCERS = 0;
  43399. _this.BonesPerMesh = 0;
  43400. _this.NONUNIFORMSCALING = false;
  43401. _this.MORPHTARGETS = false;
  43402. _this.MORPHTARGETS_NORMAL = false;
  43403. _this.MORPHTARGETS_TANGENT = false;
  43404. _this.NUM_MORPH_INFLUENCERS = 0;
  43405. _this.IMAGEPROCESSING = false;
  43406. _this.VIGNETTE = false;
  43407. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43408. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43409. _this.TONEMAPPING = false;
  43410. _this.CONTRAST = false;
  43411. _this.COLORCURVES = false;
  43412. _this.COLORGRADING = false;
  43413. _this.COLORGRADING3D = false;
  43414. _this.SAMPLER3DGREENDEPTH = false;
  43415. _this.SAMPLER3DBGRMAP = false;
  43416. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43417. _this.EXPOSURE = false;
  43418. _this.USEPHYSICALLIGHTFALLOFF = false;
  43419. _this.TWOSIDEDLIGHTING = false;
  43420. _this.SHADOWFLOAT = false;
  43421. _this.CLIPPLANE = false;
  43422. _this.POINTSIZE = false;
  43423. _this.FOG = false;
  43424. _this.LOGARITHMICDEPTH = false;
  43425. _this.FORCENORMALFORWARD = false;
  43426. _this.SPECULARAA = false;
  43427. _this.UNLIT = false;
  43428. _this.rebuild();
  43429. return _this;
  43430. }
  43431. /**
  43432. * Resets the PBR Material defines.
  43433. */
  43434. PBRMaterialDefines.prototype.reset = function () {
  43435. _super.prototype.reset.call(this);
  43436. this.ALPHATESTVALUE = "0.5";
  43437. this.PBR = true;
  43438. };
  43439. return PBRMaterialDefines;
  43440. }(BABYLON.MaterialDefines));
  43441. /**
  43442. * The Physically based material base class of BJS.
  43443. *
  43444. * This offers the main features of a standard PBR material.
  43445. * For more information, please refer to the documentation :
  43446. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43447. */
  43448. var PBRBaseMaterial = /** @class */ (function (_super) {
  43449. __extends(PBRBaseMaterial, _super);
  43450. /**
  43451. * Instantiates a new PBRMaterial instance.
  43452. *
  43453. * @param name The material name
  43454. * @param scene The scene the material will be use in.
  43455. */
  43456. function PBRBaseMaterial(name, scene) {
  43457. var _this = _super.call(this, name, scene) || this;
  43458. /**
  43459. * Intensity of the direct lights e.g. the four lights available in your scene.
  43460. * This impacts both the direct diffuse and specular highlights.
  43461. */
  43462. _this._directIntensity = 1.0;
  43463. /**
  43464. * Intensity of the emissive part of the material.
  43465. * This helps controlling the emissive effect without modifying the emissive color.
  43466. */
  43467. _this._emissiveIntensity = 1.0;
  43468. /**
  43469. * Intensity of the environment e.g. how much the environment will light the object
  43470. * either through harmonics for rough material or through the refelction for shiny ones.
  43471. */
  43472. _this._environmentIntensity = 1.0;
  43473. /**
  43474. * This is a special control allowing the reduction of the specular highlights coming from the
  43475. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43476. */
  43477. _this._specularIntensity = 1.0;
  43478. /**
  43479. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43480. */
  43481. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43482. /**
  43483. * Debug Control allowing disabling the bump map on this material.
  43484. */
  43485. _this._disableBumpMap = false;
  43486. /**
  43487. * AKA Occlusion Texture Intensity in other nomenclature.
  43488. */
  43489. _this._ambientTextureStrength = 1.0;
  43490. /**
  43491. * The color of a material in ambient lighting.
  43492. */
  43493. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43494. /**
  43495. * AKA Diffuse Color in other nomenclature.
  43496. */
  43497. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43498. /**
  43499. * AKA Specular Color in other nomenclature.
  43500. */
  43501. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43502. /**
  43503. * The color applied when light is reflected from a material.
  43504. */
  43505. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43506. /**
  43507. * The color applied when light is emitted from a material.
  43508. */
  43509. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43510. /**
  43511. * AKA Glossiness in other nomenclature.
  43512. */
  43513. _this._microSurface = 0.9;
  43514. /**
  43515. * source material index of refraction (IOR)' / 'destination material IOR.
  43516. */
  43517. _this._indexOfRefraction = 0.66;
  43518. /**
  43519. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43520. */
  43521. _this._invertRefractionY = false;
  43522. /**
  43523. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43524. * Materials half opaque for instance using refraction could benefit from this control.
  43525. */
  43526. _this._linkRefractionWithTransparency = false;
  43527. /**
  43528. * Specifies that the material will use the light map as a show map.
  43529. */
  43530. _this._useLightmapAsShadowmap = false;
  43531. /**
  43532. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43533. * makes the reflect vector face the model (under horizon).
  43534. */
  43535. _this._useHorizonOcclusion = true;
  43536. /**
  43537. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43538. * too much the area relying on ambient texture to define their ambient occlusion.
  43539. */
  43540. _this._useRadianceOcclusion = true;
  43541. /**
  43542. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43543. */
  43544. _this._useAlphaFromAlbedoTexture = false;
  43545. /**
  43546. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43547. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43548. */
  43549. _this._useSpecularOverAlpha = true;
  43550. /**
  43551. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43552. */
  43553. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43554. /**
  43555. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43556. */
  43557. _this._useRoughnessFromMetallicTextureAlpha = true;
  43558. /**
  43559. * Specifies if the metallic texture contains the roughness information in its green channel.
  43560. */
  43561. _this._useRoughnessFromMetallicTextureGreen = false;
  43562. /**
  43563. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43564. */
  43565. _this._useMetallnessFromMetallicTextureBlue = false;
  43566. /**
  43567. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43568. */
  43569. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43570. /**
  43571. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43572. */
  43573. _this._useAmbientInGrayScale = false;
  43574. /**
  43575. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43576. * The material will try to infer what glossiness each pixel should be.
  43577. */
  43578. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43579. /**
  43580. * BJS is using an harcoded light falloff based on a manually sets up range.
  43581. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43582. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43583. */
  43584. _this._usePhysicalLightFalloff = true;
  43585. /**
  43586. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43587. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43588. */
  43589. _this._useRadianceOverAlpha = true;
  43590. /**
  43591. * Allows using an object space normal map (instead of tangent space).
  43592. */
  43593. _this._useObjectSpaceNormalMap = false;
  43594. /**
  43595. * Allows using the bump map in parallax mode.
  43596. */
  43597. _this._useParallax = false;
  43598. /**
  43599. * Allows using the bump map in parallax occlusion mode.
  43600. */
  43601. _this._useParallaxOcclusion = false;
  43602. /**
  43603. * Controls the scale bias of the parallax mode.
  43604. */
  43605. _this._parallaxScaleBias = 0.05;
  43606. /**
  43607. * If sets to true, disables all the lights affecting the material.
  43608. */
  43609. _this._disableLighting = false;
  43610. /**
  43611. * Number of Simultaneous lights allowed on the material.
  43612. */
  43613. _this._maxSimultaneousLights = 4;
  43614. /**
  43615. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43616. */
  43617. _this._invertNormalMapX = false;
  43618. /**
  43619. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43620. */
  43621. _this._invertNormalMapY = false;
  43622. /**
  43623. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43624. */
  43625. _this._twoSidedLighting = false;
  43626. /**
  43627. * Defines the alpha limits in alpha test mode.
  43628. */
  43629. _this._alphaCutOff = 0.4;
  43630. /**
  43631. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43632. */
  43633. _this._forceAlphaTest = false;
  43634. /**
  43635. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43636. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43637. */
  43638. _this._useAlphaFresnel = false;
  43639. /**
  43640. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43641. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43642. */
  43643. _this._useLinearAlphaFresnel = false;
  43644. /**
  43645. * The transparency mode of the material.
  43646. */
  43647. _this._transparencyMode = null;
  43648. /**
  43649. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43650. * from cos thetav and roughness:
  43651. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43652. */
  43653. _this._environmentBRDFTexture = null;
  43654. /**
  43655. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43656. */
  43657. _this._forceIrradianceInFragment = false;
  43658. /**
  43659. * Force normal to face away from face.
  43660. */
  43661. _this._forceNormalForward = false;
  43662. /**
  43663. * Enables specular anti aliasing in the PBR shader.
  43664. * It will both interacts on the Geometry for analytical and IBL lighting.
  43665. * It also prefilter the roughness map based on the bump values.
  43666. */
  43667. _this._enableSpecularAntiAliasing = false;
  43668. /**
  43669. * Stores the available render targets.
  43670. */
  43671. _this._renderTargets = new BABYLON.SmartArray(16);
  43672. /**
  43673. * Sets the global ambient color for the material used in lighting calculations.
  43674. */
  43675. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43676. /**
  43677. * If set to true, no lighting calculations will be applied.
  43678. */
  43679. _this._unlit = false;
  43680. // Setup the default processing configuration to the scene.
  43681. _this._attachImageProcessingConfiguration(null);
  43682. _this.getRenderTargetTextures = function () {
  43683. _this._renderTargets.reset();
  43684. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43685. _this._renderTargets.push(_this._reflectionTexture);
  43686. }
  43687. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43688. _this._renderTargets.push(_this._refractionTexture);
  43689. }
  43690. return _this._renderTargets;
  43691. };
  43692. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43693. return _this;
  43694. }
  43695. /**
  43696. * Attaches a new image processing configuration to the PBR Material.
  43697. * @param configuration
  43698. */
  43699. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43700. var _this = this;
  43701. if (configuration === this._imageProcessingConfiguration) {
  43702. return;
  43703. }
  43704. // Detaches observer.
  43705. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43706. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43707. }
  43708. // Pick the scene configuration if needed.
  43709. if (!configuration) {
  43710. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43711. }
  43712. else {
  43713. this._imageProcessingConfiguration = configuration;
  43714. }
  43715. // Attaches observer.
  43716. if (this._imageProcessingConfiguration) {
  43717. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43718. _this._markAllSubMeshesAsImageProcessingDirty();
  43719. });
  43720. }
  43721. };
  43722. /**
  43723. * Gets the name of the material class.
  43724. */
  43725. PBRBaseMaterial.prototype.getClassName = function () {
  43726. return "PBRBaseMaterial";
  43727. };
  43728. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43729. /**
  43730. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43731. */
  43732. get: function () {
  43733. return this._useLogarithmicDepth;
  43734. },
  43735. /**
  43736. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43737. */
  43738. set: function (value) {
  43739. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43740. },
  43741. enumerable: true,
  43742. configurable: true
  43743. });
  43744. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43745. /**
  43746. * Gets the current transparency mode.
  43747. */
  43748. get: function () {
  43749. return this._transparencyMode;
  43750. },
  43751. /**
  43752. * Sets the transparency mode of the material.
  43753. *
  43754. * | Value | Type | Description |
  43755. * | ----- | ----------------------------------- | ----------- |
  43756. * | 0 | OPAQUE | |
  43757. * | 1 | ALPHATEST | |
  43758. * | 2 | ALPHABLEND | |
  43759. * | 3 | ALPHATESTANDBLEND | |
  43760. *
  43761. */
  43762. set: function (value) {
  43763. if (this._transparencyMode === value) {
  43764. return;
  43765. }
  43766. this._transparencyMode = value;
  43767. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43768. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43769. },
  43770. enumerable: true,
  43771. configurable: true
  43772. });
  43773. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43774. /**
  43775. * Returns true if alpha blending should be disabled.
  43776. */
  43777. get: function () {
  43778. return (this._linkRefractionWithTransparency ||
  43779. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43780. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43781. },
  43782. enumerable: true,
  43783. configurable: true
  43784. });
  43785. /**
  43786. * Specifies whether or not this material should be rendered in alpha blend mode.
  43787. */
  43788. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43789. if (this._disableAlphaBlending) {
  43790. return false;
  43791. }
  43792. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43793. };
  43794. /**
  43795. * Specifies if the mesh will require alpha blending.
  43796. * @param mesh - BJS mesh.
  43797. */
  43798. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43799. if (this._disableAlphaBlending) {
  43800. return false;
  43801. }
  43802. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43803. };
  43804. /**
  43805. * Specifies whether or not this material should be rendered in alpha test mode.
  43806. */
  43807. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43808. if (this._forceAlphaTest) {
  43809. return true;
  43810. }
  43811. if (this._linkRefractionWithTransparency) {
  43812. return false;
  43813. }
  43814. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43815. };
  43816. /**
  43817. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43818. */
  43819. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43820. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43821. };
  43822. /**
  43823. * Gets the texture used for the alpha test.
  43824. */
  43825. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43826. return this._albedoTexture;
  43827. };
  43828. /**
  43829. * Specifies that the submesh is ready to be used.
  43830. * @param mesh - BJS mesh.
  43831. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43832. * @param useInstances - Specifies that instances should be used.
  43833. * @returns - boolean indicating that the submesh is ready or not.
  43834. */
  43835. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43836. if (subMesh.effect && this.isFrozen) {
  43837. if (this._wasPreviouslyReady) {
  43838. return true;
  43839. }
  43840. }
  43841. if (!subMesh._materialDefines) {
  43842. subMesh._materialDefines = new PBRMaterialDefines();
  43843. }
  43844. var defines = subMesh._materialDefines;
  43845. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43846. if (defines._renderId === this.getScene().getRenderId()) {
  43847. return true;
  43848. }
  43849. }
  43850. var scene = this.getScene();
  43851. var engine = scene.getEngine();
  43852. if (defines._areTexturesDirty) {
  43853. if (scene.texturesEnabled) {
  43854. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43855. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43856. return false;
  43857. }
  43858. }
  43859. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43860. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43861. return false;
  43862. }
  43863. }
  43864. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43865. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43866. return false;
  43867. }
  43868. }
  43869. var reflectionTexture = this._getReflectionTexture();
  43870. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43871. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43872. return false;
  43873. }
  43874. }
  43875. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43876. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43877. return false;
  43878. }
  43879. }
  43880. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43881. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43882. return false;
  43883. }
  43884. }
  43885. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43886. if (this._metallicTexture) {
  43887. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43888. return false;
  43889. }
  43890. }
  43891. else if (this._reflectivityTexture) {
  43892. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43893. return false;
  43894. }
  43895. }
  43896. if (this._microSurfaceTexture) {
  43897. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43898. return false;
  43899. }
  43900. }
  43901. }
  43902. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43903. // Bump texture cannot be not blocking.
  43904. if (!this._bumpTexture.isReady()) {
  43905. return false;
  43906. }
  43907. }
  43908. var refractionTexture = this._getRefractionTexture();
  43909. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43910. if (!refractionTexture.isReadyOrNotBlocking()) {
  43911. return false;
  43912. }
  43913. }
  43914. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43915. // This is blocking.
  43916. if (!this._environmentBRDFTexture.isReady()) {
  43917. return false;
  43918. }
  43919. }
  43920. }
  43921. }
  43922. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43923. if (!this._imageProcessingConfiguration.isReady()) {
  43924. return false;
  43925. }
  43926. }
  43927. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43928. mesh.createNormals(true);
  43929. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43930. }
  43931. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43932. if (effect) {
  43933. scene.resetCachedMaterial();
  43934. subMesh.setEffect(effect, defines);
  43935. this.buildUniformLayout();
  43936. }
  43937. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43938. return false;
  43939. }
  43940. defines._renderId = scene.getRenderId();
  43941. this._wasPreviouslyReady = true;
  43942. return true;
  43943. };
  43944. /**
  43945. * Specifies if the material uses metallic roughness workflow.
  43946. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43947. */
  43948. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43949. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43950. return true;
  43951. }
  43952. return false;
  43953. };
  43954. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43955. if (onCompiled === void 0) { onCompiled = null; }
  43956. if (onError === void 0) { onError = null; }
  43957. if (useInstances === void 0) { useInstances = null; }
  43958. if (useClipPlane === void 0) { useClipPlane = null; }
  43959. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43960. if (!defines.isDirty) {
  43961. return null;
  43962. }
  43963. defines.markAsProcessed();
  43964. var scene = this.getScene();
  43965. var engine = scene.getEngine();
  43966. // Fallbacks
  43967. var fallbacks = new BABYLON.EffectFallbacks();
  43968. var fallbackRank = 0;
  43969. if (defines.USESPHERICALINVERTEX) {
  43970. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43971. }
  43972. if (defines.FOG) {
  43973. fallbacks.addFallback(fallbackRank, "FOG");
  43974. }
  43975. if (defines.SPECULARAA) {
  43976. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43977. }
  43978. if (defines.POINTSIZE) {
  43979. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43980. }
  43981. if (defines.LOGARITHMICDEPTH) {
  43982. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43983. }
  43984. if (defines.PARALLAX) {
  43985. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43986. }
  43987. if (defines.PARALLAXOCCLUSION) {
  43988. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43989. }
  43990. if (defines.ENVIRONMENTBRDF) {
  43991. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43992. }
  43993. if (defines.TANGENT) {
  43994. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43995. }
  43996. if (defines.BUMP) {
  43997. fallbacks.addFallback(fallbackRank++, "BUMP");
  43998. }
  43999. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44000. if (defines.SPECULARTERM) {
  44001. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44002. }
  44003. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44004. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44005. }
  44006. if (defines.LIGHTMAP) {
  44007. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44008. }
  44009. if (defines.NORMAL) {
  44010. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44011. }
  44012. if (defines.AMBIENT) {
  44013. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44014. }
  44015. if (defines.EMISSIVE) {
  44016. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44017. }
  44018. if (defines.VERTEXCOLOR) {
  44019. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44020. }
  44021. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44022. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44023. }
  44024. if (defines.MORPHTARGETS) {
  44025. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44026. }
  44027. //Attributes
  44028. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44029. if (defines.NORMAL) {
  44030. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44031. }
  44032. if (defines.TANGENT) {
  44033. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44034. }
  44035. if (defines.UV1) {
  44036. attribs.push(BABYLON.VertexBuffer.UVKind);
  44037. }
  44038. if (defines.UV2) {
  44039. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44040. }
  44041. if (defines.VERTEXCOLOR) {
  44042. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44043. }
  44044. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44045. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44046. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44047. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44048. "vFogInfos", "vFogColor", "pointSize",
  44049. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44050. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44051. "mBones",
  44052. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44053. "vLightingIntensity",
  44054. "logarithmicDepthConstant",
  44055. "vSphericalX", "vSphericalY", "vSphericalZ",
  44056. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44057. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44058. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44059. "vTangentSpaceParams"
  44060. ];
  44061. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44062. "bumpSampler", "lightmapSampler", "opacitySampler",
  44063. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44064. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44065. "microSurfaceSampler", "environmentBrdfSampler"];
  44066. var uniformBuffers = ["Material", "Scene"];
  44067. if (BABYLON.ImageProcessingConfiguration) {
  44068. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44069. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44070. }
  44071. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44072. uniformsNames: uniforms,
  44073. uniformBuffersNames: uniformBuffers,
  44074. samplers: samplers,
  44075. defines: defines,
  44076. maxSimultaneousLights: this._maxSimultaneousLights
  44077. });
  44078. var join = defines.toString();
  44079. return engine.createEffect("pbr", {
  44080. attributes: attribs,
  44081. uniformsNames: uniforms,
  44082. uniformBuffersNames: uniformBuffers,
  44083. samplers: samplers,
  44084. defines: join,
  44085. fallbacks: fallbacks,
  44086. onCompiled: onCompiled,
  44087. onError: onError,
  44088. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44089. }, engine);
  44090. };
  44091. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44092. if (useInstances === void 0) { useInstances = null; }
  44093. if (useClipPlane === void 0) { useClipPlane = null; }
  44094. var scene = this.getScene();
  44095. var engine = scene.getEngine();
  44096. // Lights
  44097. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44098. defines._needNormals = true;
  44099. // Textures
  44100. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44101. if (defines._areTexturesDirty) {
  44102. defines._needUVs = false;
  44103. if (scene.texturesEnabled) {
  44104. if (scene.getEngine().getCaps().textureLOD) {
  44105. defines.LODBASEDMICROSFURACE = true;
  44106. }
  44107. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44108. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44109. }
  44110. else {
  44111. defines.ALBEDO = false;
  44112. }
  44113. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44114. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44115. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44116. }
  44117. else {
  44118. defines.AMBIENT = false;
  44119. }
  44120. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44121. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44122. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44123. }
  44124. else {
  44125. defines.OPACITY = false;
  44126. }
  44127. var reflectionTexture = this._getReflectionTexture();
  44128. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44129. defines.REFLECTION = true;
  44130. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44131. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44132. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44133. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44134. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44135. defines.INVERTCUBICMAP = true;
  44136. }
  44137. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44138. switch (reflectionTexture.coordinatesMode) {
  44139. case BABYLON.Texture.EXPLICIT_MODE:
  44140. defines.REFLECTIONMAP_EXPLICIT = true;
  44141. break;
  44142. case BABYLON.Texture.PLANAR_MODE:
  44143. defines.REFLECTIONMAP_PLANAR = true;
  44144. break;
  44145. case BABYLON.Texture.PROJECTION_MODE:
  44146. defines.REFLECTIONMAP_PROJECTION = true;
  44147. break;
  44148. case BABYLON.Texture.SKYBOX_MODE:
  44149. defines.REFLECTIONMAP_SKYBOX = true;
  44150. break;
  44151. case BABYLON.Texture.SPHERICAL_MODE:
  44152. defines.REFLECTIONMAP_SPHERICAL = true;
  44153. break;
  44154. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44155. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44156. break;
  44157. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44158. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44159. break;
  44160. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44161. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44162. break;
  44163. case BABYLON.Texture.CUBIC_MODE:
  44164. case BABYLON.Texture.INVCUBIC_MODE:
  44165. default:
  44166. defines.REFLECTIONMAP_CUBIC = true;
  44167. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44168. break;
  44169. }
  44170. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44171. if (reflectionTexture.sphericalPolynomial) {
  44172. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44173. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44174. defines.USESPHERICALINVERTEX = false;
  44175. }
  44176. else {
  44177. defines.USESPHERICALINVERTEX = true;
  44178. }
  44179. }
  44180. }
  44181. }
  44182. else {
  44183. defines.REFLECTION = false;
  44184. defines.REFLECTIONMAP_3D = false;
  44185. defines.REFLECTIONMAP_SPHERICAL = false;
  44186. defines.REFLECTIONMAP_PLANAR = false;
  44187. defines.REFLECTIONMAP_CUBIC = false;
  44188. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44189. defines.REFLECTIONMAP_PROJECTION = false;
  44190. defines.REFLECTIONMAP_SKYBOX = false;
  44191. defines.REFLECTIONMAP_EXPLICIT = false;
  44192. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44193. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44194. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44195. defines.INVERTCUBICMAP = false;
  44196. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44197. defines.USESPHERICALINVERTEX = false;
  44198. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44199. defines.LODINREFLECTIONALPHA = false;
  44200. defines.GAMMAREFLECTION = false;
  44201. defines.RGBDREFLECTION = false;
  44202. }
  44203. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44204. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44205. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44206. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44207. }
  44208. else {
  44209. defines.LIGHTMAP = false;
  44210. }
  44211. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44212. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44213. }
  44214. else {
  44215. defines.EMISSIVE = false;
  44216. }
  44217. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44218. if (this._metallicTexture) {
  44219. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44220. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44221. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44222. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44223. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44224. }
  44225. else if (this._reflectivityTexture) {
  44226. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44227. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44228. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44229. }
  44230. else {
  44231. defines.REFLECTIVITY = false;
  44232. }
  44233. if (this._microSurfaceTexture) {
  44234. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44235. }
  44236. else {
  44237. defines.MICROSURFACEMAP = false;
  44238. }
  44239. }
  44240. else {
  44241. defines.REFLECTIVITY = false;
  44242. defines.MICROSURFACEMAP = false;
  44243. }
  44244. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44245. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44246. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44247. defines.PARALLAX = true;
  44248. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44249. }
  44250. else {
  44251. defines.PARALLAX = false;
  44252. }
  44253. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44254. }
  44255. else {
  44256. defines.BUMP = false;
  44257. }
  44258. var refractionTexture = this._getRefractionTexture();
  44259. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44260. defines.REFRACTION = true;
  44261. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44262. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44263. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44264. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44265. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44266. if (this._linkRefractionWithTransparency) {
  44267. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44268. }
  44269. }
  44270. else {
  44271. defines.REFRACTION = false;
  44272. }
  44273. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44274. defines.ENVIRONMENTBRDF = true;
  44275. }
  44276. else {
  44277. defines.ENVIRONMENTBRDF = false;
  44278. }
  44279. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44280. defines.ALPHAFROMALBEDO = true;
  44281. }
  44282. else {
  44283. defines.ALPHAFROMALBEDO = false;
  44284. }
  44285. }
  44286. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44287. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44288. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44289. if (!this.backFaceCulling && this._twoSidedLighting) {
  44290. defines.TWOSIDEDLIGHTING = true;
  44291. }
  44292. else {
  44293. defines.TWOSIDEDLIGHTING = false;
  44294. }
  44295. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44296. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44297. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44298. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44299. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44300. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44301. }
  44302. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44303. this._imageProcessingConfiguration.prepareDefines(defines);
  44304. }
  44305. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44306. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44307. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44308. // Misc.
  44309. if (defines._areMiscDirty) {
  44310. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44311. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44312. }
  44313. // Values that need to be evaluated on every frame
  44314. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44315. // Attribs
  44316. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44317. };
  44318. /**
  44319. * Force shader compilation
  44320. */
  44321. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44322. var _this = this;
  44323. var localOptions = __assign({ clipPlane: false }, options);
  44324. var defines = new PBRMaterialDefines();
  44325. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44326. if (effect.isReady()) {
  44327. if (onCompiled) {
  44328. onCompiled(this);
  44329. }
  44330. }
  44331. else {
  44332. effect.onCompileObservable.add(function () {
  44333. if (onCompiled) {
  44334. onCompiled(_this);
  44335. }
  44336. });
  44337. }
  44338. };
  44339. /**
  44340. * Initializes the uniform buffer layout for the shader.
  44341. */
  44342. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44343. // Order is important !
  44344. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44345. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44346. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44347. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44348. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44349. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44350. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44351. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44352. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44353. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44354. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44355. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44356. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44357. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44358. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44359. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44360. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44361. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44362. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44363. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44364. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44365. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44366. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44367. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44368. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44369. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44370. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44371. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44372. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44373. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44374. this._uniformBuffer.addUniform("pointSize", 1);
  44375. this._uniformBuffer.create();
  44376. };
  44377. /**
  44378. * Unbinds the textures.
  44379. */
  44380. PBRBaseMaterial.prototype.unbind = function () {
  44381. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44382. this._uniformBuffer.setTexture("reflectionSampler", null);
  44383. }
  44384. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44385. this._uniformBuffer.setTexture("refractionSampler", null);
  44386. }
  44387. _super.prototype.unbind.call(this);
  44388. };
  44389. /**
  44390. * Binds the submesh data.
  44391. * @param world - The world matrix.
  44392. * @param mesh - The BJS mesh.
  44393. * @param subMesh - A submesh of the BJS mesh.
  44394. */
  44395. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44396. var scene = this.getScene();
  44397. var defines = subMesh._materialDefines;
  44398. if (!defines) {
  44399. return;
  44400. }
  44401. var effect = subMesh.effect;
  44402. if (!effect) {
  44403. return;
  44404. }
  44405. this._activeEffect = effect;
  44406. // Matrices
  44407. this.bindOnlyWorldMatrix(world);
  44408. // Normal Matrix
  44409. if (defines.OBJECTSPACE_NORMALMAP) {
  44410. world.toNormalMatrix(this._normalMatrix);
  44411. this.bindOnlyNormalMatrix(this._normalMatrix);
  44412. }
  44413. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44414. // Bones
  44415. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44416. var reflectionTexture = null;
  44417. if (mustRebind) {
  44418. this._uniformBuffer.bindToEffect(effect, "Material");
  44419. this.bindViewProjection(effect);
  44420. reflectionTexture = this._getReflectionTexture();
  44421. var refractionTexture = this._getRefractionTexture();
  44422. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44423. // Texture uniforms
  44424. if (scene.texturesEnabled) {
  44425. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44426. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44427. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44428. }
  44429. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44430. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44431. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44432. }
  44433. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44434. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44435. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44436. }
  44437. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44438. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44439. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44440. if (reflectionTexture.boundingBoxSize) {
  44441. var cubeTexture = reflectionTexture;
  44442. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44443. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44444. }
  44445. var polynomials = reflectionTexture.sphericalPolynomial;
  44446. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44447. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44448. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44449. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44450. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44451. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44452. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44453. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44454. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44455. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44456. }
  44457. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44458. }
  44459. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44460. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44461. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44462. }
  44463. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44464. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44465. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44466. }
  44467. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44468. if (this._metallicTexture) {
  44469. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44470. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44471. }
  44472. else if (this._reflectivityTexture) {
  44473. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44474. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44475. }
  44476. if (this._microSurfaceTexture) {
  44477. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44478. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44479. }
  44480. }
  44481. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44482. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44483. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44484. if (scene._mirroredCameraPosition) {
  44485. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44486. }
  44487. else {
  44488. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44489. }
  44490. }
  44491. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44492. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44493. var depth = 1.0;
  44494. if (!refractionTexture.isCube) {
  44495. if (refractionTexture.depth) {
  44496. depth = refractionTexture.depth;
  44497. }
  44498. }
  44499. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44500. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44501. }
  44502. }
  44503. // Point size
  44504. if (this.pointsCloud) {
  44505. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44506. }
  44507. // Colors
  44508. if (defines.METALLICWORKFLOW) {
  44509. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44510. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44511. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44512. }
  44513. else {
  44514. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44515. }
  44516. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44517. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44518. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44519. // Misc
  44520. this._lightingInfos.x = this._directIntensity;
  44521. this._lightingInfos.y = this._emissiveIntensity;
  44522. this._lightingInfos.z = this._environmentIntensity;
  44523. this._lightingInfos.w = this._specularIntensity;
  44524. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44525. }
  44526. // Textures
  44527. if (scene.texturesEnabled) {
  44528. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44529. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44530. }
  44531. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44532. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44533. }
  44534. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44535. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44536. }
  44537. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44538. if (defines.LODBASEDMICROSFURACE) {
  44539. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44540. }
  44541. else {
  44542. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44543. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44544. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44545. }
  44546. }
  44547. if (defines.ENVIRONMENTBRDF) {
  44548. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44549. }
  44550. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44551. if (defines.LODBASEDMICROSFURACE) {
  44552. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44553. }
  44554. else {
  44555. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44556. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44557. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44558. }
  44559. }
  44560. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44561. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44562. }
  44563. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44564. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44565. }
  44566. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44567. if (this._metallicTexture) {
  44568. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44569. }
  44570. else if (this._reflectivityTexture) {
  44571. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44572. }
  44573. if (this._microSurfaceTexture) {
  44574. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44575. }
  44576. }
  44577. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44578. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44579. }
  44580. }
  44581. // Clip plane
  44582. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44583. // Colors
  44584. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44585. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44586. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44587. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44588. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44589. }
  44590. if (mustRebind || !this.isFrozen) {
  44591. // Lights
  44592. if (scene.lightsEnabled && !this._disableLighting) {
  44593. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44594. }
  44595. // View
  44596. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44597. this.bindView(effect);
  44598. }
  44599. // Fog
  44600. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44601. // Morph targets
  44602. if (defines.NUM_MORPH_INFLUENCERS) {
  44603. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44604. }
  44605. // image processing
  44606. this._imageProcessingConfiguration.bind(this._activeEffect);
  44607. // Log. depth
  44608. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44609. }
  44610. this._uniformBuffer.update();
  44611. this._afterBind(mesh, this._activeEffect);
  44612. };
  44613. /**
  44614. * Returns the animatable textures.
  44615. * @returns - Array of animatable textures.
  44616. */
  44617. PBRBaseMaterial.prototype.getAnimatables = function () {
  44618. var results = [];
  44619. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44620. results.push(this._albedoTexture);
  44621. }
  44622. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44623. results.push(this._ambientTexture);
  44624. }
  44625. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44626. results.push(this._opacityTexture);
  44627. }
  44628. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44629. results.push(this._reflectionTexture);
  44630. }
  44631. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44632. results.push(this._emissiveTexture);
  44633. }
  44634. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44635. results.push(this._metallicTexture);
  44636. }
  44637. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44638. results.push(this._reflectivityTexture);
  44639. }
  44640. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44641. results.push(this._bumpTexture);
  44642. }
  44643. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44644. results.push(this._lightmapTexture);
  44645. }
  44646. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44647. results.push(this._refractionTexture);
  44648. }
  44649. return results;
  44650. };
  44651. /**
  44652. * Returns the texture used for reflections.
  44653. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44654. */
  44655. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44656. if (this._reflectionTexture) {
  44657. return this._reflectionTexture;
  44658. }
  44659. return this.getScene().environmentTexture;
  44660. };
  44661. /**
  44662. * Returns the texture used for refraction or null if none is used.
  44663. * @returns - Refection texture if present. If no refraction texture and refraction
  44664. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44665. */
  44666. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44667. if (this._refractionTexture) {
  44668. return this._refractionTexture;
  44669. }
  44670. if (this._linkRefractionWithTransparency) {
  44671. return this.getScene().environmentTexture;
  44672. }
  44673. return null;
  44674. };
  44675. /**
  44676. * Disposes the resources of the material.
  44677. * @param forceDisposeEffect - Forces the disposal of effects.
  44678. * @param forceDisposeTextures - Forces the disposal of all textures.
  44679. */
  44680. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44681. if (forceDisposeTextures) {
  44682. if (this._albedoTexture) {
  44683. this._albedoTexture.dispose();
  44684. }
  44685. if (this._ambientTexture) {
  44686. this._ambientTexture.dispose();
  44687. }
  44688. if (this._opacityTexture) {
  44689. this._opacityTexture.dispose();
  44690. }
  44691. if (this._reflectionTexture) {
  44692. this._reflectionTexture.dispose();
  44693. }
  44694. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44695. this._environmentBRDFTexture.dispose();
  44696. }
  44697. if (this._emissiveTexture) {
  44698. this._emissiveTexture.dispose();
  44699. }
  44700. if (this._metallicTexture) {
  44701. this._metallicTexture.dispose();
  44702. }
  44703. if (this._reflectivityTexture) {
  44704. this._reflectivityTexture.dispose();
  44705. }
  44706. if (this._bumpTexture) {
  44707. this._bumpTexture.dispose();
  44708. }
  44709. if (this._lightmapTexture) {
  44710. this._lightmapTexture.dispose();
  44711. }
  44712. if (this._refractionTexture) {
  44713. this._refractionTexture.dispose();
  44714. }
  44715. }
  44716. this._renderTargets.dispose();
  44717. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44718. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44719. }
  44720. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44721. };
  44722. /**
  44723. * Stores the reflectivity values based on metallic roughness workflow.
  44724. */
  44725. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44726. __decorate([
  44727. BABYLON.serializeAsImageProcessingConfiguration()
  44728. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44729. __decorate([
  44730. BABYLON.serialize()
  44731. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44732. __decorate([
  44733. BABYLON.serialize()
  44734. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44735. return PBRBaseMaterial;
  44736. }(BABYLON.PushMaterial));
  44737. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44738. })(BABYLON || (BABYLON = {}));
  44739. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44740. var BABYLON;
  44741. (function (BABYLON) {
  44742. /**
  44743. * The Physically based simple base material of BJS.
  44744. *
  44745. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44746. * It is used as the base class for both the specGloss and metalRough conventions.
  44747. */
  44748. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44749. __extends(PBRBaseSimpleMaterial, _super);
  44750. /**
  44751. * Instantiates a new PBRMaterial instance.
  44752. *
  44753. * @param name The material name
  44754. * @param scene The scene the material will be use in.
  44755. */
  44756. function PBRBaseSimpleMaterial(name, scene) {
  44757. var _this = _super.call(this, name, scene) || this;
  44758. /**
  44759. * Number of Simultaneous lights allowed on the material.
  44760. */
  44761. _this.maxSimultaneousLights = 4;
  44762. /**
  44763. * If sets to true, disables all the lights affecting the material.
  44764. */
  44765. _this.disableLighting = false;
  44766. /**
  44767. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44768. */
  44769. _this.invertNormalMapX = false;
  44770. /**
  44771. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44772. */
  44773. _this.invertNormalMapY = false;
  44774. /**
  44775. * Emissivie color used to self-illuminate the model.
  44776. */
  44777. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44778. /**
  44779. * Occlusion Channel Strenght.
  44780. */
  44781. _this.occlusionStrength = 1.0;
  44782. _this.useLightmapAsShadowmap = false;
  44783. _this._useAlphaFromAlbedoTexture = true;
  44784. _this._useAmbientInGrayScale = true;
  44785. return _this;
  44786. }
  44787. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44788. /**
  44789. * Gets the current double sided mode.
  44790. */
  44791. get: function () {
  44792. return this._twoSidedLighting;
  44793. },
  44794. /**
  44795. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44796. */
  44797. set: function (value) {
  44798. if (this._twoSidedLighting === value) {
  44799. return;
  44800. }
  44801. this._twoSidedLighting = value;
  44802. this.backFaceCulling = !value;
  44803. this._markAllSubMeshesAsTexturesDirty();
  44804. },
  44805. enumerable: true,
  44806. configurable: true
  44807. });
  44808. /**
  44809. * Return the active textures of the material.
  44810. */
  44811. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44812. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44813. if (this.environmentTexture) {
  44814. activeTextures.push(this.environmentTexture);
  44815. }
  44816. if (this.normalTexture) {
  44817. activeTextures.push(this.normalTexture);
  44818. }
  44819. if (this.emissiveTexture) {
  44820. activeTextures.push(this.emissiveTexture);
  44821. }
  44822. if (this.occlusionTexture) {
  44823. activeTextures.push(this.occlusionTexture);
  44824. }
  44825. if (this.lightmapTexture) {
  44826. activeTextures.push(this.lightmapTexture);
  44827. }
  44828. return activeTextures;
  44829. };
  44830. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44831. if (_super.prototype.hasTexture.call(this, texture)) {
  44832. return true;
  44833. }
  44834. if (this.lightmapTexture === texture) {
  44835. return true;
  44836. }
  44837. return false;
  44838. };
  44839. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44840. return "PBRBaseSimpleMaterial";
  44841. };
  44842. __decorate([
  44843. BABYLON.serialize(),
  44844. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44845. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44846. __decorate([
  44847. BABYLON.serialize(),
  44848. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44849. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44850. __decorate([
  44851. BABYLON.serializeAsTexture(),
  44852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44853. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44854. __decorate([
  44855. BABYLON.serialize(),
  44856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44857. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44858. __decorate([
  44859. BABYLON.serialize(),
  44860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44861. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44862. __decorate([
  44863. BABYLON.serializeAsTexture(),
  44864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44865. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44866. __decorate([
  44867. BABYLON.serializeAsColor3("emissive"),
  44868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44869. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44870. __decorate([
  44871. BABYLON.serializeAsTexture(),
  44872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44873. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44874. __decorate([
  44875. BABYLON.serialize(),
  44876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44877. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44878. __decorate([
  44879. BABYLON.serializeAsTexture(),
  44880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44881. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44882. __decorate([
  44883. BABYLON.serialize(),
  44884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44885. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44886. __decorate([
  44887. BABYLON.serialize()
  44888. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44889. __decorate([
  44890. BABYLON.serializeAsTexture(),
  44891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44892. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44893. __decorate([
  44894. BABYLON.serialize(),
  44895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44896. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44897. return PBRBaseSimpleMaterial;
  44898. }(BABYLON.PBRBaseMaterial));
  44899. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44900. })(BABYLON || (BABYLON = {}));
  44901. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44902. var BABYLON;
  44903. (function (BABYLON) {
  44904. /**
  44905. * The Physically based material of BJS.
  44906. *
  44907. * This offers the main features of a standard PBR material.
  44908. * For more information, please refer to the documentation :
  44909. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44910. */
  44911. var PBRMaterial = /** @class */ (function (_super) {
  44912. __extends(PBRMaterial, _super);
  44913. /**
  44914. * Instantiates a new PBRMaterial instance.
  44915. *
  44916. * @param name The material name
  44917. * @param scene The scene the material will be use in.
  44918. */
  44919. function PBRMaterial(name, scene) {
  44920. var _this = _super.call(this, name, scene) || this;
  44921. /**
  44922. * Intensity of the direct lights e.g. the four lights available in your scene.
  44923. * This impacts both the direct diffuse and specular highlights.
  44924. */
  44925. _this.directIntensity = 1.0;
  44926. /**
  44927. * Intensity of the emissive part of the material.
  44928. * This helps controlling the emissive effect without modifying the emissive color.
  44929. */
  44930. _this.emissiveIntensity = 1.0;
  44931. /**
  44932. * Intensity of the environment e.g. how much the environment will light the object
  44933. * either through harmonics for rough material or through the refelction for shiny ones.
  44934. */
  44935. _this.environmentIntensity = 1.0;
  44936. /**
  44937. * This is a special control allowing the reduction of the specular highlights coming from the
  44938. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44939. */
  44940. _this.specularIntensity = 1.0;
  44941. /**
  44942. * Debug Control allowing disabling the bump map on this material.
  44943. */
  44944. _this.disableBumpMap = false;
  44945. /**
  44946. * AKA Occlusion Texture Intensity in other nomenclature.
  44947. */
  44948. _this.ambientTextureStrength = 1.0;
  44949. /**
  44950. * The color of a material in ambient lighting.
  44951. */
  44952. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44953. /**
  44954. * AKA Diffuse Color in other nomenclature.
  44955. */
  44956. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44957. /**
  44958. * AKA Specular Color in other nomenclature.
  44959. */
  44960. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44961. /**
  44962. * The color reflected from the material.
  44963. */
  44964. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44965. /**
  44966. * The color emitted from the material.
  44967. */
  44968. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44969. /**
  44970. * AKA Glossiness in other nomenclature.
  44971. */
  44972. _this.microSurface = 1.0;
  44973. /**
  44974. * source material index of refraction (IOR)' / 'destination material IOR.
  44975. */
  44976. _this.indexOfRefraction = 0.66;
  44977. /**
  44978. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44979. */
  44980. _this.invertRefractionY = false;
  44981. /**
  44982. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44983. * Materials half opaque for instance using refraction could benefit from this control.
  44984. */
  44985. _this.linkRefractionWithTransparency = false;
  44986. _this.useLightmapAsShadowmap = false;
  44987. /**
  44988. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44989. */
  44990. _this.useAlphaFromAlbedoTexture = false;
  44991. /**
  44992. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44993. */
  44994. _this.forceAlphaTest = false;
  44995. /**
  44996. * Defines the alpha limits in alpha test mode.
  44997. */
  44998. _this.alphaCutOff = 0.4;
  44999. /**
  45000. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45001. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45002. */
  45003. _this.useSpecularOverAlpha = true;
  45004. /**
  45005. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45006. */
  45007. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45008. /**
  45009. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45010. */
  45011. _this.useRoughnessFromMetallicTextureAlpha = true;
  45012. /**
  45013. * Specifies if the metallic texture contains the roughness information in its green channel.
  45014. */
  45015. _this.useRoughnessFromMetallicTextureGreen = false;
  45016. /**
  45017. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45018. */
  45019. _this.useMetallnessFromMetallicTextureBlue = false;
  45020. /**
  45021. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45022. */
  45023. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45024. /**
  45025. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45026. */
  45027. _this.useAmbientInGrayScale = false;
  45028. /**
  45029. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45030. * The material will try to infer what glossiness each pixel should be.
  45031. */
  45032. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45033. /**
  45034. * BJS is using an harcoded light falloff based on a manually sets up range.
  45035. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45036. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45037. */
  45038. _this.usePhysicalLightFalloff = true;
  45039. /**
  45040. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45041. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45042. */
  45043. _this.useRadianceOverAlpha = true;
  45044. /**
  45045. * Allows using an object space normal map (instead of tangent space).
  45046. */
  45047. _this.useObjectSpaceNormalMap = false;
  45048. /**
  45049. * Allows using the bump map in parallax mode.
  45050. */
  45051. _this.useParallax = false;
  45052. /**
  45053. * Allows using the bump map in parallax occlusion mode.
  45054. */
  45055. _this.useParallaxOcclusion = false;
  45056. /**
  45057. * Controls the scale bias of the parallax mode.
  45058. */
  45059. _this.parallaxScaleBias = 0.05;
  45060. /**
  45061. * If sets to true, disables all the lights affecting the material.
  45062. */
  45063. _this.disableLighting = false;
  45064. /**
  45065. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45066. */
  45067. _this.forceIrradianceInFragment = false;
  45068. /**
  45069. * Number of Simultaneous lights allowed on the material.
  45070. */
  45071. _this.maxSimultaneousLights = 4;
  45072. /**
  45073. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45074. */
  45075. _this.invertNormalMapX = false;
  45076. /**
  45077. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45078. */
  45079. _this.invertNormalMapY = false;
  45080. /**
  45081. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45082. */
  45083. _this.twoSidedLighting = false;
  45084. /**
  45085. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45086. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45087. */
  45088. _this.useAlphaFresnel = false;
  45089. /**
  45090. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45091. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45092. */
  45093. _this.useLinearAlphaFresnel = false;
  45094. /**
  45095. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45096. * And/Or occlude the blended part.
  45097. */
  45098. _this.environmentBRDFTexture = null;
  45099. /**
  45100. * Force normal to face away from face.
  45101. */
  45102. _this.forceNormalForward = false;
  45103. /**
  45104. * Enables specular anti aliasing in the PBR shader.
  45105. * It will both interacts on the Geometry for analytical and IBL lighting.
  45106. * It also prefilter the roughness map based on the bump values.
  45107. */
  45108. _this.enableSpecularAntiAliasing = false;
  45109. /**
  45110. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45111. * makes the reflect vector face the model (under horizon).
  45112. */
  45113. _this.useHorizonOcclusion = true;
  45114. /**
  45115. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45116. * too much the area relying on ambient texture to define their ambient occlusion.
  45117. */
  45118. _this.useRadianceOcclusion = true;
  45119. /**
  45120. * If set to true, no lighting calculations will be applied.
  45121. */
  45122. _this.unlit = false;
  45123. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45124. return _this;
  45125. }
  45126. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45127. /**
  45128. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45129. */
  45130. get: function () {
  45131. return this._PBRMATERIAL_OPAQUE;
  45132. },
  45133. enumerable: true,
  45134. configurable: true
  45135. });
  45136. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45137. /**
  45138. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45139. */
  45140. get: function () {
  45141. return this._PBRMATERIAL_ALPHATEST;
  45142. },
  45143. enumerable: true,
  45144. configurable: true
  45145. });
  45146. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45147. /**
  45148. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45149. */
  45150. get: function () {
  45151. return this._PBRMATERIAL_ALPHABLEND;
  45152. },
  45153. enumerable: true,
  45154. configurable: true
  45155. });
  45156. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45157. /**
  45158. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45159. * They are also discarded below the alpha cutoff threshold to improve performances.
  45160. */
  45161. get: function () {
  45162. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45163. },
  45164. enumerable: true,
  45165. configurable: true
  45166. });
  45167. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45168. /**
  45169. * Gets the image processing configuration used either in this material.
  45170. */
  45171. get: function () {
  45172. return this._imageProcessingConfiguration;
  45173. },
  45174. /**
  45175. * Sets the Default image processing configuration used either in the this material.
  45176. *
  45177. * If sets to null, the scene one is in use.
  45178. */
  45179. set: function (value) {
  45180. this._attachImageProcessingConfiguration(value);
  45181. // Ensure the effect will be rebuilt.
  45182. this._markAllSubMeshesAsTexturesDirty();
  45183. },
  45184. enumerable: true,
  45185. configurable: true
  45186. });
  45187. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45188. /**
  45189. * Gets wether the color curves effect is enabled.
  45190. */
  45191. get: function () {
  45192. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45193. },
  45194. /**
  45195. * Sets wether the color curves effect is enabled.
  45196. */
  45197. set: function (value) {
  45198. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45199. },
  45200. enumerable: true,
  45201. configurable: true
  45202. });
  45203. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45204. /**
  45205. * Gets wether the color grading effect is enabled.
  45206. */
  45207. get: function () {
  45208. return this.imageProcessingConfiguration.colorGradingEnabled;
  45209. },
  45210. /**
  45211. * Gets wether the color grading effect is enabled.
  45212. */
  45213. set: function (value) {
  45214. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45220. /**
  45221. * Gets wether tonemapping is enabled or not.
  45222. */
  45223. get: function () {
  45224. return this._imageProcessingConfiguration.toneMappingEnabled;
  45225. },
  45226. /**
  45227. * Sets wether tonemapping is enabled or not
  45228. */
  45229. set: function (value) {
  45230. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45231. },
  45232. enumerable: true,
  45233. configurable: true
  45234. });
  45235. ;
  45236. ;
  45237. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45238. /**
  45239. * The camera exposure used on this material.
  45240. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45241. * This corresponds to a photographic exposure.
  45242. */
  45243. get: function () {
  45244. return this._imageProcessingConfiguration.exposure;
  45245. },
  45246. /**
  45247. * The camera exposure used on this material.
  45248. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45249. * This corresponds to a photographic exposure.
  45250. */
  45251. set: function (value) {
  45252. this._imageProcessingConfiguration.exposure = value;
  45253. },
  45254. enumerable: true,
  45255. configurable: true
  45256. });
  45257. ;
  45258. ;
  45259. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45260. /**
  45261. * Gets The camera contrast used on this material.
  45262. */
  45263. get: function () {
  45264. return this._imageProcessingConfiguration.contrast;
  45265. },
  45266. /**
  45267. * Sets The camera contrast used on this material.
  45268. */
  45269. set: function (value) {
  45270. this._imageProcessingConfiguration.contrast = value;
  45271. },
  45272. enumerable: true,
  45273. configurable: true
  45274. });
  45275. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45276. /**
  45277. * Gets the Color Grading 2D Lookup Texture.
  45278. */
  45279. get: function () {
  45280. return this._imageProcessingConfiguration.colorGradingTexture;
  45281. },
  45282. /**
  45283. * Sets the Color Grading 2D Lookup Texture.
  45284. */
  45285. set: function (value) {
  45286. this._imageProcessingConfiguration.colorGradingTexture = value;
  45287. },
  45288. enumerable: true,
  45289. configurable: true
  45290. });
  45291. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45292. /**
  45293. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45294. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45295. * 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;
  45296. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45297. */
  45298. get: function () {
  45299. return this._imageProcessingConfiguration.colorCurves;
  45300. },
  45301. /**
  45302. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45303. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45304. * 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;
  45305. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45306. */
  45307. set: function (value) {
  45308. this._imageProcessingConfiguration.colorCurves = value;
  45309. },
  45310. enumerable: true,
  45311. configurable: true
  45312. });
  45313. /**
  45314. * Returns the name of this material class.
  45315. */
  45316. PBRMaterial.prototype.getClassName = function () {
  45317. return "PBRMaterial";
  45318. };
  45319. /**
  45320. * Returns an array of the actively used textures.
  45321. * @returns - Array of BaseTextures
  45322. */
  45323. PBRMaterial.prototype.getActiveTextures = function () {
  45324. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45325. if (this._albedoTexture) {
  45326. activeTextures.push(this._albedoTexture);
  45327. }
  45328. if (this._ambientTexture) {
  45329. activeTextures.push(this._ambientTexture);
  45330. }
  45331. if (this._opacityTexture) {
  45332. activeTextures.push(this._opacityTexture);
  45333. }
  45334. if (this._reflectionTexture) {
  45335. activeTextures.push(this._reflectionTexture);
  45336. }
  45337. if (this._emissiveTexture) {
  45338. activeTextures.push(this._emissiveTexture);
  45339. }
  45340. if (this._reflectivityTexture) {
  45341. activeTextures.push(this._reflectivityTexture);
  45342. }
  45343. if (this._metallicTexture) {
  45344. activeTextures.push(this._metallicTexture);
  45345. }
  45346. if (this._microSurfaceTexture) {
  45347. activeTextures.push(this._microSurfaceTexture);
  45348. }
  45349. if (this._bumpTexture) {
  45350. activeTextures.push(this._bumpTexture);
  45351. }
  45352. if (this._lightmapTexture) {
  45353. activeTextures.push(this._lightmapTexture);
  45354. }
  45355. if (this._refractionTexture) {
  45356. activeTextures.push(this._refractionTexture);
  45357. }
  45358. return activeTextures;
  45359. };
  45360. /**
  45361. * Checks to see if a texture is used in the material.
  45362. * @param texture - Base texture to use.
  45363. * @returns - Boolean specifying if a texture is used in the material.
  45364. */
  45365. PBRMaterial.prototype.hasTexture = function (texture) {
  45366. if (_super.prototype.hasTexture.call(this, texture)) {
  45367. return true;
  45368. }
  45369. if (this._albedoTexture === texture) {
  45370. return true;
  45371. }
  45372. if (this._ambientTexture === texture) {
  45373. return true;
  45374. }
  45375. if (this._opacityTexture === texture) {
  45376. return true;
  45377. }
  45378. if (this._reflectionTexture === texture) {
  45379. return true;
  45380. }
  45381. if (this._reflectivityTexture === texture) {
  45382. return true;
  45383. }
  45384. if (this._metallicTexture === texture) {
  45385. return true;
  45386. }
  45387. if (this._microSurfaceTexture === texture) {
  45388. return true;
  45389. }
  45390. if (this._bumpTexture === texture) {
  45391. return true;
  45392. }
  45393. if (this._lightmapTexture === texture) {
  45394. return true;
  45395. }
  45396. if (this._refractionTexture === texture) {
  45397. return true;
  45398. }
  45399. return false;
  45400. };
  45401. /**
  45402. * Makes a duplicate of the current material.
  45403. * @param name - name to use for the new material.
  45404. */
  45405. PBRMaterial.prototype.clone = function (name) {
  45406. var _this = this;
  45407. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45408. clone.id = name;
  45409. clone.name = name;
  45410. return clone;
  45411. };
  45412. /**
  45413. * Serializes this PBR Material.
  45414. * @returns - An object with the serialized material.
  45415. */
  45416. PBRMaterial.prototype.serialize = function () {
  45417. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45418. serializationObject.customType = "BABYLON.PBRMaterial";
  45419. return serializationObject;
  45420. };
  45421. // Statics
  45422. /**
  45423. * Parses a PBR Material from a serialized object.
  45424. * @param source - Serialized object.
  45425. * @param scene - BJS scene instance.
  45426. * @param rootUrl - url for the scene object
  45427. * @returns - PBRMaterial
  45428. */
  45429. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45430. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45431. };
  45432. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45433. /**
  45434. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45435. */
  45436. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45437. /**
  45438. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45439. */
  45440. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45441. /**
  45442. * 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.
  45443. * They are also discarded below the alpha cutoff threshold to improve performances.
  45444. */
  45445. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45446. __decorate([
  45447. BABYLON.serialize(),
  45448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45449. ], PBRMaterial.prototype, "directIntensity", void 0);
  45450. __decorate([
  45451. BABYLON.serialize(),
  45452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45453. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45454. __decorate([
  45455. BABYLON.serialize(),
  45456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45457. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45458. __decorate([
  45459. BABYLON.serialize(),
  45460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45461. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45462. __decorate([
  45463. BABYLON.serialize(),
  45464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45465. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45466. __decorate([
  45467. BABYLON.serializeAsTexture(),
  45468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45469. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45470. __decorate([
  45471. BABYLON.serializeAsTexture(),
  45472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45473. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45474. __decorate([
  45475. BABYLON.serialize(),
  45476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45477. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45478. __decorate([
  45479. BABYLON.serializeAsTexture(),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45481. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45482. __decorate([
  45483. BABYLON.serializeAsTexture(),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45485. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45486. __decorate([
  45487. BABYLON.serializeAsTexture(),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45489. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45490. __decorate([
  45491. BABYLON.serializeAsTexture(),
  45492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45493. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45494. __decorate([
  45495. BABYLON.serializeAsTexture(),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45497. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45498. __decorate([
  45499. BABYLON.serialize(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "metallic", void 0);
  45502. __decorate([
  45503. BABYLON.serialize(),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45505. ], PBRMaterial.prototype, "roughness", void 0);
  45506. __decorate([
  45507. BABYLON.serializeAsTexture(),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45509. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45510. __decorate([
  45511. BABYLON.serializeAsTexture(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45514. __decorate([
  45515. BABYLON.serializeAsTexture(),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45517. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45518. __decorate([
  45519. BABYLON.serializeAsTexture(),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45521. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45522. __decorate([
  45523. BABYLON.serializeAsColor3("ambient"),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], PBRMaterial.prototype, "ambientColor", void 0);
  45526. __decorate([
  45527. BABYLON.serializeAsColor3("albedo"),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45529. ], PBRMaterial.prototype, "albedoColor", void 0);
  45530. __decorate([
  45531. BABYLON.serializeAsColor3("reflectivity"),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45534. __decorate([
  45535. BABYLON.serializeAsColor3("reflection"),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45538. __decorate([
  45539. BABYLON.serializeAsColor3("emissive"),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45541. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45542. __decorate([
  45543. BABYLON.serialize(),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45545. ], PBRMaterial.prototype, "microSurface", void 0);
  45546. __decorate([
  45547. BABYLON.serialize(),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45549. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45550. __decorate([
  45551. BABYLON.serialize(),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45553. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45554. __decorate([
  45555. BABYLON.serialize(),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45558. __decorate([
  45559. BABYLON.serialize(),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45562. __decorate([
  45563. BABYLON.serialize(),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45565. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45566. __decorate([
  45567. BABYLON.serialize(),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45569. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45570. __decorate([
  45571. BABYLON.serialize(),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45573. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45574. __decorate([
  45575. BABYLON.serialize(),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45577. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45578. __decorate([
  45579. BABYLON.serialize(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45581. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45582. __decorate([
  45583. BABYLON.serialize(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45586. __decorate([
  45587. BABYLON.serialize(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45589. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45597. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45598. __decorate([
  45599. BABYLON.serialize(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45601. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45613. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRMaterial.prototype, "useParallax", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45633. ], PBRMaterial.prototype, "disableLighting", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45641. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45642. __decorate([
  45643. BABYLON.serialize(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45645. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45658. __decorate([
  45659. BABYLON.serialize(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45662. __decorate([
  45663. BABYLON.serializeAsTexture(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45665. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45666. __decorate([
  45667. BABYLON.serialize(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45670. __decorate([
  45671. BABYLON.serialize(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45674. __decorate([
  45675. BABYLON.serialize(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45685. ], PBRMaterial.prototype, "unlit", void 0);
  45686. return PBRMaterial;
  45687. }(BABYLON.PBRBaseMaterial));
  45688. BABYLON.PBRMaterial = PBRMaterial;
  45689. })(BABYLON || (BABYLON = {}));
  45690. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45691. var BABYLON;
  45692. (function (BABYLON) {
  45693. /**
  45694. * The PBR material of BJS following the metal roughness convention.
  45695. *
  45696. * This fits to the PBR convention in the GLTF definition:
  45697. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45698. */
  45699. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45700. __extends(PBRMetallicRoughnessMaterial, _super);
  45701. /**
  45702. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45703. *
  45704. * @param name The material name
  45705. * @param scene The scene the material will be use in.
  45706. */
  45707. function PBRMetallicRoughnessMaterial(name, scene) {
  45708. var _this = _super.call(this, name, scene) || this;
  45709. _this._useRoughnessFromMetallicTextureAlpha = false;
  45710. _this._useRoughnessFromMetallicTextureGreen = true;
  45711. _this._useMetallnessFromMetallicTextureBlue = true;
  45712. _this.metallic = 1.0;
  45713. _this.roughness = 1.0;
  45714. return _this;
  45715. }
  45716. /**
  45717. * Return the currrent class name of the material.
  45718. */
  45719. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45720. return "PBRMetallicRoughnessMaterial";
  45721. };
  45722. /**
  45723. * Return the active textures of the material.
  45724. */
  45725. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45726. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45727. if (this.baseTexture) {
  45728. activeTextures.push(this.baseTexture);
  45729. }
  45730. if (this.metallicRoughnessTexture) {
  45731. activeTextures.push(this.metallicRoughnessTexture);
  45732. }
  45733. return activeTextures;
  45734. };
  45735. /**
  45736. * Checks to see if a texture is used in the material.
  45737. * @param texture - Base texture to use.
  45738. * @returns - Boolean specifying if a texture is used in the material.
  45739. */
  45740. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45741. if (_super.prototype.hasTexture.call(this, texture)) {
  45742. return true;
  45743. }
  45744. if (this.baseTexture === texture) {
  45745. return true;
  45746. }
  45747. if (this.metallicRoughnessTexture === texture) {
  45748. return true;
  45749. }
  45750. return false;
  45751. };
  45752. /**
  45753. * Makes a duplicate of the current material.
  45754. * @param name - name to use for the new material.
  45755. */
  45756. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45757. var _this = this;
  45758. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45759. clone.id = name;
  45760. clone.name = name;
  45761. return clone;
  45762. };
  45763. /**
  45764. * Serialize the material to a parsable JSON object.
  45765. */
  45766. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45767. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45768. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45769. return serializationObject;
  45770. };
  45771. /**
  45772. * Parses a JSON object correponding to the serialize function.
  45773. */
  45774. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45775. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45776. };
  45777. __decorate([
  45778. BABYLON.serializeAsColor3(),
  45779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45780. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45781. __decorate([
  45782. BABYLON.serializeAsTexture(),
  45783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45784. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45785. __decorate([
  45786. BABYLON.serialize(),
  45787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45788. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45789. __decorate([
  45790. BABYLON.serialize(),
  45791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45792. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45793. __decorate([
  45794. BABYLON.serializeAsTexture(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45796. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45797. return PBRMetallicRoughnessMaterial;
  45798. }(BABYLON.PBRBaseSimpleMaterial));
  45799. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45800. })(BABYLON || (BABYLON = {}));
  45801. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45802. var BABYLON;
  45803. (function (BABYLON) {
  45804. /**
  45805. * The PBR material of BJS following the specular glossiness convention.
  45806. *
  45807. * This fits to the PBR convention in the GLTF definition:
  45808. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45809. */
  45810. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45811. __extends(PBRSpecularGlossinessMaterial, _super);
  45812. /**
  45813. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45814. *
  45815. * @param name The material name
  45816. * @param scene The scene the material will be use in.
  45817. */
  45818. function PBRSpecularGlossinessMaterial(name, scene) {
  45819. var _this = _super.call(this, name, scene) || this;
  45820. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45821. return _this;
  45822. }
  45823. /**
  45824. * Return the currrent class name of the material.
  45825. */
  45826. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45827. return "PBRSpecularGlossinessMaterial";
  45828. };
  45829. /**
  45830. * Return the active textures of the material.
  45831. */
  45832. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45833. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45834. if (this.diffuseTexture) {
  45835. activeTextures.push(this.diffuseTexture);
  45836. }
  45837. if (this.specularGlossinessTexture) {
  45838. activeTextures.push(this.specularGlossinessTexture);
  45839. }
  45840. return activeTextures;
  45841. };
  45842. /**
  45843. * Checks to see if a texture is used in the material.
  45844. * @param texture - Base texture to use.
  45845. * @returns - Boolean specifying if a texture is used in the material.
  45846. */
  45847. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45848. if (_super.prototype.hasTexture.call(this, texture)) {
  45849. return true;
  45850. }
  45851. if (this.diffuseTexture === texture) {
  45852. return true;
  45853. }
  45854. if (this.specularGlossinessTexture === texture) {
  45855. return true;
  45856. }
  45857. return false;
  45858. };
  45859. /**
  45860. * Makes a duplicate of the current material.
  45861. * @param name - name to use for the new material.
  45862. */
  45863. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45864. var _this = this;
  45865. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45866. clone.id = name;
  45867. clone.name = name;
  45868. return clone;
  45869. };
  45870. /**
  45871. * Serialize the material to a parsable JSON object.
  45872. */
  45873. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45874. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45875. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45876. return serializationObject;
  45877. };
  45878. /**
  45879. * Parses a JSON object correponding to the serialize function.
  45880. */
  45881. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45882. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45883. };
  45884. __decorate([
  45885. BABYLON.serializeAsColor3("diffuse"),
  45886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45887. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45888. __decorate([
  45889. BABYLON.serializeAsTexture(),
  45890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45891. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45892. __decorate([
  45893. BABYLON.serializeAsColor3("specular"),
  45894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45895. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45896. __decorate([
  45897. BABYLON.serialize(),
  45898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45899. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45900. __decorate([
  45901. BABYLON.serializeAsTexture(),
  45902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45903. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45904. return PBRSpecularGlossinessMaterial;
  45905. }(BABYLON.PBRBaseSimpleMaterial));
  45906. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45907. })(BABYLON || (BABYLON = {}));
  45908. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45909. var BABYLON;
  45910. (function (BABYLON) {
  45911. BABYLON.CameraInputTypes = {};
  45912. var CameraInputsManager = /** @class */ (function () {
  45913. function CameraInputsManager(camera) {
  45914. this.attached = {};
  45915. this.camera = camera;
  45916. this.checkInputs = function () { };
  45917. }
  45918. /**
  45919. * Add an input method to a camera.
  45920. * builtin inputs example: camera.inputs.addGamepad();
  45921. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45922. * @param input camera input method
  45923. */
  45924. CameraInputsManager.prototype.add = function (input) {
  45925. var type = input.getSimpleName();
  45926. if (this.attached[type]) {
  45927. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45928. return;
  45929. }
  45930. this.attached[type] = input;
  45931. input.camera = this.camera;
  45932. //for checkInputs, we are dynamically creating a function
  45933. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45934. if (input.checkInputs) {
  45935. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45936. }
  45937. if (this.attachedElement) {
  45938. input.attachControl(this.attachedElement);
  45939. }
  45940. };
  45941. /**
  45942. * Remove a specific input method from a camera
  45943. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45944. * @param inputToRemove camera input method
  45945. */
  45946. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45947. for (var cam in this.attached) {
  45948. var input = this.attached[cam];
  45949. if (input === inputToRemove) {
  45950. input.detachControl(this.attachedElement);
  45951. input.camera = null;
  45952. delete this.attached[cam];
  45953. this.rebuildInputCheck();
  45954. }
  45955. }
  45956. };
  45957. CameraInputsManager.prototype.removeByType = function (inputType) {
  45958. for (var cam in this.attached) {
  45959. var input = this.attached[cam];
  45960. if (input.getClassName() === inputType) {
  45961. input.detachControl(this.attachedElement);
  45962. input.camera = null;
  45963. delete this.attached[cam];
  45964. this.rebuildInputCheck();
  45965. }
  45966. }
  45967. };
  45968. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45969. var current = this.checkInputs;
  45970. return function () {
  45971. current();
  45972. fn();
  45973. };
  45974. };
  45975. CameraInputsManager.prototype.attachInput = function (input) {
  45976. if (this.attachedElement) {
  45977. input.attachControl(this.attachedElement, this.noPreventDefault);
  45978. }
  45979. };
  45980. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45981. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45982. if (this.attachedElement) {
  45983. return;
  45984. }
  45985. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45986. this.attachedElement = element;
  45987. this.noPreventDefault = noPreventDefault;
  45988. for (var cam in this.attached) {
  45989. this.attached[cam].attachControl(element, noPreventDefault);
  45990. }
  45991. };
  45992. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45993. if (disconnect === void 0) { disconnect = false; }
  45994. if (this.attachedElement !== element) {
  45995. return;
  45996. }
  45997. for (var cam in this.attached) {
  45998. this.attached[cam].detachControl(element);
  45999. if (disconnect) {
  46000. this.attached[cam].camera = null;
  46001. }
  46002. }
  46003. this.attachedElement = null;
  46004. };
  46005. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46006. this.checkInputs = function () { };
  46007. for (var cam in this.attached) {
  46008. var input = this.attached[cam];
  46009. if (input.checkInputs) {
  46010. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46011. }
  46012. }
  46013. };
  46014. /**
  46015. * Remove all attached input methods from a camera
  46016. */
  46017. CameraInputsManager.prototype.clear = function () {
  46018. if (this.attachedElement) {
  46019. this.detachElement(this.attachedElement, true);
  46020. }
  46021. this.attached = {};
  46022. this.attachedElement = null;
  46023. this.checkInputs = function () { };
  46024. };
  46025. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46026. var inputs = {};
  46027. for (var cam in this.attached) {
  46028. var input = this.attached[cam];
  46029. var res = BABYLON.SerializationHelper.Serialize(input);
  46030. inputs[input.getClassName()] = res;
  46031. }
  46032. serializedCamera.inputsmgr = inputs;
  46033. };
  46034. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46035. var parsedInputs = parsedCamera.inputsmgr;
  46036. if (parsedInputs) {
  46037. this.clear();
  46038. for (var n in parsedInputs) {
  46039. var construct = BABYLON.CameraInputTypes[n];
  46040. if (construct) {
  46041. var parsedinput = parsedInputs[n];
  46042. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46043. this.add(input);
  46044. }
  46045. }
  46046. }
  46047. else {
  46048. //2016-03-08 this part is for managing backward compatibility
  46049. for (var n in this.attached) {
  46050. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46051. if (construct) {
  46052. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46053. this.remove(this.attached[n]);
  46054. this.add(input);
  46055. }
  46056. }
  46057. }
  46058. };
  46059. return CameraInputsManager;
  46060. }());
  46061. BABYLON.CameraInputsManager = CameraInputsManager;
  46062. })(BABYLON || (BABYLON = {}));
  46063. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46064. var BABYLON;
  46065. (function (BABYLON) {
  46066. var TargetCamera = /** @class */ (function (_super) {
  46067. __extends(TargetCamera, _super);
  46068. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46069. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46070. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46071. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46072. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46073. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46074. _this.speed = 2.0;
  46075. _this.noRotationConstraint = false;
  46076. _this.lockedTarget = null;
  46077. _this._currentTarget = BABYLON.Vector3.Zero();
  46078. _this._viewMatrix = BABYLON.Matrix.Zero();
  46079. _this._camMatrix = BABYLON.Matrix.Zero();
  46080. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46081. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46082. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46083. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46084. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46085. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46086. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46087. return _this;
  46088. }
  46089. TargetCamera.prototype.getFrontPosition = function (distance) {
  46090. this.getWorldMatrix();
  46091. var direction = this.getTarget().subtract(this.position);
  46092. direction.normalize();
  46093. direction.scaleInPlace(distance);
  46094. return this.globalPosition.add(direction);
  46095. };
  46096. TargetCamera.prototype._getLockedTargetPosition = function () {
  46097. if (!this.lockedTarget) {
  46098. return null;
  46099. }
  46100. if (this.lockedTarget.absolutePosition) {
  46101. this.lockedTarget.computeWorldMatrix();
  46102. }
  46103. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46104. };
  46105. TargetCamera.prototype.storeState = function () {
  46106. this._storedPosition = this.position.clone();
  46107. this._storedRotation = this.rotation.clone();
  46108. if (this.rotationQuaternion) {
  46109. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46110. }
  46111. return _super.prototype.storeState.call(this);
  46112. };
  46113. /**
  46114. * Restored camera state. You must call storeState() first
  46115. */
  46116. TargetCamera.prototype._restoreStateValues = function () {
  46117. if (!_super.prototype._restoreStateValues.call(this)) {
  46118. return false;
  46119. }
  46120. this.position = this._storedPosition.clone();
  46121. this.rotation = this._storedRotation.clone();
  46122. if (this.rotationQuaternion) {
  46123. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46124. }
  46125. this.cameraDirection.copyFromFloats(0, 0, 0);
  46126. this.cameraRotation.copyFromFloats(0, 0);
  46127. return true;
  46128. };
  46129. // Cache
  46130. TargetCamera.prototype._initCache = function () {
  46131. _super.prototype._initCache.call(this);
  46132. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46133. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46134. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46135. };
  46136. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46137. if (!ignoreParentClass) {
  46138. _super.prototype._updateCache.call(this);
  46139. }
  46140. var lockedTargetPosition = this._getLockedTargetPosition();
  46141. if (!lockedTargetPosition) {
  46142. this._cache.lockedTarget = null;
  46143. }
  46144. else {
  46145. if (!this._cache.lockedTarget) {
  46146. this._cache.lockedTarget = lockedTargetPosition.clone();
  46147. }
  46148. else {
  46149. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46150. }
  46151. }
  46152. this._cache.rotation.copyFrom(this.rotation);
  46153. if (this.rotationQuaternion)
  46154. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46155. };
  46156. // Synchronized
  46157. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46158. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46159. return false;
  46160. }
  46161. var lockedTargetPosition = this._getLockedTargetPosition();
  46162. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46163. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46164. };
  46165. // Methods
  46166. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46167. var engine = this.getEngine();
  46168. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46169. };
  46170. // Target
  46171. TargetCamera.prototype.setTarget = function (target) {
  46172. this.upVector.normalize();
  46173. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46174. this._camMatrix.invert();
  46175. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46176. var vDir = target.subtract(this.position);
  46177. if (vDir.x >= 0.0) {
  46178. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46179. }
  46180. else {
  46181. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46182. }
  46183. this.rotation.z = 0;
  46184. if (isNaN(this.rotation.x)) {
  46185. this.rotation.x = 0;
  46186. }
  46187. if (isNaN(this.rotation.y)) {
  46188. this.rotation.y = 0;
  46189. }
  46190. if (isNaN(this.rotation.z)) {
  46191. this.rotation.z = 0;
  46192. }
  46193. if (this.rotationQuaternion) {
  46194. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46195. }
  46196. };
  46197. /**
  46198. * Return the current target position of the camera. This value is expressed in local space.
  46199. */
  46200. TargetCamera.prototype.getTarget = function () {
  46201. return this._currentTarget;
  46202. };
  46203. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46204. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46205. };
  46206. TargetCamera.prototype._updatePosition = function () {
  46207. if (this.parent) {
  46208. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46209. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46210. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46211. return;
  46212. }
  46213. this.position.addInPlace(this.cameraDirection);
  46214. };
  46215. TargetCamera.prototype._checkInputs = function () {
  46216. var needToMove = this._decideIfNeedsToMove();
  46217. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46218. // Move
  46219. if (needToMove) {
  46220. this._updatePosition();
  46221. }
  46222. // Rotate
  46223. if (needToRotate) {
  46224. this.rotation.x += this.cameraRotation.x;
  46225. this.rotation.y += this.cameraRotation.y;
  46226. //rotate, if quaternion is set and rotation was used
  46227. if (this.rotationQuaternion) {
  46228. var len = this.rotation.lengthSquared();
  46229. if (len) {
  46230. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46231. }
  46232. }
  46233. if (!this.noRotationConstraint) {
  46234. var limit = (Math.PI / 2) * 0.95;
  46235. if (this.rotation.x > limit)
  46236. this.rotation.x = limit;
  46237. if (this.rotation.x < -limit)
  46238. this.rotation.x = -limit;
  46239. }
  46240. }
  46241. // Inertia
  46242. if (needToMove) {
  46243. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46244. this.cameraDirection.x = 0;
  46245. }
  46246. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46247. this.cameraDirection.y = 0;
  46248. }
  46249. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46250. this.cameraDirection.z = 0;
  46251. }
  46252. this.cameraDirection.scaleInPlace(this.inertia);
  46253. }
  46254. if (needToRotate) {
  46255. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46256. this.cameraRotation.x = 0;
  46257. }
  46258. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46259. this.cameraRotation.y = 0;
  46260. }
  46261. this.cameraRotation.scaleInPlace(this.inertia);
  46262. }
  46263. _super.prototype._checkInputs.call(this);
  46264. };
  46265. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46266. if (this.rotationQuaternion) {
  46267. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46268. }
  46269. else {
  46270. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46271. }
  46272. //update the up vector!
  46273. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46274. };
  46275. TargetCamera.prototype._getViewMatrix = function () {
  46276. if (this.lockedTarget) {
  46277. this.setTarget(this._getLockedTargetPosition());
  46278. }
  46279. // Compute
  46280. this._updateCameraRotationMatrix();
  46281. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46282. // Computing target and final matrix
  46283. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46284. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46285. return this._viewMatrix;
  46286. };
  46287. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46288. if (this.parent) {
  46289. var parentWorldMatrix = this.parent.getWorldMatrix();
  46290. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46291. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46292. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46293. this._markSyncedWithParent();
  46294. }
  46295. else {
  46296. this._globalPosition.copyFrom(this.position);
  46297. this._globalCurrentTarget.copyFrom(target);
  46298. this._globalCurrentUpVector.copyFrom(up);
  46299. }
  46300. if (this.getScene().useRightHandedSystem) {
  46301. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46302. }
  46303. else {
  46304. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46305. }
  46306. };
  46307. /**
  46308. * @override
  46309. * Override Camera.createRigCamera
  46310. */
  46311. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46312. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46313. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46314. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46315. if (!this.rotationQuaternion) {
  46316. this.rotationQuaternion = new BABYLON.Quaternion();
  46317. }
  46318. rigCamera._cameraRigParams = {};
  46319. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46320. }
  46321. return rigCamera;
  46322. }
  46323. return null;
  46324. };
  46325. /**
  46326. * @override
  46327. * Override Camera._updateRigCameras
  46328. */
  46329. TargetCamera.prototype._updateRigCameras = function () {
  46330. var camLeft = this._rigCameras[0];
  46331. var camRight = this._rigCameras[1];
  46332. switch (this.cameraRigMode) {
  46333. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46334. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46335. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46336. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46337. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46338. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46339. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46340. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46341. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46342. camLeft.setTarget(this.getTarget());
  46343. camRight.setTarget(this.getTarget());
  46344. break;
  46345. case BABYLON.Camera.RIG_MODE_VR:
  46346. if (camLeft.rotationQuaternion) {
  46347. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46348. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46349. }
  46350. else {
  46351. camLeft.rotation.copyFrom(this.rotation);
  46352. camRight.rotation.copyFrom(this.rotation);
  46353. }
  46354. camLeft.position.copyFrom(this.position);
  46355. camRight.position.copyFrom(this.position);
  46356. break;
  46357. }
  46358. _super.prototype._updateRigCameras.call(this);
  46359. };
  46360. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46361. if (!this._rigCamTransformMatrix) {
  46362. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46363. }
  46364. var target = this.getTarget();
  46365. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46366. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46367. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46368. };
  46369. TargetCamera.prototype.getClassName = function () {
  46370. return "TargetCamera";
  46371. };
  46372. __decorate([
  46373. BABYLON.serializeAsVector3()
  46374. ], TargetCamera.prototype, "rotation", void 0);
  46375. __decorate([
  46376. BABYLON.serialize()
  46377. ], TargetCamera.prototype, "speed", void 0);
  46378. __decorate([
  46379. BABYLON.serializeAsMeshReference("lockedTargetId")
  46380. ], TargetCamera.prototype, "lockedTarget", void 0);
  46381. return TargetCamera;
  46382. }(BABYLON.Camera));
  46383. BABYLON.TargetCamera = TargetCamera;
  46384. })(BABYLON || (BABYLON = {}));
  46385. //# sourceMappingURL=babylon.targetCamera.js.map
  46386. var BABYLON;
  46387. (function (BABYLON) {
  46388. var FreeCameraMouseInput = /** @class */ (function () {
  46389. function FreeCameraMouseInput(touchEnabled) {
  46390. if (touchEnabled === void 0) { touchEnabled = true; }
  46391. this.touchEnabled = touchEnabled;
  46392. this.buttons = [0, 1, 2];
  46393. this.angularSensibility = 2000.0;
  46394. this.previousPosition = null;
  46395. }
  46396. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46397. var _this = this;
  46398. var engine = this.camera.getEngine();
  46399. if (!this._pointerInput) {
  46400. this._pointerInput = function (p, s) {
  46401. var evt = p.event;
  46402. if (engine.isInVRExclusivePointerMode) {
  46403. return;
  46404. }
  46405. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46406. return;
  46407. }
  46408. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46409. return;
  46410. }
  46411. var srcElement = (evt.srcElement || evt.target);
  46412. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46413. try {
  46414. srcElement.setPointerCapture(evt.pointerId);
  46415. }
  46416. catch (e) {
  46417. //Nothing to do with the error. Execution will continue.
  46418. }
  46419. _this.previousPosition = {
  46420. x: evt.clientX,
  46421. y: evt.clientY
  46422. };
  46423. if (!noPreventDefault) {
  46424. evt.preventDefault();
  46425. element.focus();
  46426. }
  46427. }
  46428. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46429. try {
  46430. srcElement.releasePointerCapture(evt.pointerId);
  46431. }
  46432. catch (e) {
  46433. //Nothing to do with the error.
  46434. }
  46435. _this.previousPosition = null;
  46436. if (!noPreventDefault) {
  46437. evt.preventDefault();
  46438. }
  46439. }
  46440. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46441. if (!_this.previousPosition || engine.isPointerLock) {
  46442. return;
  46443. }
  46444. var offsetX = evt.clientX - _this.previousPosition.x;
  46445. if (_this.camera.getScene().useRightHandedSystem)
  46446. offsetX *= -1;
  46447. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46448. offsetX *= -1;
  46449. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46450. var offsetY = evt.clientY - _this.previousPosition.y;
  46451. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46452. _this.previousPosition = {
  46453. x: evt.clientX,
  46454. y: evt.clientY
  46455. };
  46456. if (!noPreventDefault) {
  46457. evt.preventDefault();
  46458. }
  46459. }
  46460. };
  46461. }
  46462. this._onMouseMove = function (evt) {
  46463. if (!engine.isPointerLock) {
  46464. return;
  46465. }
  46466. if (engine.isInVRExclusivePointerMode) {
  46467. return;
  46468. }
  46469. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46470. if (_this.camera.getScene().useRightHandedSystem)
  46471. offsetX *= -1;
  46472. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46473. offsetX *= -1;
  46474. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46475. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46476. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46477. _this.previousPosition = null;
  46478. if (!noPreventDefault) {
  46479. evt.preventDefault();
  46480. }
  46481. };
  46482. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46483. element.addEventListener("mousemove", this._onMouseMove, false);
  46484. };
  46485. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46486. if (this._observer && element) {
  46487. this.camera.getScene().onPointerObservable.remove(this._observer);
  46488. if (this._onMouseMove) {
  46489. element.removeEventListener("mousemove", this._onMouseMove);
  46490. }
  46491. this._observer = null;
  46492. this._onMouseMove = null;
  46493. this.previousPosition = null;
  46494. }
  46495. };
  46496. FreeCameraMouseInput.prototype.getClassName = function () {
  46497. return "FreeCameraMouseInput";
  46498. };
  46499. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46500. return "mouse";
  46501. };
  46502. __decorate([
  46503. BABYLON.serialize()
  46504. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46505. __decorate([
  46506. BABYLON.serialize()
  46507. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46508. return FreeCameraMouseInput;
  46509. }());
  46510. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46511. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46512. })(BABYLON || (BABYLON = {}));
  46513. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46514. var BABYLON;
  46515. (function (BABYLON) {
  46516. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46517. function FreeCameraKeyboardMoveInput() {
  46518. this._keys = new Array();
  46519. this.keysUp = [38];
  46520. this.keysDown = [40];
  46521. this.keysLeft = [37];
  46522. this.keysRight = [39];
  46523. }
  46524. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46525. var _this = this;
  46526. if (this._onCanvasBlurObserver) {
  46527. return;
  46528. }
  46529. this._scene = this.camera.getScene();
  46530. this._engine = this._scene.getEngine();
  46531. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46532. _this._keys = [];
  46533. });
  46534. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46535. var evt = info.event;
  46536. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46537. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46538. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46539. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46540. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46541. var index = _this._keys.indexOf(evt.keyCode);
  46542. if (index === -1) {
  46543. _this._keys.push(evt.keyCode);
  46544. }
  46545. if (!noPreventDefault) {
  46546. evt.preventDefault();
  46547. }
  46548. }
  46549. }
  46550. else {
  46551. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46552. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46553. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46554. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46555. var index = _this._keys.indexOf(evt.keyCode);
  46556. if (index >= 0) {
  46557. _this._keys.splice(index, 1);
  46558. }
  46559. if (!noPreventDefault) {
  46560. evt.preventDefault();
  46561. }
  46562. }
  46563. }
  46564. });
  46565. };
  46566. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46567. if (this._scene) {
  46568. if (this._onKeyboardObserver) {
  46569. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46570. }
  46571. if (this._onCanvasBlurObserver) {
  46572. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46573. }
  46574. this._onKeyboardObserver = null;
  46575. this._onCanvasBlurObserver = null;
  46576. }
  46577. this._keys = [];
  46578. };
  46579. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46580. if (this._onKeyboardObserver) {
  46581. var camera = this.camera;
  46582. // Keyboard
  46583. for (var index = 0; index < this._keys.length; index++) {
  46584. var keyCode = this._keys[index];
  46585. var speed = camera._computeLocalCameraSpeed();
  46586. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46587. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46588. }
  46589. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46590. camera._localDirection.copyFromFloats(0, 0, speed);
  46591. }
  46592. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46593. camera._localDirection.copyFromFloats(speed, 0, 0);
  46594. }
  46595. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46596. camera._localDirection.copyFromFloats(0, 0, -speed);
  46597. }
  46598. if (camera.getScene().useRightHandedSystem) {
  46599. camera._localDirection.z *= -1;
  46600. }
  46601. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46602. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46603. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46604. }
  46605. }
  46606. };
  46607. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46608. return "FreeCameraKeyboardMoveInput";
  46609. };
  46610. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46611. this._keys = [];
  46612. };
  46613. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46614. return "keyboard";
  46615. };
  46616. __decorate([
  46617. BABYLON.serialize()
  46618. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46619. __decorate([
  46620. BABYLON.serialize()
  46621. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46622. __decorate([
  46623. BABYLON.serialize()
  46624. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46625. __decorate([
  46626. BABYLON.serialize()
  46627. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46628. return FreeCameraKeyboardMoveInput;
  46629. }());
  46630. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46631. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46632. })(BABYLON || (BABYLON = {}));
  46633. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46634. var BABYLON;
  46635. (function (BABYLON) {
  46636. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46637. __extends(FreeCameraInputsManager, _super);
  46638. function FreeCameraInputsManager(camera) {
  46639. return _super.call(this, camera) || this;
  46640. }
  46641. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46642. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46643. return this;
  46644. };
  46645. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46646. if (touchEnabled === void 0) { touchEnabled = true; }
  46647. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46648. return this;
  46649. };
  46650. FreeCameraInputsManager.prototype.addGamepad = function () {
  46651. this.add(new BABYLON.FreeCameraGamepadInput());
  46652. return this;
  46653. };
  46654. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46655. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46656. return this;
  46657. };
  46658. FreeCameraInputsManager.prototype.addTouch = function () {
  46659. this.add(new BABYLON.FreeCameraTouchInput());
  46660. return this;
  46661. };
  46662. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46663. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46664. return this;
  46665. };
  46666. return FreeCameraInputsManager;
  46667. }(BABYLON.CameraInputsManager));
  46668. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46669. })(BABYLON || (BABYLON = {}));
  46670. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46671. var BABYLON;
  46672. (function (BABYLON) {
  46673. var FreeCamera = /** @class */ (function (_super) {
  46674. __extends(FreeCamera, _super);
  46675. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46676. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46677. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46678. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46679. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46680. _this.checkCollisions = false;
  46681. _this.applyGravity = false;
  46682. _this._needMoveForGravity = false;
  46683. _this._oldPosition = BABYLON.Vector3.Zero();
  46684. _this._diffPosition = BABYLON.Vector3.Zero();
  46685. _this._newPosition = BABYLON.Vector3.Zero();
  46686. // Collisions
  46687. _this._collisionMask = -1;
  46688. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46689. if (collidedMesh === void 0) { collidedMesh = null; }
  46690. //TODO move this to the collision coordinator!
  46691. if (_this.getScene().workerCollisions)
  46692. newPosition.multiplyInPlace(_this._collider._radius);
  46693. var updatePosition = function (newPos) {
  46694. _this._newPosition.copyFrom(newPos);
  46695. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46696. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46697. _this.position.addInPlace(_this._diffPosition);
  46698. if (_this.onCollide && collidedMesh) {
  46699. _this.onCollide(collidedMesh);
  46700. }
  46701. }
  46702. };
  46703. updatePosition(newPosition);
  46704. };
  46705. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46706. _this.inputs.addKeyboard().addMouse();
  46707. return _this;
  46708. }
  46709. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46710. //-- begin properties for backward compatibility for inputs
  46711. /**
  46712. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46713. * Higher values reduce sensitivity.
  46714. */
  46715. get: function () {
  46716. var mouse = this.inputs.attached["mouse"];
  46717. if (mouse)
  46718. return mouse.angularSensibility;
  46719. return 0;
  46720. },
  46721. /**
  46722. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46723. * Higher values reduce sensitivity.
  46724. */
  46725. set: function (value) {
  46726. var mouse = this.inputs.attached["mouse"];
  46727. if (mouse)
  46728. mouse.angularSensibility = value;
  46729. },
  46730. enumerable: true,
  46731. configurable: true
  46732. });
  46733. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46734. get: function () {
  46735. var keyboard = this.inputs.attached["keyboard"];
  46736. if (keyboard)
  46737. return keyboard.keysUp;
  46738. return [];
  46739. },
  46740. set: function (value) {
  46741. var keyboard = this.inputs.attached["keyboard"];
  46742. if (keyboard)
  46743. keyboard.keysUp = value;
  46744. },
  46745. enumerable: true,
  46746. configurable: true
  46747. });
  46748. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46749. get: function () {
  46750. var keyboard = this.inputs.attached["keyboard"];
  46751. if (keyboard)
  46752. return keyboard.keysDown;
  46753. return [];
  46754. },
  46755. set: function (value) {
  46756. var keyboard = this.inputs.attached["keyboard"];
  46757. if (keyboard)
  46758. keyboard.keysDown = value;
  46759. },
  46760. enumerable: true,
  46761. configurable: true
  46762. });
  46763. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46764. get: function () {
  46765. var keyboard = this.inputs.attached["keyboard"];
  46766. if (keyboard)
  46767. return keyboard.keysLeft;
  46768. return [];
  46769. },
  46770. set: function (value) {
  46771. var keyboard = this.inputs.attached["keyboard"];
  46772. if (keyboard)
  46773. keyboard.keysLeft = value;
  46774. },
  46775. enumerable: true,
  46776. configurable: true
  46777. });
  46778. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46779. get: function () {
  46780. var keyboard = this.inputs.attached["keyboard"];
  46781. if (keyboard)
  46782. return keyboard.keysRight;
  46783. return [];
  46784. },
  46785. set: function (value) {
  46786. var keyboard = this.inputs.attached["keyboard"];
  46787. if (keyboard)
  46788. keyboard.keysRight = value;
  46789. },
  46790. enumerable: true,
  46791. configurable: true
  46792. });
  46793. // Controls
  46794. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46795. this.inputs.attachElement(element, noPreventDefault);
  46796. };
  46797. FreeCamera.prototype.detachControl = function (element) {
  46798. this.inputs.detachElement(element);
  46799. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46800. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46801. };
  46802. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46803. get: function () {
  46804. return this._collisionMask;
  46805. },
  46806. set: function (mask) {
  46807. this._collisionMask = !isNaN(mask) ? mask : -1;
  46808. },
  46809. enumerable: true,
  46810. configurable: true
  46811. });
  46812. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46813. var globalPosition;
  46814. if (this.parent) {
  46815. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46816. }
  46817. else {
  46818. globalPosition = this.position;
  46819. }
  46820. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46821. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46822. if (!this._collider) {
  46823. this._collider = new BABYLON.Collider();
  46824. }
  46825. this._collider._radius = this.ellipsoid;
  46826. this._collider.collisionMask = this._collisionMask;
  46827. //no need for clone, as long as gravity is not on.
  46828. var actualDisplacement = displacement;
  46829. //add gravity to the direction to prevent the dual-collision checking
  46830. if (this.applyGravity) {
  46831. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46832. actualDisplacement = displacement.add(this.getScene().gravity);
  46833. }
  46834. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46835. };
  46836. FreeCamera.prototype._checkInputs = function () {
  46837. if (!this._localDirection) {
  46838. this._localDirection = BABYLON.Vector3.Zero();
  46839. this._transformedDirection = BABYLON.Vector3.Zero();
  46840. }
  46841. this.inputs.checkInputs();
  46842. _super.prototype._checkInputs.call(this);
  46843. };
  46844. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46845. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46846. };
  46847. FreeCamera.prototype._updatePosition = function () {
  46848. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46849. this._collideWithWorld(this.cameraDirection);
  46850. }
  46851. else {
  46852. _super.prototype._updatePosition.call(this);
  46853. }
  46854. };
  46855. FreeCamera.prototype.dispose = function () {
  46856. this.inputs.clear();
  46857. _super.prototype.dispose.call(this);
  46858. };
  46859. FreeCamera.prototype.getClassName = function () {
  46860. return "FreeCamera";
  46861. };
  46862. __decorate([
  46863. BABYLON.serializeAsVector3()
  46864. ], FreeCamera.prototype, "ellipsoid", void 0);
  46865. __decorate([
  46866. BABYLON.serializeAsVector3()
  46867. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46868. __decorate([
  46869. BABYLON.serialize()
  46870. ], FreeCamera.prototype, "checkCollisions", void 0);
  46871. __decorate([
  46872. BABYLON.serialize()
  46873. ], FreeCamera.prototype, "applyGravity", void 0);
  46874. return FreeCamera;
  46875. }(BABYLON.TargetCamera));
  46876. BABYLON.FreeCamera = FreeCamera;
  46877. })(BABYLON || (BABYLON = {}));
  46878. //# sourceMappingURL=babylon.freeCamera.js.map
  46879. var BABYLON;
  46880. (function (BABYLON) {
  46881. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46882. function ArcRotateCameraKeyboardMoveInput() {
  46883. this._keys = new Array();
  46884. this.keysUp = [38];
  46885. this.keysDown = [40];
  46886. this.keysLeft = [37];
  46887. this.keysRight = [39];
  46888. this.keysReset = [220];
  46889. this.panningSensibility = 50.0;
  46890. this.zoomingSensibility = 25.0;
  46891. this.useAltToZoom = true;
  46892. }
  46893. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46894. var _this = this;
  46895. if (this._onCanvasBlurObserver) {
  46896. return;
  46897. }
  46898. this._scene = this.camera.getScene();
  46899. this._engine = this._scene.getEngine();
  46900. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46901. _this._keys = [];
  46902. });
  46903. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46904. var evt = info.event;
  46905. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46906. _this._ctrlPressed = evt.ctrlKey;
  46907. _this._altPressed = evt.altKey;
  46908. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46909. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46910. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46911. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46912. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46913. var index = _this._keys.indexOf(evt.keyCode);
  46914. if (index === -1) {
  46915. _this._keys.push(evt.keyCode);
  46916. }
  46917. if (evt.preventDefault) {
  46918. if (!noPreventDefault) {
  46919. evt.preventDefault();
  46920. }
  46921. }
  46922. }
  46923. }
  46924. else {
  46925. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46926. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46927. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46928. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46929. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46930. var index = _this._keys.indexOf(evt.keyCode);
  46931. if (index >= 0) {
  46932. _this._keys.splice(index, 1);
  46933. }
  46934. if (evt.preventDefault) {
  46935. if (!noPreventDefault) {
  46936. evt.preventDefault();
  46937. }
  46938. }
  46939. }
  46940. }
  46941. });
  46942. };
  46943. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46944. if (this._scene) {
  46945. if (this._onKeyboardObserver) {
  46946. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46947. }
  46948. if (this._onCanvasBlurObserver) {
  46949. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46950. }
  46951. this._onKeyboardObserver = null;
  46952. this._onCanvasBlurObserver = null;
  46953. }
  46954. this._keys = [];
  46955. };
  46956. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46957. if (this._onKeyboardObserver) {
  46958. var camera = this.camera;
  46959. for (var index = 0; index < this._keys.length; index++) {
  46960. var keyCode = this._keys[index];
  46961. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46962. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46963. camera.inertialPanningX -= 1 / this.panningSensibility;
  46964. }
  46965. else {
  46966. camera.inertialAlphaOffset -= 0.01;
  46967. }
  46968. }
  46969. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46970. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46971. camera.inertialPanningY += 1 / this.panningSensibility;
  46972. }
  46973. else if (this._altPressed && this.useAltToZoom) {
  46974. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46975. }
  46976. else {
  46977. camera.inertialBetaOffset -= 0.01;
  46978. }
  46979. }
  46980. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46981. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46982. camera.inertialPanningX += 1 / this.panningSensibility;
  46983. }
  46984. else {
  46985. camera.inertialAlphaOffset += 0.01;
  46986. }
  46987. }
  46988. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46989. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46990. camera.inertialPanningY -= 1 / this.panningSensibility;
  46991. }
  46992. else if (this._altPressed && this.useAltToZoom) {
  46993. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46994. }
  46995. else {
  46996. camera.inertialBetaOffset += 0.01;
  46997. }
  46998. }
  46999. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47000. camera.restoreState();
  47001. }
  47002. }
  47003. }
  47004. };
  47005. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47006. return "ArcRotateCameraKeyboardMoveInput";
  47007. };
  47008. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47009. return "keyboard";
  47010. };
  47011. __decorate([
  47012. BABYLON.serialize()
  47013. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47014. __decorate([
  47015. BABYLON.serialize()
  47016. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47017. __decorate([
  47018. BABYLON.serialize()
  47019. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47020. __decorate([
  47021. BABYLON.serialize()
  47022. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47023. __decorate([
  47024. BABYLON.serialize()
  47025. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47026. __decorate([
  47027. BABYLON.serialize()
  47028. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47029. __decorate([
  47030. BABYLON.serialize()
  47031. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47032. __decorate([
  47033. BABYLON.serialize()
  47034. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47035. return ArcRotateCameraKeyboardMoveInput;
  47036. }());
  47037. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47038. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47039. })(BABYLON || (BABYLON = {}));
  47040. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47041. var BABYLON;
  47042. (function (BABYLON) {
  47043. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47044. function ArcRotateCameraMouseWheelInput() {
  47045. this.wheelPrecision = 3.0;
  47046. /**
  47047. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47048. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47049. */
  47050. this.wheelDeltaPercentage = 0;
  47051. }
  47052. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47053. var _this = this;
  47054. this._wheel = function (p, s) {
  47055. //sanity check - this should be a PointerWheel event.
  47056. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47057. return;
  47058. var event = p.event;
  47059. var delta = 0;
  47060. if (event.wheelDelta) {
  47061. if (_this.wheelDeltaPercentage) {
  47062. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47063. if (event.wheelDelta > 0) {
  47064. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47065. }
  47066. else {
  47067. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47068. }
  47069. }
  47070. else {
  47071. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47072. }
  47073. }
  47074. else if (event.detail) {
  47075. delta = -event.detail / _this.wheelPrecision;
  47076. }
  47077. if (delta)
  47078. _this.camera.inertialRadiusOffset += delta;
  47079. if (event.preventDefault) {
  47080. if (!noPreventDefault) {
  47081. event.preventDefault();
  47082. }
  47083. }
  47084. };
  47085. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47086. };
  47087. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47088. if (this._observer && element) {
  47089. this.camera.getScene().onPointerObservable.remove(this._observer);
  47090. this._observer = null;
  47091. this._wheel = null;
  47092. }
  47093. };
  47094. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47095. return "ArcRotateCameraMouseWheelInput";
  47096. };
  47097. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47098. return "mousewheel";
  47099. };
  47100. __decorate([
  47101. BABYLON.serialize()
  47102. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47103. __decorate([
  47104. BABYLON.serialize()
  47105. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47106. return ArcRotateCameraMouseWheelInput;
  47107. }());
  47108. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47109. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47110. })(BABYLON || (BABYLON = {}));
  47111. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47112. var BABYLON;
  47113. (function (BABYLON) {
  47114. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47115. function ArcRotateCameraPointersInput() {
  47116. this.buttons = [0, 1, 2];
  47117. this.angularSensibilityX = 1000.0;
  47118. this.angularSensibilityY = 1000.0;
  47119. this.pinchPrecision = 12.0;
  47120. /**
  47121. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47122. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47123. */
  47124. this.pinchDeltaPercentage = 0;
  47125. this.panningSensibility = 1000.0;
  47126. this.multiTouchPanning = true;
  47127. this.multiTouchPanAndZoom = true;
  47128. this._isPanClick = false;
  47129. this.pinchInwards = true;
  47130. }
  47131. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47132. var _this = this;
  47133. var engine = this.camera.getEngine();
  47134. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47135. var pointA = null;
  47136. var pointB = null;
  47137. var previousPinchSquaredDistance = 0;
  47138. var initialDistance = 0;
  47139. var twoFingerActivityCount = 0;
  47140. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47141. this._pointerInput = function (p, s) {
  47142. var evt = p.event;
  47143. var isTouch = p.event.pointerType === "touch";
  47144. if (engine.isInVRExclusivePointerMode) {
  47145. return;
  47146. }
  47147. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47148. return;
  47149. }
  47150. var srcElement = (evt.srcElement || evt.target);
  47151. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47152. try {
  47153. srcElement.setPointerCapture(evt.pointerId);
  47154. }
  47155. catch (e) {
  47156. //Nothing to do with the error. Execution will continue.
  47157. }
  47158. // Manage panning with pan button click
  47159. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47160. // manage pointers
  47161. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47162. if (pointA === null) {
  47163. pointA = cacheSoloPointer;
  47164. }
  47165. else if (pointB === null) {
  47166. pointB = cacheSoloPointer;
  47167. }
  47168. if (!noPreventDefault) {
  47169. evt.preventDefault();
  47170. element.focus();
  47171. }
  47172. }
  47173. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47174. _this.camera.restoreState();
  47175. }
  47176. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47177. try {
  47178. srcElement.releasePointerCapture(evt.pointerId);
  47179. }
  47180. catch (e) {
  47181. //Nothing to do with the error.
  47182. }
  47183. cacheSoloPointer = null;
  47184. previousPinchSquaredDistance = 0;
  47185. previousMultiTouchPanPosition.isPaning = false;
  47186. previousMultiTouchPanPosition.isPinching = false;
  47187. twoFingerActivityCount = 0;
  47188. initialDistance = 0;
  47189. if (!isTouch) {
  47190. pointB = null; // Mouse and pen are mono pointer
  47191. }
  47192. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47193. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47194. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47195. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47196. if (engine._badOS) {
  47197. pointA = pointB = null;
  47198. }
  47199. else {
  47200. //only remove the impacted pointer in case of multitouch allowing on most
  47201. //platforms switching from rotate to zoom and pan seamlessly.
  47202. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47203. pointA = pointB;
  47204. pointB = null;
  47205. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47206. }
  47207. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47208. pointB = null;
  47209. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47210. }
  47211. else {
  47212. pointA = pointB = null;
  47213. }
  47214. }
  47215. if (!noPreventDefault) {
  47216. evt.preventDefault();
  47217. }
  47218. }
  47219. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47220. if (!noPreventDefault) {
  47221. evt.preventDefault();
  47222. }
  47223. // One button down
  47224. if (pointA && pointB === null && cacheSoloPointer) {
  47225. if (_this.panningSensibility !== 0 &&
  47226. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47227. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47228. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47229. }
  47230. else {
  47231. var offsetX = evt.clientX - cacheSoloPointer.x;
  47232. var offsetY = evt.clientY - cacheSoloPointer.y;
  47233. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47234. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47235. }
  47236. cacheSoloPointer.x = evt.clientX;
  47237. cacheSoloPointer.y = evt.clientY;
  47238. }
  47239. // Two buttons down: pinch/pan
  47240. else if (pointA && pointB) {
  47241. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47242. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47243. ed.x = evt.clientX;
  47244. ed.y = evt.clientY;
  47245. var direction = _this.pinchInwards ? 1 : -1;
  47246. var distX = pointA.x - pointB.x;
  47247. var distY = pointA.y - pointB.y;
  47248. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47249. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47250. if (previousPinchSquaredDistance === 0) {
  47251. initialDistance = pinchDistance;
  47252. previousPinchSquaredDistance = pinchSquaredDistance;
  47253. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47254. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47255. return;
  47256. }
  47257. if (_this.multiTouchPanAndZoom) {
  47258. if (_this.pinchDeltaPercentage) {
  47259. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47260. }
  47261. else {
  47262. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47263. (_this.pinchPrecision *
  47264. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47265. direction);
  47266. }
  47267. if (_this.panningSensibility !== 0) {
  47268. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47269. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47270. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47271. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47272. previousMultiTouchPanPosition.x = pointersCenterX;
  47273. previousMultiTouchPanPosition.y = pointersCenterY;
  47274. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47275. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47276. }
  47277. }
  47278. else {
  47279. twoFingerActivityCount++;
  47280. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47281. if (_this.pinchDeltaPercentage) {
  47282. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47283. }
  47284. else {
  47285. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47286. (_this.pinchPrecision *
  47287. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47288. direction);
  47289. }
  47290. previousMultiTouchPanPosition.isPaning = false;
  47291. previousMultiTouchPanPosition.isPinching = true;
  47292. }
  47293. else {
  47294. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47295. if (!previousMultiTouchPanPosition.isPaning) {
  47296. previousMultiTouchPanPosition.isPaning = true;
  47297. previousMultiTouchPanPosition.isPinching = false;
  47298. previousMultiTouchPanPosition.x = ed.x;
  47299. previousMultiTouchPanPosition.y = ed.y;
  47300. return;
  47301. }
  47302. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47303. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47304. }
  47305. }
  47306. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47307. previousMultiTouchPanPosition.x = ed.x;
  47308. previousMultiTouchPanPosition.y = ed.y;
  47309. }
  47310. }
  47311. previousPinchSquaredDistance = pinchSquaredDistance;
  47312. }
  47313. }
  47314. };
  47315. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47316. this._onContextMenu = function (evt) {
  47317. evt.preventDefault();
  47318. };
  47319. if (!this.camera._useCtrlForPanning) {
  47320. element.addEventListener("contextmenu", this._onContextMenu, false);
  47321. }
  47322. this._onLostFocus = function () {
  47323. //this._keys = [];
  47324. pointA = pointB = null;
  47325. previousPinchSquaredDistance = 0;
  47326. previousMultiTouchPanPosition.isPaning = false;
  47327. previousMultiTouchPanPosition.isPinching = false;
  47328. twoFingerActivityCount = 0;
  47329. cacheSoloPointer = null;
  47330. initialDistance = 0;
  47331. };
  47332. this._onMouseMove = function (evt) {
  47333. if (!engine.isPointerLock) {
  47334. return;
  47335. }
  47336. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47337. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47338. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47339. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47340. if (!noPreventDefault) {
  47341. evt.preventDefault();
  47342. }
  47343. };
  47344. this._onGestureStart = function (e) {
  47345. if (window.MSGesture === undefined) {
  47346. return;
  47347. }
  47348. if (!_this._MSGestureHandler) {
  47349. _this._MSGestureHandler = new MSGesture();
  47350. _this._MSGestureHandler.target = element;
  47351. }
  47352. _this._MSGestureHandler.addPointer(e.pointerId);
  47353. };
  47354. this._onGesture = function (e) {
  47355. _this.camera.radius *= e.scale;
  47356. if (e.preventDefault) {
  47357. if (!noPreventDefault) {
  47358. e.stopPropagation();
  47359. e.preventDefault();
  47360. }
  47361. }
  47362. };
  47363. element.addEventListener("mousemove", this._onMouseMove, false);
  47364. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47365. element.addEventListener("MSGestureChange", this._onGesture, false);
  47366. BABYLON.Tools.RegisterTopRootEvents([
  47367. { name: "blur", handler: this._onLostFocus }
  47368. ]);
  47369. };
  47370. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47371. if (this._onLostFocus) {
  47372. BABYLON.Tools.UnregisterTopRootEvents([
  47373. { name: "blur", handler: this._onLostFocus }
  47374. ]);
  47375. }
  47376. if (element && this._observer) {
  47377. this.camera.getScene().onPointerObservable.remove(this._observer);
  47378. this._observer = null;
  47379. if (this._onContextMenu) {
  47380. element.removeEventListener("contextmenu", this._onContextMenu);
  47381. }
  47382. if (this._onMouseMove) {
  47383. element.removeEventListener("mousemove", this._onMouseMove);
  47384. }
  47385. if (this._onGestureStart) {
  47386. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47387. }
  47388. if (this._onGesture) {
  47389. element.removeEventListener("MSGestureChange", this._onGesture);
  47390. }
  47391. this._isPanClick = false;
  47392. this.pinchInwards = true;
  47393. this._onMouseMove = null;
  47394. this._onGestureStart = null;
  47395. this._onGesture = null;
  47396. this._MSGestureHandler = null;
  47397. this._onLostFocus = null;
  47398. this._onContextMenu = null;
  47399. }
  47400. };
  47401. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47402. return "ArcRotateCameraPointersInput";
  47403. };
  47404. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47405. return "pointers";
  47406. };
  47407. __decorate([
  47408. BABYLON.serialize()
  47409. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47410. __decorate([
  47411. BABYLON.serialize()
  47412. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47413. __decorate([
  47414. BABYLON.serialize()
  47415. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47416. __decorate([
  47417. BABYLON.serialize()
  47418. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47419. __decorate([
  47420. BABYLON.serialize()
  47421. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47422. __decorate([
  47423. BABYLON.serialize()
  47424. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47425. __decorate([
  47426. BABYLON.serialize()
  47427. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47428. __decorate([
  47429. BABYLON.serialize()
  47430. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47431. return ArcRotateCameraPointersInput;
  47432. }());
  47433. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47434. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47435. })(BABYLON || (BABYLON = {}));
  47436. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47437. var BABYLON;
  47438. (function (BABYLON) {
  47439. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47440. __extends(ArcRotateCameraInputsManager, _super);
  47441. function ArcRotateCameraInputsManager(camera) {
  47442. return _super.call(this, camera) || this;
  47443. }
  47444. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47445. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47446. return this;
  47447. };
  47448. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47449. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47450. return this;
  47451. };
  47452. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47453. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47454. return this;
  47455. };
  47456. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47457. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47458. return this;
  47459. };
  47460. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47461. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47462. return this;
  47463. };
  47464. return ArcRotateCameraInputsManager;
  47465. }(BABYLON.CameraInputsManager));
  47466. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47467. })(BABYLON || (BABYLON = {}));
  47468. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47469. var BABYLON;
  47470. (function (BABYLON) {
  47471. var ArcRotateCamera = /** @class */ (function (_super) {
  47472. __extends(ArcRotateCamera, _super);
  47473. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47474. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47475. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47476. _this.inertialAlphaOffset = 0;
  47477. _this.inertialBetaOffset = 0;
  47478. _this.inertialRadiusOffset = 0;
  47479. _this.lowerAlphaLimit = null;
  47480. _this.upperAlphaLimit = null;
  47481. _this.lowerBetaLimit = 0.01;
  47482. _this.upperBetaLimit = Math.PI;
  47483. _this.lowerRadiusLimit = null;
  47484. _this.upperRadiusLimit = null;
  47485. _this.inertialPanningX = 0;
  47486. _this.inertialPanningY = 0;
  47487. _this.pinchToPanMaxDistance = 20;
  47488. _this.panningDistanceLimit = null;
  47489. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47490. _this.panningInertia = 0.9;
  47491. //-- end properties for backward compatibility for inputs
  47492. _this.zoomOnFactor = 1;
  47493. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47494. _this.allowUpsideDown = true;
  47495. _this._viewMatrix = new BABYLON.Matrix();
  47496. // Panning
  47497. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47498. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47499. _this.checkCollisions = false;
  47500. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47501. _this._previousPosition = BABYLON.Vector3.Zero();
  47502. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47503. _this._newPosition = BABYLON.Vector3.Zero();
  47504. _this._computationVector = BABYLON.Vector3.Zero();
  47505. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47506. if (collidedMesh === void 0) { collidedMesh = null; }
  47507. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47508. newPosition.multiplyInPlace(_this._collider._radius);
  47509. }
  47510. if (!collidedMesh) {
  47511. _this._previousPosition.copyFrom(_this.position);
  47512. }
  47513. else {
  47514. _this.setPosition(newPosition);
  47515. if (_this.onCollide) {
  47516. _this.onCollide(collidedMesh);
  47517. }
  47518. }
  47519. // Recompute because of constraints
  47520. var cosa = Math.cos(_this.alpha);
  47521. var sina = Math.sin(_this.alpha);
  47522. var cosb = Math.cos(_this.beta);
  47523. var sinb = Math.sin(_this.beta);
  47524. if (sinb === 0) {
  47525. sinb = 0.0001;
  47526. }
  47527. var target = _this._getTargetPosition();
  47528. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47529. target.addToRef(_this._computationVector, _this._newPosition);
  47530. _this.position.copyFrom(_this._newPosition);
  47531. var up = _this.upVector;
  47532. if (_this.allowUpsideDown && _this.beta < 0) {
  47533. up = up.clone();
  47534. up = up.negate();
  47535. }
  47536. _this._computeViewMatrix(_this.position, target, up);
  47537. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47538. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47539. _this._collisionTriggered = false;
  47540. };
  47541. _this._target = BABYLON.Vector3.Zero();
  47542. if (target) {
  47543. _this.setTarget(target);
  47544. }
  47545. _this.alpha = alpha;
  47546. _this.beta = beta;
  47547. _this.radius = radius;
  47548. _this.getViewMatrix();
  47549. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47550. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47551. return _this;
  47552. }
  47553. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47554. get: function () {
  47555. return this._target;
  47556. },
  47557. set: function (value) {
  47558. this.setTarget(value);
  47559. },
  47560. enumerable: true,
  47561. configurable: true
  47562. });
  47563. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47564. //-- begin properties for backward compatibility for inputs
  47565. get: function () {
  47566. var pointers = this.inputs.attached["pointers"];
  47567. if (pointers)
  47568. return pointers.angularSensibilityX;
  47569. return 0;
  47570. },
  47571. set: function (value) {
  47572. var pointers = this.inputs.attached["pointers"];
  47573. if (pointers) {
  47574. pointers.angularSensibilityX = value;
  47575. }
  47576. },
  47577. enumerable: true,
  47578. configurable: true
  47579. });
  47580. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47581. get: function () {
  47582. var pointers = this.inputs.attached["pointers"];
  47583. if (pointers)
  47584. return pointers.angularSensibilityY;
  47585. return 0;
  47586. },
  47587. set: function (value) {
  47588. var pointers = this.inputs.attached["pointers"];
  47589. if (pointers) {
  47590. pointers.angularSensibilityY = value;
  47591. }
  47592. },
  47593. enumerable: true,
  47594. configurable: true
  47595. });
  47596. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47597. get: function () {
  47598. var pointers = this.inputs.attached["pointers"];
  47599. if (pointers)
  47600. return pointers.pinchPrecision;
  47601. return 0;
  47602. },
  47603. set: function (value) {
  47604. var pointers = this.inputs.attached["pointers"];
  47605. if (pointers) {
  47606. pointers.pinchPrecision = value;
  47607. }
  47608. },
  47609. enumerable: true,
  47610. configurable: true
  47611. });
  47612. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47613. get: function () {
  47614. var pointers = this.inputs.attached["pointers"];
  47615. if (pointers)
  47616. return pointers.pinchDeltaPercentage;
  47617. return 0;
  47618. },
  47619. set: function (value) {
  47620. var pointers = this.inputs.attached["pointers"];
  47621. if (pointers) {
  47622. pointers.pinchDeltaPercentage = value;
  47623. }
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47629. get: function () {
  47630. var pointers = this.inputs.attached["pointers"];
  47631. if (pointers)
  47632. return pointers.panningSensibility;
  47633. return 0;
  47634. },
  47635. set: function (value) {
  47636. var pointers = this.inputs.attached["pointers"];
  47637. if (pointers) {
  47638. pointers.panningSensibility = value;
  47639. }
  47640. },
  47641. enumerable: true,
  47642. configurable: true
  47643. });
  47644. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47645. get: function () {
  47646. var keyboard = this.inputs.attached["keyboard"];
  47647. if (keyboard)
  47648. return keyboard.keysUp;
  47649. return [];
  47650. },
  47651. set: function (value) {
  47652. var keyboard = this.inputs.attached["keyboard"];
  47653. if (keyboard)
  47654. keyboard.keysUp = value;
  47655. },
  47656. enumerable: true,
  47657. configurable: true
  47658. });
  47659. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47660. get: function () {
  47661. var keyboard = this.inputs.attached["keyboard"];
  47662. if (keyboard)
  47663. return keyboard.keysDown;
  47664. return [];
  47665. },
  47666. set: function (value) {
  47667. var keyboard = this.inputs.attached["keyboard"];
  47668. if (keyboard)
  47669. keyboard.keysDown = value;
  47670. },
  47671. enumerable: true,
  47672. configurable: true
  47673. });
  47674. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47675. get: function () {
  47676. var keyboard = this.inputs.attached["keyboard"];
  47677. if (keyboard)
  47678. return keyboard.keysLeft;
  47679. return [];
  47680. },
  47681. set: function (value) {
  47682. var keyboard = this.inputs.attached["keyboard"];
  47683. if (keyboard)
  47684. keyboard.keysLeft = value;
  47685. },
  47686. enumerable: true,
  47687. configurable: true
  47688. });
  47689. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47690. get: function () {
  47691. var keyboard = this.inputs.attached["keyboard"];
  47692. if (keyboard)
  47693. return keyboard.keysRight;
  47694. return [];
  47695. },
  47696. set: function (value) {
  47697. var keyboard = this.inputs.attached["keyboard"];
  47698. if (keyboard)
  47699. keyboard.keysRight = value;
  47700. },
  47701. enumerable: true,
  47702. configurable: true
  47703. });
  47704. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47705. get: function () {
  47706. var mousewheel = this.inputs.attached["mousewheel"];
  47707. if (mousewheel)
  47708. return mousewheel.wheelPrecision;
  47709. return 0;
  47710. },
  47711. set: function (value) {
  47712. var mousewheel = this.inputs.attached["mousewheel"];
  47713. if (mousewheel)
  47714. mousewheel.wheelPrecision = value;
  47715. },
  47716. enumerable: true,
  47717. configurable: true
  47718. });
  47719. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47720. get: function () {
  47721. var mousewheel = this.inputs.attached["mousewheel"];
  47722. if (mousewheel)
  47723. return mousewheel.wheelDeltaPercentage;
  47724. return 0;
  47725. },
  47726. set: function (value) {
  47727. var mousewheel = this.inputs.attached["mousewheel"];
  47728. if (mousewheel)
  47729. mousewheel.wheelDeltaPercentage = value;
  47730. },
  47731. enumerable: true,
  47732. configurable: true
  47733. });
  47734. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47735. get: function () {
  47736. return this._bouncingBehavior;
  47737. },
  47738. enumerable: true,
  47739. configurable: true
  47740. });
  47741. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47742. get: function () {
  47743. return this._bouncingBehavior != null;
  47744. },
  47745. set: function (value) {
  47746. if (value === this.useBouncingBehavior) {
  47747. return;
  47748. }
  47749. if (value) {
  47750. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47751. this.addBehavior(this._bouncingBehavior);
  47752. }
  47753. else if (this._bouncingBehavior) {
  47754. this.removeBehavior(this._bouncingBehavior);
  47755. this._bouncingBehavior = null;
  47756. }
  47757. },
  47758. enumerable: true,
  47759. configurable: true
  47760. });
  47761. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47762. get: function () {
  47763. return this._framingBehavior;
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47769. get: function () {
  47770. return this._framingBehavior != null;
  47771. },
  47772. set: function (value) {
  47773. if (value === this.useFramingBehavior) {
  47774. return;
  47775. }
  47776. if (value) {
  47777. this._framingBehavior = new BABYLON.FramingBehavior();
  47778. this.addBehavior(this._framingBehavior);
  47779. }
  47780. else if (this._framingBehavior) {
  47781. this.removeBehavior(this._framingBehavior);
  47782. this._framingBehavior = null;
  47783. }
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47789. get: function () {
  47790. return this._autoRotationBehavior;
  47791. },
  47792. enumerable: true,
  47793. configurable: true
  47794. });
  47795. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47796. get: function () {
  47797. return this._autoRotationBehavior != null;
  47798. },
  47799. set: function (value) {
  47800. if (value === this.useAutoRotationBehavior) {
  47801. return;
  47802. }
  47803. if (value) {
  47804. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47805. this.addBehavior(this._autoRotationBehavior);
  47806. }
  47807. else if (this._autoRotationBehavior) {
  47808. this.removeBehavior(this._autoRotationBehavior);
  47809. this._autoRotationBehavior = null;
  47810. }
  47811. },
  47812. enumerable: true,
  47813. configurable: true
  47814. });
  47815. // Cache
  47816. ArcRotateCamera.prototype._initCache = function () {
  47817. _super.prototype._initCache.call(this);
  47818. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47819. this._cache.alpha = undefined;
  47820. this._cache.beta = undefined;
  47821. this._cache.radius = undefined;
  47822. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47823. };
  47824. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47825. if (!ignoreParentClass) {
  47826. _super.prototype._updateCache.call(this);
  47827. }
  47828. this._cache._target.copyFrom(this._getTargetPosition());
  47829. this._cache.alpha = this.alpha;
  47830. this._cache.beta = this.beta;
  47831. this._cache.radius = this.radius;
  47832. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47833. };
  47834. ArcRotateCamera.prototype._getTargetPosition = function () {
  47835. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47836. var pos = this._targetHost.getAbsolutePosition();
  47837. if (this._targetBoundingCenter) {
  47838. pos.addToRef(this._targetBoundingCenter, this._target);
  47839. }
  47840. else {
  47841. this._target.copyFrom(pos);
  47842. }
  47843. }
  47844. var lockedTargetPosition = this._getLockedTargetPosition();
  47845. if (lockedTargetPosition) {
  47846. return lockedTargetPosition;
  47847. }
  47848. return this._target;
  47849. };
  47850. ArcRotateCamera.prototype.storeState = function () {
  47851. this._storedAlpha = this.alpha;
  47852. this._storedBeta = this.beta;
  47853. this._storedRadius = this.radius;
  47854. this._storedTarget = this._getTargetPosition().clone();
  47855. return _super.prototype.storeState.call(this);
  47856. };
  47857. /**
  47858. * Restored camera state. You must call storeState() first
  47859. */
  47860. ArcRotateCamera.prototype._restoreStateValues = function () {
  47861. if (!_super.prototype._restoreStateValues.call(this)) {
  47862. return false;
  47863. }
  47864. this.alpha = this._storedAlpha;
  47865. this.beta = this._storedBeta;
  47866. this.radius = this._storedRadius;
  47867. this.setTarget(this._storedTarget.clone());
  47868. this.inertialAlphaOffset = 0;
  47869. this.inertialBetaOffset = 0;
  47870. this.inertialRadiusOffset = 0;
  47871. this.inertialPanningX = 0;
  47872. this.inertialPanningY = 0;
  47873. return true;
  47874. };
  47875. // Synchronized
  47876. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47877. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47878. return false;
  47879. return this._cache._target.equals(this._getTargetPosition())
  47880. && this._cache.alpha === this.alpha
  47881. && this._cache.beta === this.beta
  47882. && this._cache.radius === this.radius
  47883. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47884. };
  47885. // Methods
  47886. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47887. var _this = this;
  47888. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47889. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47890. this._useCtrlForPanning = useCtrlForPanning;
  47891. this._panningMouseButton = panningMouseButton;
  47892. this.inputs.attachElement(element, noPreventDefault);
  47893. this._reset = function () {
  47894. _this.inertialAlphaOffset = 0;
  47895. _this.inertialBetaOffset = 0;
  47896. _this.inertialRadiusOffset = 0;
  47897. _this.inertialPanningX = 0;
  47898. _this.inertialPanningY = 0;
  47899. };
  47900. };
  47901. ArcRotateCamera.prototype.detachControl = function (element) {
  47902. this.inputs.detachElement(element);
  47903. if (this._reset) {
  47904. this._reset();
  47905. }
  47906. };
  47907. ArcRotateCamera.prototype._checkInputs = function () {
  47908. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47909. if (this._collisionTriggered) {
  47910. return;
  47911. }
  47912. this.inputs.checkInputs();
  47913. // Inertia
  47914. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47915. var inertialAlphaOffset = this.inertialAlphaOffset;
  47916. if (this.beta <= 0)
  47917. inertialAlphaOffset *= -1;
  47918. if (this.getScene().useRightHandedSystem)
  47919. inertialAlphaOffset *= -1;
  47920. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47921. inertialAlphaOffset *= -1;
  47922. this.alpha += inertialAlphaOffset;
  47923. this.beta += this.inertialBetaOffset;
  47924. this.radius -= this.inertialRadiusOffset;
  47925. this.inertialAlphaOffset *= this.inertia;
  47926. this.inertialBetaOffset *= this.inertia;
  47927. this.inertialRadiusOffset *= this.inertia;
  47928. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47929. this.inertialAlphaOffset = 0;
  47930. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47931. this.inertialBetaOffset = 0;
  47932. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47933. this.inertialRadiusOffset = 0;
  47934. }
  47935. // Panning inertia
  47936. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47937. if (!this._localDirection) {
  47938. this._localDirection = BABYLON.Vector3.Zero();
  47939. this._transformedDirection = BABYLON.Vector3.Zero();
  47940. }
  47941. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47942. this._localDirection.multiplyInPlace(this.panningAxis);
  47943. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47944. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47945. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47946. if (!this.panningAxis.y) {
  47947. this._transformedDirection.y = 0;
  47948. }
  47949. if (!this._targetHost) {
  47950. if (this.panningDistanceLimit) {
  47951. this._transformedDirection.addInPlace(this._target);
  47952. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47953. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47954. this._target.copyFrom(this._transformedDirection);
  47955. }
  47956. }
  47957. else {
  47958. this._target.addInPlace(this._transformedDirection);
  47959. }
  47960. }
  47961. this.inertialPanningX *= this.panningInertia;
  47962. this.inertialPanningY *= this.panningInertia;
  47963. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47964. this.inertialPanningX = 0;
  47965. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47966. this.inertialPanningY = 0;
  47967. }
  47968. // Limits
  47969. this._checkLimits();
  47970. _super.prototype._checkInputs.call(this);
  47971. };
  47972. ArcRotateCamera.prototype._checkLimits = function () {
  47973. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47974. if (this.allowUpsideDown && this.beta > Math.PI) {
  47975. this.beta = this.beta - (2 * Math.PI);
  47976. }
  47977. }
  47978. else {
  47979. if (this.beta < this.lowerBetaLimit) {
  47980. this.beta = this.lowerBetaLimit;
  47981. }
  47982. }
  47983. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47984. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47985. this.beta = this.beta + (2 * Math.PI);
  47986. }
  47987. }
  47988. else {
  47989. if (this.beta > this.upperBetaLimit) {
  47990. this.beta = this.upperBetaLimit;
  47991. }
  47992. }
  47993. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47994. this.alpha = this.lowerAlphaLimit;
  47995. }
  47996. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47997. this.alpha = this.upperAlphaLimit;
  47998. }
  47999. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48000. this.radius = this.lowerRadiusLimit;
  48001. }
  48002. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48003. this.radius = this.upperRadiusLimit;
  48004. }
  48005. };
  48006. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48007. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48008. this.radius = this._computationVector.length();
  48009. if (this.radius === 0) {
  48010. this.radius = 0.0001; // Just to avoid division by zero
  48011. }
  48012. // Alpha
  48013. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48014. if (this._computationVector.z < 0) {
  48015. this.alpha = 2 * Math.PI - this.alpha;
  48016. }
  48017. // Beta
  48018. this.beta = Math.acos(this._computationVector.y / this.radius);
  48019. this._checkLimits();
  48020. };
  48021. ArcRotateCamera.prototype.setPosition = function (position) {
  48022. if (this.position.equals(position)) {
  48023. return;
  48024. }
  48025. this.position.copyFrom(position);
  48026. this.rebuildAnglesAndRadius();
  48027. };
  48028. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48029. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48030. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48031. if (target.getBoundingInfo) {
  48032. if (toBoundingCenter) {
  48033. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48034. }
  48035. else {
  48036. this._targetBoundingCenter = null;
  48037. }
  48038. this._targetHost = target;
  48039. this._target = this._getTargetPosition();
  48040. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48041. }
  48042. else {
  48043. var newTarget = target;
  48044. var currentTarget = this._getTargetPosition();
  48045. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48046. return;
  48047. }
  48048. this._targetHost = null;
  48049. this._target = newTarget;
  48050. this._targetBoundingCenter = null;
  48051. this.onMeshTargetChangedObservable.notifyObservers(null);
  48052. }
  48053. this.rebuildAnglesAndRadius();
  48054. };
  48055. ArcRotateCamera.prototype._getViewMatrix = function () {
  48056. // Compute
  48057. var cosa = Math.cos(this.alpha);
  48058. var sina = Math.sin(this.alpha);
  48059. var cosb = Math.cos(this.beta);
  48060. var sinb = Math.sin(this.beta);
  48061. if (sinb === 0) {
  48062. sinb = 0.0001;
  48063. }
  48064. var target = this._getTargetPosition();
  48065. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48066. target.addToRef(this._computationVector, this._newPosition);
  48067. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48068. if (!this._collider) {
  48069. this._collider = new BABYLON.Collider();
  48070. }
  48071. this._collider._radius = this.collisionRadius;
  48072. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48073. this._collisionTriggered = true;
  48074. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48075. }
  48076. else {
  48077. this.position.copyFrom(this._newPosition);
  48078. var up = this.upVector;
  48079. if (this.allowUpsideDown && sinb < 0) {
  48080. up = up.clone();
  48081. up = up.negate();
  48082. }
  48083. this._computeViewMatrix(this.position, target, up);
  48084. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48085. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48086. }
  48087. this._currentTarget = target;
  48088. return this._viewMatrix;
  48089. };
  48090. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48091. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48092. meshes = meshes || this.getScene().meshes;
  48093. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48094. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48095. this.radius = distance * this.zoomOnFactor;
  48096. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48097. };
  48098. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48099. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48100. var meshesOrMinMaxVector;
  48101. var distance;
  48102. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48103. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48104. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48105. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48106. }
  48107. else { //minMaxVector and distance
  48108. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48109. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48110. distance = minMaxVectorAndDistance.distance;
  48111. }
  48112. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48113. if (!doNotUpdateMaxZ) {
  48114. this.maxZ = distance * 2;
  48115. }
  48116. };
  48117. /**
  48118. * @override
  48119. * Override Camera.createRigCamera
  48120. */
  48121. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48122. var alphaShift = 0;
  48123. switch (this.cameraRigMode) {
  48124. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48125. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48126. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48127. case BABYLON.Camera.RIG_MODE_VR:
  48128. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48129. break;
  48130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48131. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48132. break;
  48133. }
  48134. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48135. rigCam._cameraRigParams = {};
  48136. return rigCam;
  48137. };
  48138. /**
  48139. * @override
  48140. * Override Camera._updateRigCameras
  48141. */
  48142. ArcRotateCamera.prototype._updateRigCameras = function () {
  48143. var camLeft = this._rigCameras[0];
  48144. var camRight = this._rigCameras[1];
  48145. camLeft.beta = camRight.beta = this.beta;
  48146. camLeft.radius = camRight.radius = this.radius;
  48147. switch (this.cameraRigMode) {
  48148. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48149. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48150. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48151. case BABYLON.Camera.RIG_MODE_VR:
  48152. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48153. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48154. break;
  48155. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48156. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48157. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48158. break;
  48159. }
  48160. _super.prototype._updateRigCameras.call(this);
  48161. };
  48162. ArcRotateCamera.prototype.dispose = function () {
  48163. this.inputs.clear();
  48164. _super.prototype.dispose.call(this);
  48165. };
  48166. ArcRotateCamera.prototype.getClassName = function () {
  48167. return "ArcRotateCamera";
  48168. };
  48169. __decorate([
  48170. BABYLON.serialize()
  48171. ], ArcRotateCamera.prototype, "alpha", void 0);
  48172. __decorate([
  48173. BABYLON.serialize()
  48174. ], ArcRotateCamera.prototype, "beta", void 0);
  48175. __decorate([
  48176. BABYLON.serialize()
  48177. ], ArcRotateCamera.prototype, "radius", void 0);
  48178. __decorate([
  48179. BABYLON.serializeAsVector3("target")
  48180. ], ArcRotateCamera.prototype, "_target", void 0);
  48181. __decorate([
  48182. BABYLON.serialize()
  48183. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48184. __decorate([
  48185. BABYLON.serialize()
  48186. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48187. __decorate([
  48188. BABYLON.serialize()
  48189. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48190. __decorate([
  48191. BABYLON.serialize()
  48192. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48193. __decorate([
  48194. BABYLON.serialize()
  48195. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48196. __decorate([
  48197. BABYLON.serialize()
  48198. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48199. __decorate([
  48200. BABYLON.serialize()
  48201. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48202. __decorate([
  48203. BABYLON.serialize()
  48204. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48205. __decorate([
  48206. BABYLON.serialize()
  48207. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48208. __decorate([
  48209. BABYLON.serialize()
  48210. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48211. __decorate([
  48212. BABYLON.serialize()
  48213. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48214. __decorate([
  48215. BABYLON.serialize()
  48216. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48217. __decorate([
  48218. BABYLON.serialize()
  48219. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48220. __decorate([
  48221. BABYLON.serializeAsVector3()
  48222. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48223. __decorate([
  48224. BABYLON.serialize()
  48225. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48226. __decorate([
  48227. BABYLON.serialize()
  48228. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48229. __decorate([
  48230. BABYLON.serialize()
  48231. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48232. return ArcRotateCamera;
  48233. }(BABYLON.TargetCamera));
  48234. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48235. })(BABYLON || (BABYLON = {}));
  48236. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48237. var BABYLON;
  48238. (function (BABYLON) {
  48239. /**
  48240. * The HemisphericLight simulates the ambient environment light,
  48241. * so the passed direction is the light reflection direction, not the incoming direction.
  48242. */
  48243. var HemisphericLight = /** @class */ (function (_super) {
  48244. __extends(HemisphericLight, _super);
  48245. /**
  48246. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48247. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48248. * The HemisphericLight can't cast shadows.
  48249. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48250. * @param name The friendly name of the light
  48251. * @param direction The direction of the light reflection
  48252. * @param scene The scene the light belongs to
  48253. */
  48254. function HemisphericLight(name, direction, scene) {
  48255. var _this = _super.call(this, name, scene) || this;
  48256. /**
  48257. * The groundColor is the light in the opposite direction to the one specified during creation.
  48258. * 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.
  48259. */
  48260. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48261. _this.direction = direction || BABYLON.Vector3.Up();
  48262. return _this;
  48263. }
  48264. HemisphericLight.prototype._buildUniformLayout = function () {
  48265. this._uniformBuffer.addUniform("vLightData", 4);
  48266. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48267. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48268. this._uniformBuffer.addUniform("vLightGround", 3);
  48269. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48270. this._uniformBuffer.addUniform("depthValues", 2);
  48271. this._uniformBuffer.create();
  48272. };
  48273. /**
  48274. * Returns the string "HemisphericLight".
  48275. * @return The class name
  48276. */
  48277. HemisphericLight.prototype.getClassName = function () {
  48278. return "HemisphericLight";
  48279. };
  48280. /**
  48281. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48282. * Returns the updated direction.
  48283. * @param target The target the direction should point to
  48284. * @return The computed direction
  48285. */
  48286. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48287. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48288. return this.direction;
  48289. };
  48290. /**
  48291. * Returns the shadow generator associated to the light.
  48292. * @returns Always null for hemispheric lights because it does not support shadows.
  48293. */
  48294. HemisphericLight.prototype.getShadowGenerator = function () {
  48295. return null;
  48296. };
  48297. /**
  48298. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48299. * @param effect The effect to update
  48300. * @param lightIndex The index of the light in the effect to update
  48301. * @returns The hemispheric light
  48302. */
  48303. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48304. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48305. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48306. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48307. return this;
  48308. };
  48309. /**
  48310. * @hidden internal use only.
  48311. */
  48312. HemisphericLight.prototype._getWorldMatrix = function () {
  48313. if (!this._worldMatrix) {
  48314. this._worldMatrix = BABYLON.Matrix.Identity();
  48315. }
  48316. return this._worldMatrix;
  48317. };
  48318. /**
  48319. * Returns the integer 3.
  48320. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48321. */
  48322. HemisphericLight.prototype.getTypeID = function () {
  48323. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48324. };
  48325. __decorate([
  48326. BABYLON.serializeAsColor3()
  48327. ], HemisphericLight.prototype, "groundColor", void 0);
  48328. __decorate([
  48329. BABYLON.serializeAsVector3()
  48330. ], HemisphericLight.prototype, "direction", void 0);
  48331. return HemisphericLight;
  48332. }(BABYLON.Light));
  48333. BABYLON.HemisphericLight = HemisphericLight;
  48334. })(BABYLON || (BABYLON = {}));
  48335. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48336. var BABYLON;
  48337. (function (BABYLON) {
  48338. /**
  48339. * Base implementation IShadowLight
  48340. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48341. */
  48342. var ShadowLight = /** @class */ (function (_super) {
  48343. __extends(ShadowLight, _super);
  48344. function ShadowLight() {
  48345. var _this = _super !== null && _super.apply(this, arguments) || this;
  48346. _this._needProjectionMatrixCompute = true;
  48347. return _this;
  48348. }
  48349. ShadowLight.prototype._setPosition = function (value) {
  48350. this._position = value;
  48351. };
  48352. Object.defineProperty(ShadowLight.prototype, "position", {
  48353. /**
  48354. * Sets the position the shadow will be casted from. Also use as the light position for both
  48355. * point and spot lights.
  48356. */
  48357. get: function () {
  48358. return this._position;
  48359. },
  48360. /**
  48361. * Sets the position the shadow will be casted from. Also use as the light position for both
  48362. * point and spot lights.
  48363. */
  48364. set: function (value) {
  48365. this._setPosition(value);
  48366. },
  48367. enumerable: true,
  48368. configurable: true
  48369. });
  48370. ShadowLight.prototype._setDirection = function (value) {
  48371. this._direction = value;
  48372. };
  48373. Object.defineProperty(ShadowLight.prototype, "direction", {
  48374. /**
  48375. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48376. * Also use as the light direction on spot and directional lights.
  48377. */
  48378. get: function () {
  48379. return this._direction;
  48380. },
  48381. /**
  48382. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48383. * Also use as the light direction on spot and directional lights.
  48384. */
  48385. set: function (value) {
  48386. this._setDirection(value);
  48387. },
  48388. enumerable: true,
  48389. configurable: true
  48390. });
  48391. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48392. /**
  48393. * Gets the shadow projection clipping minimum z value.
  48394. */
  48395. get: function () {
  48396. return this._shadowMinZ;
  48397. },
  48398. /**
  48399. * Sets the shadow projection clipping minimum z value.
  48400. */
  48401. set: function (value) {
  48402. this._shadowMinZ = value;
  48403. this.forceProjectionMatrixCompute();
  48404. },
  48405. enumerable: true,
  48406. configurable: true
  48407. });
  48408. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48409. /**
  48410. * Sets the shadow projection clipping maximum z value.
  48411. */
  48412. get: function () {
  48413. return this._shadowMaxZ;
  48414. },
  48415. /**
  48416. * Gets the shadow projection clipping maximum z value.
  48417. */
  48418. set: function (value) {
  48419. this._shadowMaxZ = value;
  48420. this.forceProjectionMatrixCompute();
  48421. },
  48422. enumerable: true,
  48423. configurable: true
  48424. });
  48425. /**
  48426. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48427. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48428. */
  48429. ShadowLight.prototype.computeTransformedInformation = function () {
  48430. if (this.parent && this.parent.getWorldMatrix) {
  48431. if (!this.transformedPosition) {
  48432. this.transformedPosition = BABYLON.Vector3.Zero();
  48433. }
  48434. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48435. // In case the direction is present.
  48436. if (this.direction) {
  48437. if (!this.transformedDirection) {
  48438. this.transformedDirection = BABYLON.Vector3.Zero();
  48439. }
  48440. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48441. }
  48442. return true;
  48443. }
  48444. return false;
  48445. };
  48446. /**
  48447. * Return the depth scale used for the shadow map.
  48448. * @returns the depth scale.
  48449. */
  48450. ShadowLight.prototype.getDepthScale = function () {
  48451. return 50.0;
  48452. };
  48453. /**
  48454. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48455. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48456. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48457. */
  48458. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48459. return this.transformedDirection ? this.transformedDirection : this.direction;
  48460. };
  48461. /**
  48462. * Returns the ShadowLight absolute position in the World.
  48463. * @returns the position vector in world space
  48464. */
  48465. ShadowLight.prototype.getAbsolutePosition = function () {
  48466. return this.transformedPosition ? this.transformedPosition : this.position;
  48467. };
  48468. /**
  48469. * Sets the ShadowLight direction toward the passed target.
  48470. * @param target The point tot target in local space
  48471. * @returns the updated ShadowLight direction
  48472. */
  48473. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48474. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48475. return this.direction;
  48476. };
  48477. /**
  48478. * Returns the light rotation in euler definition.
  48479. * @returns the x y z rotation in local space.
  48480. */
  48481. ShadowLight.prototype.getRotation = function () {
  48482. this.direction.normalize();
  48483. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48484. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48485. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48486. };
  48487. /**
  48488. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48489. * @returns true if a cube texture needs to be use
  48490. */
  48491. ShadowLight.prototype.needCube = function () {
  48492. return false;
  48493. };
  48494. /**
  48495. * Detects if the projection matrix requires to be recomputed this frame.
  48496. * @returns true if it requires to be recomputed otherwise, false.
  48497. */
  48498. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48499. return this._needProjectionMatrixCompute;
  48500. };
  48501. /**
  48502. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48503. */
  48504. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48505. this._needProjectionMatrixCompute = true;
  48506. };
  48507. /**
  48508. * Get the world matrix of the sahdow lights.
  48509. * @hidden Internal Use Only
  48510. */
  48511. ShadowLight.prototype._getWorldMatrix = function () {
  48512. if (!this._worldMatrix) {
  48513. this._worldMatrix = BABYLON.Matrix.Identity();
  48514. }
  48515. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48516. return this._worldMatrix;
  48517. };
  48518. /**
  48519. * Gets the minZ used for shadow according to both the scene and the light.
  48520. * @param activeCamera The camera we are returning the min for
  48521. * @returns the depth min z
  48522. */
  48523. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48524. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48525. };
  48526. /**
  48527. * Gets the maxZ used for shadow according to both the scene and the light.
  48528. * @param activeCamera The camera we are returning the max for
  48529. * @returns the depth max z
  48530. */
  48531. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48532. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48533. };
  48534. /**
  48535. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48536. * @param matrix The materix to updated with the projection information
  48537. * @param viewMatrix The transform matrix of the light
  48538. * @param renderList The list of mesh to render in the map
  48539. * @returns The current light
  48540. */
  48541. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48542. if (this.customProjectionMatrixBuilder) {
  48543. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48544. }
  48545. else {
  48546. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48547. }
  48548. return this;
  48549. };
  48550. __decorate([
  48551. BABYLON.serializeAsVector3()
  48552. ], ShadowLight.prototype, "position", null);
  48553. __decorate([
  48554. BABYLON.serializeAsVector3()
  48555. ], ShadowLight.prototype, "direction", null);
  48556. __decorate([
  48557. BABYLON.serialize()
  48558. ], ShadowLight.prototype, "shadowMinZ", null);
  48559. __decorate([
  48560. BABYLON.serialize()
  48561. ], ShadowLight.prototype, "shadowMaxZ", null);
  48562. return ShadowLight;
  48563. }(BABYLON.Light));
  48564. BABYLON.ShadowLight = ShadowLight;
  48565. })(BABYLON || (BABYLON = {}));
  48566. //# sourceMappingURL=babylon.shadowLight.js.map
  48567. var BABYLON;
  48568. (function (BABYLON) {
  48569. /**
  48570. * A point light is a light defined by an unique point in world space.
  48571. * The light is emitted in every direction from this point.
  48572. * A good example of a point light is a standard light bulb.
  48573. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48574. */
  48575. var PointLight = /** @class */ (function (_super) {
  48576. __extends(PointLight, _super);
  48577. /**
  48578. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48579. * A PointLight emits the light in every direction.
  48580. * It can cast shadows.
  48581. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48582. * ```javascript
  48583. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48584. * ```
  48585. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48586. * @param name The light friendly name
  48587. * @param position The position of the point light in the scene
  48588. * @param scene The scene the lights belongs to
  48589. */
  48590. function PointLight(name, position, scene) {
  48591. var _this = _super.call(this, name, scene) || this;
  48592. _this._shadowAngle = Math.PI / 2;
  48593. _this.position = position;
  48594. return _this;
  48595. }
  48596. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48597. /**
  48598. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48599. * This specifies what angle the shadow will use to be created.
  48600. *
  48601. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48602. */
  48603. get: function () {
  48604. return this._shadowAngle;
  48605. },
  48606. /**
  48607. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48608. * This specifies what angle the shadow will use to be created.
  48609. *
  48610. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48611. */
  48612. set: function (value) {
  48613. this._shadowAngle = value;
  48614. this.forceProjectionMatrixCompute();
  48615. },
  48616. enumerable: true,
  48617. configurable: true
  48618. });
  48619. Object.defineProperty(PointLight.prototype, "direction", {
  48620. /**
  48621. * Gets the direction if it has been set.
  48622. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48623. */
  48624. get: function () {
  48625. return this._direction;
  48626. },
  48627. /**
  48628. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48629. */
  48630. set: function (value) {
  48631. var previousNeedCube = this.needCube();
  48632. this._direction = value;
  48633. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48634. this._shadowGenerator.recreateShadowMap();
  48635. }
  48636. },
  48637. enumerable: true,
  48638. configurable: true
  48639. });
  48640. /**
  48641. * Returns the string "PointLight"
  48642. * @returns the class name
  48643. */
  48644. PointLight.prototype.getClassName = function () {
  48645. return "PointLight";
  48646. };
  48647. /**
  48648. * Returns the integer 0.
  48649. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48650. */
  48651. PointLight.prototype.getTypeID = function () {
  48652. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48653. };
  48654. /**
  48655. * Specifies wether or not the shadowmap should be a cube texture.
  48656. * @returns true if the shadowmap needs to be a cube texture.
  48657. */
  48658. PointLight.prototype.needCube = function () {
  48659. return !this.direction;
  48660. };
  48661. /**
  48662. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48663. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48664. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48665. */
  48666. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48667. if (this.direction) {
  48668. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48669. }
  48670. else {
  48671. switch (faceIndex) {
  48672. case 0:
  48673. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48674. case 1:
  48675. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48676. case 2:
  48677. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48678. case 3:
  48679. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48680. case 4:
  48681. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48682. case 5:
  48683. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48684. }
  48685. }
  48686. return BABYLON.Vector3.Zero();
  48687. };
  48688. /**
  48689. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48690. * - fov = PI / 2
  48691. * - aspect ratio : 1.0
  48692. * - z-near and far equal to the active camera minZ and maxZ.
  48693. * Returns the PointLight.
  48694. */
  48695. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48696. var activeCamera = this.getScene().activeCamera;
  48697. if (!activeCamera) {
  48698. return;
  48699. }
  48700. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48701. };
  48702. PointLight.prototype._buildUniformLayout = function () {
  48703. this._uniformBuffer.addUniform("vLightData", 4);
  48704. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48705. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48706. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48707. this._uniformBuffer.addUniform("depthValues", 2);
  48708. this._uniformBuffer.create();
  48709. };
  48710. /**
  48711. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48712. * @param effect The effect to update
  48713. * @param lightIndex The index of the light in the effect to update
  48714. * @returns The point light
  48715. */
  48716. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48717. if (this.computeTransformedInformation()) {
  48718. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48719. return this;
  48720. }
  48721. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48722. return this;
  48723. };
  48724. __decorate([
  48725. BABYLON.serialize()
  48726. ], PointLight.prototype, "shadowAngle", null);
  48727. return PointLight;
  48728. }(BABYLON.ShadowLight));
  48729. BABYLON.PointLight = PointLight;
  48730. })(BABYLON || (BABYLON = {}));
  48731. //# sourceMappingURL=babylon.pointLight.js.map
  48732. var BABYLON;
  48733. (function (BABYLON) {
  48734. /**
  48735. * A directional light is defined by a direction (what a surprise!).
  48736. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48737. * 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.
  48738. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48739. */
  48740. var DirectionalLight = /** @class */ (function (_super) {
  48741. __extends(DirectionalLight, _super);
  48742. /**
  48743. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48744. * The directional light is emitted from everywhere in the given direction.
  48745. * It can cast shawdows.
  48746. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48747. * @param name The friendly name of the light
  48748. * @param direction The direction of the light
  48749. * @param scene The scene the light belongs to
  48750. */
  48751. function DirectionalLight(name, direction, scene) {
  48752. var _this = _super.call(this, name, scene) || this;
  48753. _this._shadowFrustumSize = 0;
  48754. _this._shadowOrthoScale = 0.1;
  48755. /**
  48756. * Automatically compute the projection matrix to best fit (including all the casters)
  48757. * on each frame.
  48758. */
  48759. _this.autoUpdateExtends = true;
  48760. // Cache
  48761. _this._orthoLeft = Number.MAX_VALUE;
  48762. _this._orthoRight = Number.MIN_VALUE;
  48763. _this._orthoTop = Number.MIN_VALUE;
  48764. _this._orthoBottom = Number.MAX_VALUE;
  48765. _this.position = direction.scale(-1.0);
  48766. _this.direction = direction;
  48767. return _this;
  48768. }
  48769. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48770. /**
  48771. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48772. */
  48773. get: function () {
  48774. return this._shadowFrustumSize;
  48775. },
  48776. /**
  48777. * Specifies a fix frustum size for the shadow generation.
  48778. */
  48779. set: function (value) {
  48780. this._shadowFrustumSize = value;
  48781. this.forceProjectionMatrixCompute();
  48782. },
  48783. enumerable: true,
  48784. configurable: true
  48785. });
  48786. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48787. /**
  48788. * Gets the shadow projection scale against the optimal computed one.
  48789. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48790. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48791. */
  48792. get: function () {
  48793. return this._shadowOrthoScale;
  48794. },
  48795. /**
  48796. * Sets the shadow projection scale against the optimal computed one.
  48797. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48798. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48799. */
  48800. set: function (value) {
  48801. this._shadowOrthoScale = value;
  48802. this.forceProjectionMatrixCompute();
  48803. },
  48804. enumerable: true,
  48805. configurable: true
  48806. });
  48807. /**
  48808. * Returns the string "DirectionalLight".
  48809. * @return The class name
  48810. */
  48811. DirectionalLight.prototype.getClassName = function () {
  48812. return "DirectionalLight";
  48813. };
  48814. /**
  48815. * Returns the integer 1.
  48816. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48817. */
  48818. DirectionalLight.prototype.getTypeID = function () {
  48819. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48820. };
  48821. /**
  48822. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48823. * Returns the DirectionalLight Shadow projection matrix.
  48824. */
  48825. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48826. if (this.shadowFrustumSize > 0) {
  48827. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48828. }
  48829. else {
  48830. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48831. }
  48832. };
  48833. /**
  48834. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48835. * Returns the DirectionalLight Shadow projection matrix.
  48836. */
  48837. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48838. var activeCamera = this.getScene().activeCamera;
  48839. if (!activeCamera) {
  48840. return;
  48841. }
  48842. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48843. };
  48844. /**
  48845. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48846. * Returns the DirectionalLight Shadow projection matrix.
  48847. */
  48848. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48849. var activeCamera = this.getScene().activeCamera;
  48850. if (!activeCamera) {
  48851. return;
  48852. }
  48853. // Check extends
  48854. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48855. var tempVector3 = BABYLON.Vector3.Zero();
  48856. this._orthoLeft = Number.MAX_VALUE;
  48857. this._orthoRight = Number.MIN_VALUE;
  48858. this._orthoTop = Number.MIN_VALUE;
  48859. this._orthoBottom = Number.MAX_VALUE;
  48860. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48861. var mesh = renderList[meshIndex];
  48862. if (!mesh) {
  48863. continue;
  48864. }
  48865. var boundingInfo = mesh.getBoundingInfo();
  48866. var boundingBox = boundingInfo.boundingBox;
  48867. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48868. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48869. if (tempVector3.x < this._orthoLeft)
  48870. this._orthoLeft = tempVector3.x;
  48871. if (tempVector3.y < this._orthoBottom)
  48872. this._orthoBottom = tempVector3.y;
  48873. if (tempVector3.x > this._orthoRight)
  48874. this._orthoRight = tempVector3.x;
  48875. if (tempVector3.y > this._orthoTop)
  48876. this._orthoTop = tempVector3.y;
  48877. }
  48878. }
  48879. }
  48880. var xOffset = this._orthoRight - this._orthoLeft;
  48881. var yOffset = this._orthoTop - this._orthoBottom;
  48882. 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);
  48883. };
  48884. DirectionalLight.prototype._buildUniformLayout = function () {
  48885. this._uniformBuffer.addUniform("vLightData", 4);
  48886. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48887. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48888. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48889. this._uniformBuffer.addUniform("depthValues", 2);
  48890. this._uniformBuffer.create();
  48891. };
  48892. /**
  48893. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48894. * @param effect The effect to update
  48895. * @param lightIndex The index of the light in the effect to update
  48896. * @returns The directional light
  48897. */
  48898. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48899. if (this.computeTransformedInformation()) {
  48900. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48901. return this;
  48902. }
  48903. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48904. return this;
  48905. };
  48906. /**
  48907. * Gets the minZ used for shadow according to both the scene and the light.
  48908. *
  48909. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48910. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48911. * @param activeCamera The camera we are returning the min for
  48912. * @returns the depth min z
  48913. */
  48914. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48915. return 1;
  48916. };
  48917. /**
  48918. * Gets the maxZ used for shadow according to both the scene and the light.
  48919. *
  48920. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48921. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48922. * @param activeCamera The camera we are returning the max for
  48923. * @returns the depth max z
  48924. */
  48925. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48926. return 1;
  48927. };
  48928. __decorate([
  48929. BABYLON.serialize()
  48930. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48931. __decorate([
  48932. BABYLON.serialize()
  48933. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48934. __decorate([
  48935. BABYLON.serialize()
  48936. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48937. return DirectionalLight;
  48938. }(BABYLON.ShadowLight));
  48939. BABYLON.DirectionalLight = DirectionalLight;
  48940. })(BABYLON || (BABYLON = {}));
  48941. //# sourceMappingURL=babylon.directionalLight.js.map
  48942. var BABYLON;
  48943. (function (BABYLON) {
  48944. /**
  48945. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48946. * These values define a cone of light starting from the position, emitting toward the direction.
  48947. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48948. * and the exponent defines the speed of the decay of the light with distance (reach).
  48949. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48950. */
  48951. var SpotLight = /** @class */ (function (_super) {
  48952. __extends(SpotLight, _super);
  48953. /**
  48954. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48955. * It can cast shadows.
  48956. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48957. * @param name The light friendly name
  48958. * @param position The position of the spot light in the scene
  48959. * @param direction The direction of the light in the scene
  48960. * @param angle The cone angle of the light in Radians
  48961. * @param exponent The light decay speed with the distance from the emission spot
  48962. * @param scene The scene the lights belongs to
  48963. */
  48964. function SpotLight(name, position, direction, angle, exponent, scene) {
  48965. var _this = _super.call(this, name, scene) || this;
  48966. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48967. _this._projectionTextureLightNear = 1e-6;
  48968. _this._projectionTextureLightFar = 1000.0;
  48969. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48970. _this._projectionTextureViewLightDirty = true;
  48971. _this._projectionTextureProjectionLightDirty = true;
  48972. _this._projectionTextureDirty = true;
  48973. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48974. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48975. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48976. _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);
  48977. _this.position = position;
  48978. _this.direction = direction;
  48979. _this.angle = angle;
  48980. _this.exponent = exponent;
  48981. return _this;
  48982. }
  48983. Object.defineProperty(SpotLight.prototype, "angle", {
  48984. /**
  48985. * Gets the cone angle of the spot light in Radians.
  48986. */
  48987. get: function () {
  48988. return this._angle;
  48989. },
  48990. /**
  48991. * Sets the cone angle of the spot light in Radians.
  48992. */
  48993. set: function (value) {
  48994. this._angle = value;
  48995. this._projectionTextureProjectionLightDirty = true;
  48996. this.forceProjectionMatrixCompute();
  48997. },
  48998. enumerable: true,
  48999. configurable: true
  49000. });
  49001. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49002. /**
  49003. * Allows scaling the angle of the light for shadow generation only.
  49004. */
  49005. get: function () {
  49006. return this._shadowAngleScale;
  49007. },
  49008. /**
  49009. * Allows scaling the angle of the light for shadow generation only.
  49010. */
  49011. set: function (value) {
  49012. this._shadowAngleScale = value;
  49013. this.forceProjectionMatrixCompute();
  49014. },
  49015. enumerable: true,
  49016. configurable: true
  49017. });
  49018. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49019. /**
  49020. * Allows reading the projecton texture
  49021. */
  49022. get: function () {
  49023. return this._projectionTextureMatrix;
  49024. },
  49025. enumerable: true,
  49026. configurable: true
  49027. });
  49028. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49029. /**
  49030. * Gets the near clip of the Spotlight for texture projection.
  49031. */
  49032. get: function () {
  49033. return this._projectionTextureLightNear;
  49034. },
  49035. /**
  49036. * Sets the near clip of the Spotlight for texture projection.
  49037. */
  49038. set: function (value) {
  49039. this._projectionTextureLightNear = value;
  49040. this._projectionTextureProjectionLightDirty = true;
  49041. },
  49042. enumerable: true,
  49043. configurable: true
  49044. });
  49045. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49046. /**
  49047. * Gets the far clip of the Spotlight for texture projection.
  49048. */
  49049. get: function () {
  49050. return this._projectionTextureLightFar;
  49051. },
  49052. /**
  49053. * Sets the far clip of the Spotlight for texture projection.
  49054. */
  49055. set: function (value) {
  49056. this._projectionTextureLightFar = value;
  49057. this._projectionTextureProjectionLightDirty = true;
  49058. },
  49059. enumerable: true,
  49060. configurable: true
  49061. });
  49062. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49063. /**
  49064. * Gets the Up vector of the Spotlight for texture projection.
  49065. */
  49066. get: function () {
  49067. return this._projectionTextureUpDirection;
  49068. },
  49069. /**
  49070. * Sets the Up vector of the Spotlight for texture projection.
  49071. */
  49072. set: function (value) {
  49073. this._projectionTextureUpDirection = value;
  49074. this._projectionTextureProjectionLightDirty = true;
  49075. },
  49076. enumerable: true,
  49077. configurable: true
  49078. });
  49079. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49080. /**
  49081. * Gets the projection texture of the light.
  49082. */
  49083. get: function () {
  49084. return this._projectionTexture;
  49085. },
  49086. /**
  49087. * Sets the projection texture of the light.
  49088. */
  49089. set: function (value) {
  49090. this._projectionTexture = value;
  49091. this._projectionTextureDirty = true;
  49092. },
  49093. enumerable: true,
  49094. configurable: true
  49095. });
  49096. /**
  49097. * Returns the string "SpotLight".
  49098. * @returns the class name
  49099. */
  49100. SpotLight.prototype.getClassName = function () {
  49101. return "SpotLight";
  49102. };
  49103. /**
  49104. * Returns the integer 2.
  49105. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49106. */
  49107. SpotLight.prototype.getTypeID = function () {
  49108. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49109. };
  49110. /**
  49111. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49112. */
  49113. SpotLight.prototype._setDirection = function (value) {
  49114. _super.prototype._setDirection.call(this, value);
  49115. this._projectionTextureViewLightDirty = true;
  49116. };
  49117. /**
  49118. * Overrides the position setter to recompute the projection texture view light Matrix.
  49119. */
  49120. SpotLight.prototype._setPosition = function (value) {
  49121. _super.prototype._setPosition.call(this, value);
  49122. this._projectionTextureViewLightDirty = true;
  49123. };
  49124. /**
  49125. * 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.
  49126. * Returns the SpotLight.
  49127. */
  49128. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49129. var activeCamera = this.getScene().activeCamera;
  49130. if (!activeCamera) {
  49131. return;
  49132. }
  49133. this._shadowAngleScale = this._shadowAngleScale || 1;
  49134. var angle = this._shadowAngleScale * this._angle;
  49135. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49136. };
  49137. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49138. this._projectionTextureViewLightDirty = false;
  49139. this._projectionTextureDirty = true;
  49140. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49141. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49142. };
  49143. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49144. this._projectionTextureProjectionLightDirty = false;
  49145. this._projectionTextureDirty = true;
  49146. var light_far = this.projectionTextureLightFar;
  49147. var light_near = this.projectionTextureLightNear;
  49148. var P = light_far / (light_far - light_near);
  49149. var Q = -P * light_near;
  49150. var S = 1.0 / Math.tan(this._angle / 2.0);
  49151. var A = 1.0;
  49152. 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);
  49153. };
  49154. /**
  49155. * Main function for light texture projection matrix computing.
  49156. */
  49157. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49158. this._projectionTextureDirty = false;
  49159. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49160. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49161. };
  49162. SpotLight.prototype._buildUniformLayout = function () {
  49163. this._uniformBuffer.addUniform("vLightData", 4);
  49164. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49165. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49166. this._uniformBuffer.addUniform("vLightDirection", 3);
  49167. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49168. this._uniformBuffer.addUniform("depthValues", 2);
  49169. this._uniformBuffer.create();
  49170. };
  49171. /**
  49172. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49173. * @param effect The effect to update
  49174. * @param lightIndex The index of the light in the effect to update
  49175. * @returns The spot light
  49176. */
  49177. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49178. var normalizeDirection;
  49179. if (this.computeTransformedInformation()) {
  49180. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49181. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49182. }
  49183. else {
  49184. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49185. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49186. }
  49187. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49188. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49189. if (this._projectionTextureViewLightDirty) {
  49190. this._computeProjectionTextureViewLightMatrix();
  49191. }
  49192. if (this._projectionTextureProjectionLightDirty) {
  49193. this._computeProjectionTextureProjectionLightMatrix();
  49194. }
  49195. if (this._projectionTextureDirty) {
  49196. this._computeProjectionTextureMatrix();
  49197. }
  49198. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49199. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49200. }
  49201. return this;
  49202. };
  49203. /**
  49204. * Disposes the light and the associated resources.
  49205. */
  49206. SpotLight.prototype.dispose = function () {
  49207. _super.prototype.dispose.call(this);
  49208. if (this._projectionTexture) {
  49209. this._projectionTexture.dispose();
  49210. }
  49211. };
  49212. __decorate([
  49213. BABYLON.serialize()
  49214. ], SpotLight.prototype, "angle", null);
  49215. __decorate([
  49216. BABYLON.serialize()
  49217. ], SpotLight.prototype, "shadowAngleScale", null);
  49218. __decorate([
  49219. BABYLON.serialize()
  49220. ], SpotLight.prototype, "exponent", void 0);
  49221. __decorate([
  49222. BABYLON.serialize()
  49223. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49224. __decorate([
  49225. BABYLON.serialize()
  49226. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49227. __decorate([
  49228. BABYLON.serialize()
  49229. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49230. __decorate([
  49231. BABYLON.serializeAsTexture("projectedLightTexture")
  49232. ], SpotLight.prototype, "_projectionTexture", void 0);
  49233. return SpotLight;
  49234. }(BABYLON.ShadowLight));
  49235. BABYLON.SpotLight = SpotLight;
  49236. })(BABYLON || (BABYLON = {}));
  49237. //# sourceMappingURL=babylon.spotLight.js.map
  49238. var BABYLON;
  49239. (function (BABYLON) {
  49240. /**
  49241. * Class used to override all child animations of a given target
  49242. */
  49243. var AnimationPropertiesOverride = /** @class */ (function () {
  49244. function AnimationPropertiesOverride() {
  49245. /**
  49246. * Gets or sets a value indicating if animation blending must be used
  49247. */
  49248. this.enableBlending = false;
  49249. /**
  49250. * Gets or sets the blending speed to use when enableBlending is true
  49251. */
  49252. this.blendingSpeed = 0.01;
  49253. /**
  49254. * Gets or sets the default loop mode to use
  49255. */
  49256. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49257. }
  49258. return AnimationPropertiesOverride;
  49259. }());
  49260. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49261. })(BABYLON || (BABYLON = {}));
  49262. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49263. var BABYLON;
  49264. (function (BABYLON) {
  49265. /**
  49266. * Represents the range of an animation
  49267. */
  49268. var AnimationRange = /** @class */ (function () {
  49269. /**
  49270. * Initializes the range of an animation
  49271. * @param name The name of the animation range
  49272. * @param from The starting frame of the animation
  49273. * @param to The ending frame of the animation
  49274. */
  49275. function AnimationRange(
  49276. /**The name of the animation range**/
  49277. name,
  49278. /**The starting frame of the animation */
  49279. from,
  49280. /**The ending frame of the animation*/
  49281. to) {
  49282. this.name = name;
  49283. this.from = from;
  49284. this.to = to;
  49285. }
  49286. /**
  49287. * Makes a copy of the animation range
  49288. * @returns A copy of the animation range
  49289. */
  49290. AnimationRange.prototype.clone = function () {
  49291. return new AnimationRange(this.name, this.from, this.to);
  49292. };
  49293. return AnimationRange;
  49294. }());
  49295. BABYLON.AnimationRange = AnimationRange;
  49296. /**
  49297. * Composed of a frame, and an action function
  49298. */
  49299. var AnimationEvent = /** @class */ (function () {
  49300. /**
  49301. * Initializes the animation event
  49302. * @param frame The frame for which the event is triggered
  49303. * @param action The event to perform when triggered
  49304. * @param onlyOnce Specifies if the event should be triggered only once
  49305. */
  49306. function AnimationEvent(
  49307. /** The frame for which the event is triggered **/
  49308. frame,
  49309. /** The event to perform when triggered **/
  49310. action,
  49311. /** Specifies if the event should be triggered only once**/
  49312. onlyOnce) {
  49313. this.frame = frame;
  49314. this.action = action;
  49315. this.onlyOnce = onlyOnce;
  49316. /**
  49317. * Specifies if the animation event is done
  49318. */
  49319. this.isDone = false;
  49320. }
  49321. /** @hidden */
  49322. AnimationEvent.prototype._clone = function () {
  49323. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49324. };
  49325. return AnimationEvent;
  49326. }());
  49327. BABYLON.AnimationEvent = AnimationEvent;
  49328. /**
  49329. * A cursor which tracks a point on a path
  49330. */
  49331. var PathCursor = /** @class */ (function () {
  49332. /**
  49333. * Initializes the path cursor
  49334. * @param path The path to track
  49335. */
  49336. function PathCursor(path) {
  49337. this.path = path;
  49338. /**
  49339. * Stores path cursor callbacks for when an onchange event is triggered
  49340. */
  49341. this._onchange = new Array();
  49342. /**
  49343. * The value of the path cursor
  49344. */
  49345. this.value = 0;
  49346. /**
  49347. * The animation array of the path cursor
  49348. */
  49349. this.animations = new Array();
  49350. }
  49351. /**
  49352. * Gets the cursor point on the path
  49353. * @returns A point on the path cursor at the cursor location
  49354. */
  49355. PathCursor.prototype.getPoint = function () {
  49356. var point = this.path.getPointAtLengthPosition(this.value);
  49357. return new BABYLON.Vector3(point.x, 0, point.y);
  49358. };
  49359. /**
  49360. * Moves the cursor ahead by the step amount
  49361. * @param step The amount to move the cursor forward
  49362. * @returns This path cursor
  49363. */
  49364. PathCursor.prototype.moveAhead = function (step) {
  49365. if (step === void 0) { step = 0.002; }
  49366. this.move(step);
  49367. return this;
  49368. };
  49369. /**
  49370. * Moves the cursor behind by the step amount
  49371. * @param step The amount to move the cursor back
  49372. * @returns This path cursor
  49373. */
  49374. PathCursor.prototype.moveBack = function (step) {
  49375. if (step === void 0) { step = 0.002; }
  49376. this.move(-step);
  49377. return this;
  49378. };
  49379. /**
  49380. * Moves the cursor by the step amount
  49381. * If the step amount is greater than one, an exception is thrown
  49382. * @param step The amount to move the cursor
  49383. * @returns This path cursor
  49384. */
  49385. PathCursor.prototype.move = function (step) {
  49386. if (Math.abs(step) > 1) {
  49387. throw "step size should be less than 1.";
  49388. }
  49389. this.value += step;
  49390. this.ensureLimits();
  49391. this.raiseOnChange();
  49392. return this;
  49393. };
  49394. /**
  49395. * Ensures that the value is limited between zero and one
  49396. * @returns This path cursor
  49397. */
  49398. PathCursor.prototype.ensureLimits = function () {
  49399. while (this.value > 1) {
  49400. this.value -= 1;
  49401. }
  49402. while (this.value < 0) {
  49403. this.value += 1;
  49404. }
  49405. return this;
  49406. };
  49407. /**
  49408. * Runs onchange callbacks on change (used by the animation engine)
  49409. * @returns This path cursor
  49410. */
  49411. PathCursor.prototype.raiseOnChange = function () {
  49412. var _this = this;
  49413. this._onchange.forEach(function (f) { return f(_this); });
  49414. return this;
  49415. };
  49416. /**
  49417. * Executes a function on change
  49418. * @param f A path cursor onchange callback
  49419. * @returns This path cursor
  49420. */
  49421. PathCursor.prototype.onchange = function (f) {
  49422. this._onchange.push(f);
  49423. return this;
  49424. };
  49425. return PathCursor;
  49426. }());
  49427. BABYLON.PathCursor = PathCursor;
  49428. /**
  49429. * Enum for the animation key frame interpolation type
  49430. */
  49431. var AnimationKeyInterpolation;
  49432. (function (AnimationKeyInterpolation) {
  49433. /**
  49434. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49435. */
  49436. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49437. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49438. /**
  49439. * Class used to store any kind of animation
  49440. */
  49441. var Animation = /** @class */ (function () {
  49442. /**
  49443. * Initializes the animation
  49444. * @param name Name of the animation
  49445. * @param targetProperty Property to animate
  49446. * @param framePerSecond The frames per second of the animation
  49447. * @param dataType The data type of the animation
  49448. * @param loopMode The loop mode of the animation
  49449. * @param enableBlendings Specifies if blending should be enabled
  49450. */
  49451. function Animation(
  49452. /**Name of the animation */
  49453. name,
  49454. /**Property to animate */
  49455. targetProperty,
  49456. /**The frames per second of the animation */
  49457. framePerSecond,
  49458. /**The data type of the animation */
  49459. dataType,
  49460. /**The loop mode of the animation */
  49461. loopMode,
  49462. /**Specifies if blending should be enabled */
  49463. enableBlending) {
  49464. this.name = name;
  49465. this.targetProperty = targetProperty;
  49466. this.framePerSecond = framePerSecond;
  49467. this.dataType = dataType;
  49468. this.loopMode = loopMode;
  49469. this.enableBlending = enableBlending;
  49470. /**
  49471. * @hidden Internal use only
  49472. */
  49473. this._runtimeAnimations = new Array();
  49474. /**
  49475. * The set of event that will be linked to this animation
  49476. */
  49477. this._events = new Array();
  49478. /**
  49479. * Stores the blending speed of the animation
  49480. */
  49481. this.blendingSpeed = 0.01;
  49482. /**
  49483. * Stores the animation ranges for the animation
  49484. */
  49485. this._ranges = {};
  49486. this.targetPropertyPath = targetProperty.split(".");
  49487. this.dataType = dataType;
  49488. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49489. }
  49490. /**
  49491. * @hidden Internal use
  49492. */
  49493. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49494. var dataType = undefined;
  49495. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49496. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49497. }
  49498. else if (from instanceof BABYLON.Quaternion) {
  49499. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49500. }
  49501. else if (from instanceof BABYLON.Vector3) {
  49502. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49503. }
  49504. else if (from instanceof BABYLON.Vector2) {
  49505. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49506. }
  49507. else if (from instanceof BABYLON.Color3) {
  49508. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49509. }
  49510. else if (from instanceof BABYLON.Size) {
  49511. dataType = Animation.ANIMATIONTYPE_SIZE;
  49512. }
  49513. if (dataType == undefined) {
  49514. return null;
  49515. }
  49516. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49517. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49518. animation.setKeys(keys);
  49519. if (easingFunction !== undefined) {
  49520. animation.setEasingFunction(easingFunction);
  49521. }
  49522. return animation;
  49523. };
  49524. /**
  49525. * Sets up an animation
  49526. * @param property The property to animate
  49527. * @param animationType The animation type to apply
  49528. * @param framePerSecond The frames per second of the animation
  49529. * @param easingFunction The easing function used in the animation
  49530. * @returns The created animation
  49531. */
  49532. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49533. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49534. animation.setEasingFunction(easingFunction);
  49535. return animation;
  49536. };
  49537. /**
  49538. * Create and start an animation on a node
  49539. * @param name defines the name of the global animation that will be run on all nodes
  49540. * @param node defines the root node where the animation will take place
  49541. * @param targetProperty defines property to animate
  49542. * @param framePerSecond defines the number of frame per second yo use
  49543. * @param totalFrame defines the number of frames in total
  49544. * @param from defines the initial value
  49545. * @param to defines the final value
  49546. * @param loopMode defines which loop mode you want to use (off by default)
  49547. * @param easingFunction defines the easing function to use (linear by default)
  49548. * @param onAnimationEnd defines the callback to call when animation end
  49549. * @returns the animatable created for this animation
  49550. */
  49551. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49552. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49553. if (!animation) {
  49554. return null;
  49555. }
  49556. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49557. };
  49558. /**
  49559. * Create and start an animation on a node and its descendants
  49560. * @param name defines the name of the global animation that will be run on all nodes
  49561. * @param node defines the root node where the animation will take place
  49562. * @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
  49563. * @param targetProperty defines property to animate
  49564. * @param framePerSecond defines the number of frame per second to use
  49565. * @param totalFrame defines the number of frames in total
  49566. * @param from defines the initial value
  49567. * @param to defines the final value
  49568. * @param loopMode defines which loop mode you want to use (off by default)
  49569. * @param easingFunction defines the easing function to use (linear by default)
  49570. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49571. * @returns the list of animatables created for all nodes
  49572. * @example https://www.babylonjs-playground.com/#MH0VLI
  49573. */
  49574. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49575. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49576. if (!animation) {
  49577. return null;
  49578. }
  49579. var scene = node.getScene();
  49580. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49581. };
  49582. /**
  49583. * Creates a new animation, merges it with the existing animations and starts it
  49584. * @param name Name of the animation
  49585. * @param node Node which contains the scene that begins the animations
  49586. * @param targetProperty Specifies which property to animate
  49587. * @param framePerSecond The frames per second of the animation
  49588. * @param totalFrame The total number of frames
  49589. * @param from The frame at the beginning of the animation
  49590. * @param to The frame at the end of the animation
  49591. * @param loopMode Specifies the loop mode of the animation
  49592. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49593. * @param onAnimationEnd Callback to run once the animation is complete
  49594. * @returns Nullable animation
  49595. */
  49596. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49597. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49598. if (!animation) {
  49599. return null;
  49600. }
  49601. node.animations.push(animation);
  49602. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49603. };
  49604. /**
  49605. * Transition property of an host to the target Value
  49606. * @param property The property to transition
  49607. * @param targetValue The target Value of the property
  49608. * @param host The object where the property to animate belongs
  49609. * @param scene Scene used to run the animation
  49610. * @param frameRate Framerate (in frame/s) to use
  49611. * @param transition The transition type we want to use
  49612. * @param duration The duration of the animation, in milliseconds
  49613. * @param onAnimationEnd Callback trigger at the end of the animation
  49614. * @returns Nullable animation
  49615. */
  49616. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49617. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49618. if (duration <= 0) {
  49619. host[property] = targetValue;
  49620. if (onAnimationEnd) {
  49621. onAnimationEnd();
  49622. }
  49623. return null;
  49624. }
  49625. var endFrame = frameRate * (duration / 1000);
  49626. transition.setKeys([{
  49627. frame: 0,
  49628. value: host[property].clone ? host[property].clone() : host[property]
  49629. },
  49630. {
  49631. frame: endFrame,
  49632. value: targetValue
  49633. }]);
  49634. if (!host.animations) {
  49635. host.animations = [];
  49636. }
  49637. host.animations.push(transition);
  49638. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49639. animation.onAnimationEnd = onAnimationEnd;
  49640. return animation;
  49641. };
  49642. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49643. /**
  49644. * Return the array of runtime animations currently using this animation
  49645. */
  49646. get: function () {
  49647. return this._runtimeAnimations;
  49648. },
  49649. enumerable: true,
  49650. configurable: true
  49651. });
  49652. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49653. /**
  49654. * Specifies if any of the runtime animations are currently running
  49655. */
  49656. get: function () {
  49657. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49658. var runtimeAnimation = _a[_i];
  49659. if (!runtimeAnimation.isStopped) {
  49660. return true;
  49661. }
  49662. }
  49663. return false;
  49664. },
  49665. enumerable: true,
  49666. configurable: true
  49667. });
  49668. // Methods
  49669. /**
  49670. * Converts the animation to a string
  49671. * @param fullDetails support for multiple levels of logging within scene loading
  49672. * @returns String form of the animation
  49673. */
  49674. Animation.prototype.toString = function (fullDetails) {
  49675. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49676. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49677. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49678. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49679. if (fullDetails) {
  49680. ret += ", Ranges: {";
  49681. var first = true;
  49682. for (var name in this._ranges) {
  49683. if (first) {
  49684. ret += ", ";
  49685. first = false;
  49686. }
  49687. ret += name;
  49688. }
  49689. ret += "}";
  49690. }
  49691. return ret;
  49692. };
  49693. /**
  49694. * Add an event to this animation
  49695. * @param event Event to add
  49696. */
  49697. Animation.prototype.addEvent = function (event) {
  49698. this._events.push(event);
  49699. };
  49700. /**
  49701. * Remove all events found at the given frame
  49702. * @param frame The frame to remove events from
  49703. */
  49704. Animation.prototype.removeEvents = function (frame) {
  49705. for (var index = 0; index < this._events.length; index++) {
  49706. if (this._events[index].frame === frame) {
  49707. this._events.splice(index, 1);
  49708. index--;
  49709. }
  49710. }
  49711. };
  49712. /**
  49713. * Retrieves all the events from the animation
  49714. * @returns Events from the animation
  49715. */
  49716. Animation.prototype.getEvents = function () {
  49717. return this._events;
  49718. };
  49719. /**
  49720. * Creates an animation range
  49721. * @param name Name of the animation range
  49722. * @param from Starting frame of the animation range
  49723. * @param to Ending frame of the animation
  49724. */
  49725. Animation.prototype.createRange = function (name, from, to) {
  49726. // check name not already in use; could happen for bones after serialized
  49727. if (!this._ranges[name]) {
  49728. this._ranges[name] = new AnimationRange(name, from, to);
  49729. }
  49730. };
  49731. /**
  49732. * Deletes an animation range by name
  49733. * @param name Name of the animation range to delete
  49734. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49735. */
  49736. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49737. if (deleteFrames === void 0) { deleteFrames = true; }
  49738. var range = this._ranges[name];
  49739. if (!range) {
  49740. return;
  49741. }
  49742. if (deleteFrames) {
  49743. var from = range.from;
  49744. var to = range.to;
  49745. // this loop MUST go high to low for multiple splices to work
  49746. for (var key = this._keys.length - 1; key >= 0; key--) {
  49747. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49748. this._keys.splice(key, 1);
  49749. }
  49750. }
  49751. }
  49752. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49753. };
  49754. /**
  49755. * Gets the animation range by name, or null if not defined
  49756. * @param name Name of the animation range
  49757. * @returns Nullable animation range
  49758. */
  49759. Animation.prototype.getRange = function (name) {
  49760. return this._ranges[name];
  49761. };
  49762. /**
  49763. * Gets the key frames from the animation
  49764. * @returns The key frames of the animation
  49765. */
  49766. Animation.prototype.getKeys = function () {
  49767. return this._keys;
  49768. };
  49769. /**
  49770. * Gets the highest frame rate of the animation
  49771. * @returns Highest frame rate of the animation
  49772. */
  49773. Animation.prototype.getHighestFrame = function () {
  49774. var ret = 0;
  49775. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49776. if (ret < this._keys[key].frame) {
  49777. ret = this._keys[key].frame;
  49778. }
  49779. }
  49780. return ret;
  49781. };
  49782. /**
  49783. * Gets the easing function of the animation
  49784. * @returns Easing function of the animation
  49785. */
  49786. Animation.prototype.getEasingFunction = function () {
  49787. return this._easingFunction;
  49788. };
  49789. /**
  49790. * Sets the easing function of the animation
  49791. * @param easingFunction A custom mathematical formula for animation
  49792. */
  49793. Animation.prototype.setEasingFunction = function (easingFunction) {
  49794. this._easingFunction = easingFunction;
  49795. };
  49796. /**
  49797. * Interpolates a scalar linearly
  49798. * @param startValue Start value of the animation curve
  49799. * @param endValue End value of the animation curve
  49800. * @param gradient Scalar amount to interpolate
  49801. * @returns Interpolated scalar value
  49802. */
  49803. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49804. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49805. };
  49806. /**
  49807. * Interpolates a scalar cubically
  49808. * @param startValue Start value of the animation curve
  49809. * @param outTangent End tangent of the animation
  49810. * @param endValue End value of the animation curve
  49811. * @param inTangent Start tangent of the animation curve
  49812. * @param gradient Scalar amount to interpolate
  49813. * @returns Interpolated scalar value
  49814. */
  49815. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49816. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49817. };
  49818. /**
  49819. * Interpolates a quaternion using a spherical linear interpolation
  49820. * @param startValue Start value of the animation curve
  49821. * @param endValue End value of the animation curve
  49822. * @param gradient Scalar amount to interpolate
  49823. * @returns Interpolated quaternion value
  49824. */
  49825. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49826. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49827. };
  49828. /**
  49829. * Interpolates a quaternion cubically
  49830. * @param startValue Start value of the animation curve
  49831. * @param outTangent End tangent of the animation curve
  49832. * @param endValue End value of the animation curve
  49833. * @param inTangent Start tangent of the animation curve
  49834. * @param gradient Scalar amount to interpolate
  49835. * @returns Interpolated quaternion value
  49836. */
  49837. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49838. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49839. };
  49840. /**
  49841. * Interpolates a Vector3 linearl
  49842. * @param startValue Start value of the animation curve
  49843. * @param endValue End value of the animation curve
  49844. * @param gradient Scalar amount to interpolate
  49845. * @returns Interpolated scalar value
  49846. */
  49847. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49848. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49849. };
  49850. /**
  49851. * Interpolates a Vector3 cubically
  49852. * @param startValue Start value of the animation curve
  49853. * @param outTangent End tangent of the animation
  49854. * @param endValue End value of the animation curve
  49855. * @param inTangent Start tangent of the animation curve
  49856. * @param gradient Scalar amount to interpolate
  49857. * @returns InterpolatedVector3 value
  49858. */
  49859. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49860. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49861. };
  49862. /**
  49863. * Interpolates a Vector2 linearly
  49864. * @param startValue Start value of the animation curve
  49865. * @param endValue End value of the animation curve
  49866. * @param gradient Scalar amount to interpolate
  49867. * @returns Interpolated Vector2 value
  49868. */
  49869. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49870. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49871. };
  49872. /**
  49873. * Interpolates a Vector2 cubically
  49874. * @param startValue Start value of the animation curve
  49875. * @param outTangent End tangent of the animation
  49876. * @param endValue End value of the animation curve
  49877. * @param inTangent Start tangent of the animation curve
  49878. * @param gradient Scalar amount to interpolate
  49879. * @returns Interpolated Vector2 value
  49880. */
  49881. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49882. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49883. };
  49884. /**
  49885. * Interpolates a size linearly
  49886. * @param startValue Start value of the animation curve
  49887. * @param endValue End value of the animation curve
  49888. * @param gradient Scalar amount to interpolate
  49889. * @returns Interpolated Size value
  49890. */
  49891. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49892. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49893. };
  49894. /**
  49895. * Interpolates a Color3 linearly
  49896. * @param startValue Start value of the animation curve
  49897. * @param endValue End value of the animation curve
  49898. * @param gradient Scalar amount to interpolate
  49899. * @returns Interpolated Color3 value
  49900. */
  49901. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49902. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49903. };
  49904. /**
  49905. * @hidden Internal use only
  49906. */
  49907. Animation.prototype._getKeyValue = function (value) {
  49908. if (typeof value === "function") {
  49909. return value();
  49910. }
  49911. return value;
  49912. };
  49913. /**
  49914. * @hidden Internal use only
  49915. */
  49916. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49917. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49918. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49919. }
  49920. var keys = this.getKeys();
  49921. // Try to get a hash to find the right key
  49922. 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));
  49923. if (keys[startKeyIndex].frame >= currentFrame) {
  49924. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49925. startKeyIndex--;
  49926. }
  49927. }
  49928. for (var key = startKeyIndex; key < keys.length; key++) {
  49929. var endKey = keys[key + 1];
  49930. if (endKey.frame >= currentFrame) {
  49931. var startKey = keys[key];
  49932. var startValue = this._getKeyValue(startKey.value);
  49933. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49934. return startValue;
  49935. }
  49936. var endValue = this._getKeyValue(endKey.value);
  49937. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49938. var frameDelta = endKey.frame - startKey.frame;
  49939. // gradient : percent of currentFrame between the frame inf and the frame sup
  49940. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49941. // check for easingFunction and correction of gradient
  49942. var easingFunction = this.getEasingFunction();
  49943. if (easingFunction != null) {
  49944. gradient = easingFunction.ease(gradient);
  49945. }
  49946. switch (this.dataType) {
  49947. // Float
  49948. case Animation.ANIMATIONTYPE_FLOAT:
  49949. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49950. switch (loopMode) {
  49951. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49952. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49953. return floatValue;
  49954. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49955. return offsetValue * repeatCount + floatValue;
  49956. }
  49957. break;
  49958. // Quaternion
  49959. case Animation.ANIMATIONTYPE_QUATERNION:
  49960. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49961. switch (loopMode) {
  49962. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49963. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49964. return quatValue;
  49965. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49966. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49967. }
  49968. return quatValue;
  49969. // Vector3
  49970. case Animation.ANIMATIONTYPE_VECTOR3:
  49971. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49972. switch (loopMode) {
  49973. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49974. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49975. return vec3Value;
  49976. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49977. return vec3Value.add(offsetValue.scale(repeatCount));
  49978. }
  49979. // Vector2
  49980. case Animation.ANIMATIONTYPE_VECTOR2:
  49981. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49982. switch (loopMode) {
  49983. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49984. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49985. return vec2Value;
  49986. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49987. return vec2Value.add(offsetValue.scale(repeatCount));
  49988. }
  49989. // Size
  49990. case Animation.ANIMATIONTYPE_SIZE:
  49991. switch (loopMode) {
  49992. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49993. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49994. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49995. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49996. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49997. }
  49998. // Color3
  49999. case Animation.ANIMATIONTYPE_COLOR3:
  50000. switch (loopMode) {
  50001. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50002. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50003. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50004. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50005. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50006. }
  50007. // Matrix
  50008. case Animation.ANIMATIONTYPE_MATRIX:
  50009. switch (loopMode) {
  50010. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50011. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50012. if (Animation.AllowMatricesInterpolation) {
  50013. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50014. }
  50015. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50016. return startValue;
  50017. }
  50018. default:
  50019. break;
  50020. }
  50021. break;
  50022. }
  50023. }
  50024. return this._getKeyValue(keys[keys.length - 1].value);
  50025. };
  50026. /**
  50027. * Defines the function to use to interpolate matrices
  50028. * @param startValue defines the start matrix
  50029. * @param endValue defines the end matrix
  50030. * @param gradient defines the gradient between both matrices
  50031. * @param result defines an optional target matrix where to store the interpolation
  50032. * @returns the interpolated matrix
  50033. */
  50034. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50035. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50036. if (result) {
  50037. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50038. return result;
  50039. }
  50040. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50041. }
  50042. if (result) {
  50043. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50044. return result;
  50045. }
  50046. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50047. };
  50048. /**
  50049. * Makes a copy of the animation
  50050. * @returns Cloned animation
  50051. */
  50052. Animation.prototype.clone = function () {
  50053. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50054. clone.enableBlending = this.enableBlending;
  50055. clone.blendingSpeed = this.blendingSpeed;
  50056. if (this._keys) {
  50057. clone.setKeys(this._keys);
  50058. }
  50059. if (this._ranges) {
  50060. clone._ranges = {};
  50061. for (var name in this._ranges) {
  50062. var range = this._ranges[name];
  50063. if (!range) {
  50064. continue;
  50065. }
  50066. clone._ranges[name] = range.clone();
  50067. }
  50068. }
  50069. return clone;
  50070. };
  50071. /**
  50072. * Sets the key frames of the animation
  50073. * @param values The animation key frames to set
  50074. */
  50075. Animation.prototype.setKeys = function (values) {
  50076. this._keys = values.slice(0);
  50077. };
  50078. /**
  50079. * Serializes the animation to an object
  50080. * @returns Serialized object
  50081. */
  50082. Animation.prototype.serialize = function () {
  50083. var serializationObject = {};
  50084. serializationObject.name = this.name;
  50085. serializationObject.property = this.targetProperty;
  50086. serializationObject.framePerSecond = this.framePerSecond;
  50087. serializationObject.dataType = this.dataType;
  50088. serializationObject.loopBehavior = this.loopMode;
  50089. serializationObject.enableBlending = this.enableBlending;
  50090. serializationObject.blendingSpeed = this.blendingSpeed;
  50091. var dataType = this.dataType;
  50092. serializationObject.keys = [];
  50093. var keys = this.getKeys();
  50094. for (var index = 0; index < keys.length; index++) {
  50095. var animationKey = keys[index];
  50096. var key = {};
  50097. key.frame = animationKey.frame;
  50098. switch (dataType) {
  50099. case Animation.ANIMATIONTYPE_FLOAT:
  50100. key.values = [animationKey.value];
  50101. break;
  50102. case Animation.ANIMATIONTYPE_QUATERNION:
  50103. case Animation.ANIMATIONTYPE_MATRIX:
  50104. case Animation.ANIMATIONTYPE_VECTOR3:
  50105. case Animation.ANIMATIONTYPE_COLOR3:
  50106. key.values = animationKey.value.asArray();
  50107. break;
  50108. }
  50109. serializationObject.keys.push(key);
  50110. }
  50111. serializationObject.ranges = [];
  50112. for (var name in this._ranges) {
  50113. var source = this._ranges[name];
  50114. if (!source) {
  50115. continue;
  50116. }
  50117. var range = {};
  50118. range.name = name;
  50119. range.from = source.from;
  50120. range.to = source.to;
  50121. serializationObject.ranges.push(range);
  50122. }
  50123. return serializationObject;
  50124. };
  50125. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50126. /**
  50127. * Get the float animation type
  50128. */
  50129. get: function () {
  50130. return Animation._ANIMATIONTYPE_FLOAT;
  50131. },
  50132. enumerable: true,
  50133. configurable: true
  50134. });
  50135. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50136. /**
  50137. * Get the Vector3 animation type
  50138. */
  50139. get: function () {
  50140. return Animation._ANIMATIONTYPE_VECTOR3;
  50141. },
  50142. enumerable: true,
  50143. configurable: true
  50144. });
  50145. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50146. /**
  50147. * Get the Vectpr2 animation type
  50148. */
  50149. get: function () {
  50150. return Animation._ANIMATIONTYPE_VECTOR2;
  50151. },
  50152. enumerable: true,
  50153. configurable: true
  50154. });
  50155. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50156. /**
  50157. * Get the Size animation type
  50158. */
  50159. get: function () {
  50160. return Animation._ANIMATIONTYPE_SIZE;
  50161. },
  50162. enumerable: true,
  50163. configurable: true
  50164. });
  50165. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50166. /**
  50167. * Get the Quaternion animation type
  50168. */
  50169. get: function () {
  50170. return Animation._ANIMATIONTYPE_QUATERNION;
  50171. },
  50172. enumerable: true,
  50173. configurable: true
  50174. });
  50175. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50176. /**
  50177. * Get the Matrix animation type
  50178. */
  50179. get: function () {
  50180. return Animation._ANIMATIONTYPE_MATRIX;
  50181. },
  50182. enumerable: true,
  50183. configurable: true
  50184. });
  50185. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50186. /**
  50187. * Get the Color3 animation type
  50188. */
  50189. get: function () {
  50190. return Animation._ANIMATIONTYPE_COLOR3;
  50191. },
  50192. enumerable: true,
  50193. configurable: true
  50194. });
  50195. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50196. /**
  50197. * Get the Relative Loop Mode
  50198. */
  50199. get: function () {
  50200. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50206. /**
  50207. * Get the Cycle Loop Mode
  50208. */
  50209. get: function () {
  50210. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50211. },
  50212. enumerable: true,
  50213. configurable: true
  50214. });
  50215. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50216. /**
  50217. * Get the Constant Loop Mode
  50218. */
  50219. get: function () {
  50220. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50221. },
  50222. enumerable: true,
  50223. configurable: true
  50224. });
  50225. /** @hidden */
  50226. Animation._UniversalLerp = function (left, right, amount) {
  50227. var constructor = left.constructor;
  50228. if (constructor.Lerp) { // Lerp supported
  50229. return constructor.Lerp(left, right, amount);
  50230. }
  50231. else if (constructor.Slerp) { // Slerp supported
  50232. return constructor.Slerp(left, right, amount);
  50233. }
  50234. else if (left.toFixed) { // Number
  50235. return left * (1.0 - amount) + amount * right;
  50236. }
  50237. else { // Blending not supported
  50238. return right;
  50239. }
  50240. };
  50241. /**
  50242. * Parses an animation object and creates an animation
  50243. * @param parsedAnimation Parsed animation object
  50244. * @returns Animation object
  50245. */
  50246. Animation.Parse = function (parsedAnimation) {
  50247. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50248. var dataType = parsedAnimation.dataType;
  50249. var keys = [];
  50250. var data;
  50251. var index;
  50252. if (parsedAnimation.enableBlending) {
  50253. animation.enableBlending = parsedAnimation.enableBlending;
  50254. }
  50255. if (parsedAnimation.blendingSpeed) {
  50256. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50257. }
  50258. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50259. var key = parsedAnimation.keys[index];
  50260. var inTangent;
  50261. var outTangent;
  50262. switch (dataType) {
  50263. case Animation.ANIMATIONTYPE_FLOAT:
  50264. data = key.values[0];
  50265. if (key.values.length >= 1) {
  50266. inTangent = key.values[1];
  50267. }
  50268. if (key.values.length >= 2) {
  50269. outTangent = key.values[2];
  50270. }
  50271. break;
  50272. case Animation.ANIMATIONTYPE_QUATERNION:
  50273. data = BABYLON.Quaternion.FromArray(key.values);
  50274. if (key.values.length >= 8) {
  50275. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50276. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50277. inTangent = _inTangent;
  50278. }
  50279. }
  50280. if (key.values.length >= 12) {
  50281. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50282. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50283. outTangent = _outTangent;
  50284. }
  50285. }
  50286. break;
  50287. case Animation.ANIMATIONTYPE_MATRIX:
  50288. data = BABYLON.Matrix.FromArray(key.values);
  50289. break;
  50290. case Animation.ANIMATIONTYPE_COLOR3:
  50291. data = BABYLON.Color3.FromArray(key.values);
  50292. break;
  50293. case Animation.ANIMATIONTYPE_VECTOR3:
  50294. default:
  50295. data = BABYLON.Vector3.FromArray(key.values);
  50296. break;
  50297. }
  50298. var keyData = {};
  50299. keyData.frame = key.frame;
  50300. keyData.value = data;
  50301. if (inTangent != undefined) {
  50302. keyData.inTangent = inTangent;
  50303. }
  50304. if (outTangent != undefined) {
  50305. keyData.outTangent = outTangent;
  50306. }
  50307. keys.push(keyData);
  50308. }
  50309. animation.setKeys(keys);
  50310. if (parsedAnimation.ranges) {
  50311. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50312. data = parsedAnimation.ranges[index];
  50313. animation.createRange(data.name, data.from, data.to);
  50314. }
  50315. }
  50316. return animation;
  50317. };
  50318. /**
  50319. * Appends the serialized animations from the source animations
  50320. * @param source Source containing the animations
  50321. * @param destination Target to store the animations
  50322. */
  50323. Animation.AppendSerializedAnimations = function (source, destination) {
  50324. if (source.animations) {
  50325. destination.animations = [];
  50326. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50327. var animation = source.animations[animationIndex];
  50328. destination.animations.push(animation.serialize());
  50329. }
  50330. }
  50331. };
  50332. /**
  50333. * Use matrix interpolation instead of using direct key value when animating matrices
  50334. */
  50335. Animation.AllowMatricesInterpolation = false;
  50336. /**
  50337. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50338. */
  50339. Animation.AllowMatrixDecomposeForInterpolation = true;
  50340. // Statics
  50341. /**
  50342. * Float animation type
  50343. */
  50344. Animation._ANIMATIONTYPE_FLOAT = 0;
  50345. /**
  50346. * Vector3 animation type
  50347. */
  50348. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50349. /**
  50350. * Quaternion animation type
  50351. */
  50352. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50353. /**
  50354. * Matrix animation type
  50355. */
  50356. Animation._ANIMATIONTYPE_MATRIX = 3;
  50357. /**
  50358. * Color3 animation type
  50359. */
  50360. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50361. /**
  50362. * Vector2 animation type
  50363. */
  50364. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50365. /**
  50366. * Size animation type
  50367. */
  50368. Animation._ANIMATIONTYPE_SIZE = 6;
  50369. /**
  50370. * Relative Loop Mode
  50371. */
  50372. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50373. /**
  50374. * Cycle Loop Mode
  50375. */
  50376. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50377. /**
  50378. * Constant Loop Mode
  50379. */
  50380. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50381. return Animation;
  50382. }());
  50383. BABYLON.Animation = Animation;
  50384. })(BABYLON || (BABYLON = {}));
  50385. //# sourceMappingURL=babylon.animation.js.map
  50386. var BABYLON;
  50387. (function (BABYLON) {
  50388. /**
  50389. * This class defines the direct association between an animation and a target
  50390. */
  50391. var TargetedAnimation = /** @class */ (function () {
  50392. function TargetedAnimation() {
  50393. }
  50394. return TargetedAnimation;
  50395. }());
  50396. BABYLON.TargetedAnimation = TargetedAnimation;
  50397. /**
  50398. * Use this class to create coordinated animations on multiple targets
  50399. */
  50400. var AnimationGroup = /** @class */ (function () {
  50401. function AnimationGroup(name, scene) {
  50402. if (scene === void 0) { scene = null; }
  50403. this.name = name;
  50404. this._targetedAnimations = new Array();
  50405. this._animatables = new Array();
  50406. this._from = Number.MAX_VALUE;
  50407. this._to = -Number.MAX_VALUE;
  50408. this._speedRatio = 1;
  50409. this.onAnimationEndObservable = new BABYLON.Observable();
  50410. /**
  50411. * This observable will notify when all animations have ended.
  50412. */
  50413. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50414. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50415. this._scene.animationGroups.push(this);
  50416. }
  50417. Object.defineProperty(AnimationGroup.prototype, "from", {
  50418. /**
  50419. * Gets the first frame
  50420. */
  50421. get: function () {
  50422. return this._from;
  50423. },
  50424. enumerable: true,
  50425. configurable: true
  50426. });
  50427. Object.defineProperty(AnimationGroup.prototype, "to", {
  50428. /**
  50429. * Gets the last frame
  50430. */
  50431. get: function () {
  50432. return this._to;
  50433. },
  50434. enumerable: true,
  50435. configurable: true
  50436. });
  50437. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50438. /**
  50439. * Define if the animations are started
  50440. */
  50441. get: function () {
  50442. return this._isStarted;
  50443. },
  50444. enumerable: true,
  50445. configurable: true
  50446. });
  50447. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50448. /**
  50449. * Gets or sets the speed ratio to use for all animations
  50450. */
  50451. get: function () {
  50452. return this._speedRatio;
  50453. },
  50454. /**
  50455. * Gets or sets the speed ratio to use for all animations
  50456. */
  50457. set: function (value) {
  50458. if (this._speedRatio === value) {
  50459. return;
  50460. }
  50461. this._speedRatio = value;
  50462. for (var index = 0; index < this._animatables.length; index++) {
  50463. var animatable = this._animatables[index];
  50464. animatable.speedRatio = this._speedRatio;
  50465. }
  50466. },
  50467. enumerable: true,
  50468. configurable: true
  50469. });
  50470. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50471. /**
  50472. * Gets the targeted animations for this animation group
  50473. */
  50474. get: function () {
  50475. return this._targetedAnimations;
  50476. },
  50477. enumerable: true,
  50478. configurable: true
  50479. });
  50480. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50481. /**
  50482. * returning the list of animatables controlled by this animation group.
  50483. */
  50484. get: function () {
  50485. return this._animatables;
  50486. },
  50487. enumerable: true,
  50488. configurable: true
  50489. });
  50490. /**
  50491. * Add an animation (with its target) in the group
  50492. * @param animation defines the animation we want to add
  50493. * @param target defines the target of the animation
  50494. * @returns the {BABYLON.TargetedAnimation} object
  50495. */
  50496. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50497. var targetedAnimation = {
  50498. animation: animation,
  50499. target: target
  50500. };
  50501. var keys = animation.getKeys();
  50502. if (this._from > keys[0].frame) {
  50503. this._from = keys[0].frame;
  50504. }
  50505. if (this._to < keys[keys.length - 1].frame) {
  50506. this._to = keys[keys.length - 1].frame;
  50507. }
  50508. this._targetedAnimations.push(targetedAnimation);
  50509. return targetedAnimation;
  50510. };
  50511. /**
  50512. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50513. * It can add constant keys at begin or end
  50514. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50515. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50516. */
  50517. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50518. if (beginFrame === void 0) { beginFrame = null; }
  50519. if (endFrame === void 0) { endFrame = null; }
  50520. if (beginFrame == null)
  50521. beginFrame = this._from;
  50522. if (endFrame == null)
  50523. endFrame = this._to;
  50524. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50525. var targetedAnimation = this._targetedAnimations[index];
  50526. var keys = targetedAnimation.animation.getKeys();
  50527. var startKey = keys[0];
  50528. var endKey = keys[keys.length - 1];
  50529. if (startKey.frame > beginFrame) {
  50530. var newKey = {
  50531. frame: beginFrame,
  50532. value: startKey.value,
  50533. inTangent: startKey.inTangent,
  50534. outTangent: startKey.outTangent,
  50535. interpolation: startKey.interpolation
  50536. };
  50537. keys.splice(0, 0, newKey);
  50538. }
  50539. if (endKey.frame < endFrame) {
  50540. var newKey = {
  50541. frame: endFrame,
  50542. value: endKey.value,
  50543. inTangent: endKey.outTangent,
  50544. outTangent: endKey.outTangent,
  50545. interpolation: endKey.interpolation
  50546. };
  50547. keys.push(newKey);
  50548. }
  50549. }
  50550. this._from = beginFrame;
  50551. this._to = endFrame;
  50552. return this;
  50553. };
  50554. /**
  50555. * Start all animations on given targets
  50556. * @param loop defines if animations must loop
  50557. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50558. * @param from defines the from key (optional)
  50559. * @param to defines the to key (optional)
  50560. * @returns the current animation group
  50561. */
  50562. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50563. var _this = this;
  50564. if (loop === void 0) { loop = false; }
  50565. if (speedRatio === void 0) { speedRatio = 1; }
  50566. if (this._isStarted || this._targetedAnimations.length === 0) {
  50567. return this;
  50568. }
  50569. var _loop_1 = function (targetedAnimation) {
  50570. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50571. animatable.onAnimationEnd = function () {
  50572. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50573. _this._checkAnimationGroupEnded(animatable);
  50574. };
  50575. this_1._animatables.push(animatable);
  50576. };
  50577. var this_1 = this;
  50578. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50579. var targetedAnimation = _a[_i];
  50580. _loop_1(targetedAnimation);
  50581. }
  50582. this._speedRatio = speedRatio;
  50583. this._isStarted = true;
  50584. return this;
  50585. };
  50586. /**
  50587. * Pause all animations
  50588. */
  50589. AnimationGroup.prototype.pause = function () {
  50590. if (!this._isStarted) {
  50591. return this;
  50592. }
  50593. for (var index = 0; index < this._animatables.length; index++) {
  50594. var animatable = this._animatables[index];
  50595. animatable.pause();
  50596. }
  50597. return this;
  50598. };
  50599. /**
  50600. * Play all animations to initial state
  50601. * This function will start() the animations if they were not started or will restart() them if they were paused
  50602. * @param loop defines if animations must loop
  50603. */
  50604. AnimationGroup.prototype.play = function (loop) {
  50605. // only if all animatables are ready and exist
  50606. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50607. if (loop !== undefined) {
  50608. for (var index = 0; index < this._animatables.length; index++) {
  50609. var animatable = this._animatables[index];
  50610. animatable.loopAnimation = loop;
  50611. }
  50612. }
  50613. this.restart();
  50614. }
  50615. else {
  50616. this.stop();
  50617. this.start(loop, this._speedRatio);
  50618. }
  50619. return this;
  50620. };
  50621. /**
  50622. * Reset all animations to initial state
  50623. */
  50624. AnimationGroup.prototype.reset = function () {
  50625. if (!this._isStarted) {
  50626. return this;
  50627. }
  50628. for (var index = 0; index < this._animatables.length; index++) {
  50629. var animatable = this._animatables[index];
  50630. animatable.reset();
  50631. }
  50632. return this;
  50633. };
  50634. /**
  50635. * Restart animations from key 0
  50636. */
  50637. AnimationGroup.prototype.restart = function () {
  50638. if (!this._isStarted) {
  50639. return this;
  50640. }
  50641. for (var index = 0; index < this._animatables.length; index++) {
  50642. var animatable = this._animatables[index];
  50643. animatable.restart();
  50644. }
  50645. return this;
  50646. };
  50647. /**
  50648. * Stop all animations
  50649. */
  50650. AnimationGroup.prototype.stop = function () {
  50651. if (!this._isStarted) {
  50652. return this;
  50653. }
  50654. for (var index = 0; index < this._animatables.length; index++) {
  50655. var animatable = this._animatables[index];
  50656. animatable.stop();
  50657. }
  50658. this._isStarted = false;
  50659. return this;
  50660. };
  50661. /**
  50662. * Set animation weight for all animatables
  50663. * @param weight defines the weight to use
  50664. * @return the animationGroup
  50665. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50666. */
  50667. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50668. for (var index = 0; index < this._animatables.length; index++) {
  50669. var animatable = this._animatables[index];
  50670. animatable.weight = weight;
  50671. }
  50672. return this;
  50673. };
  50674. /**
  50675. * Synchronize and normalize all animatables with a source animatable
  50676. * @param root defines the root animatable to synchronize with
  50677. * @return the animationGroup
  50678. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50679. */
  50680. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50681. for (var index = 0; index < this._animatables.length; index++) {
  50682. var animatable = this._animatables[index];
  50683. animatable.syncWith(root);
  50684. }
  50685. return this;
  50686. };
  50687. /**
  50688. * Goes to a specific frame in this animation group
  50689. * @param frame the frame number to go to
  50690. * @return the animationGroup
  50691. */
  50692. AnimationGroup.prototype.goToFrame = function (frame) {
  50693. if (!this._isStarted) {
  50694. return this;
  50695. }
  50696. for (var index = 0; index < this._animatables.length; index++) {
  50697. var animatable = this._animatables[index];
  50698. animatable.goToFrame(frame);
  50699. }
  50700. return this;
  50701. };
  50702. /**
  50703. * Dispose all associated resources
  50704. */
  50705. AnimationGroup.prototype.dispose = function () {
  50706. this._targetedAnimations = [];
  50707. this._animatables = [];
  50708. var index = this._scene.animationGroups.indexOf(this);
  50709. if (index > -1) {
  50710. this._scene.animationGroups.splice(index, 1);
  50711. }
  50712. };
  50713. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50714. // animatable should be taken out of the array
  50715. var idx = this._animatables.indexOf(animatable);
  50716. if (idx > -1) {
  50717. this._animatables.splice(idx, 1);
  50718. }
  50719. // all animatables were removed? animation group ended!
  50720. if (this._animatables.length === 0) {
  50721. this._isStarted = false;
  50722. this.onAnimationGroupEndObservable.notifyObservers(this);
  50723. }
  50724. };
  50725. return AnimationGroup;
  50726. }());
  50727. BABYLON.AnimationGroup = AnimationGroup;
  50728. })(BABYLON || (BABYLON = {}));
  50729. //# sourceMappingURL=babylon.animationGroup.js.map
  50730. var BABYLON;
  50731. (function (BABYLON) {
  50732. /**
  50733. * Defines a runtime animation
  50734. */
  50735. var RuntimeAnimation = /** @class */ (function () {
  50736. /**
  50737. * Create a new RuntimeAnimation object
  50738. * @param target defines the target of the animation
  50739. * @param animation defines the source animation object
  50740. * @param scene defines the hosting scene
  50741. * @param host defines the initiating Animatable
  50742. */
  50743. function RuntimeAnimation(target, animation, scene, host) {
  50744. var _this = this;
  50745. this._events = new Array();
  50746. /**
  50747. * The current frame of the runtime animation
  50748. */
  50749. this._currentFrame = 0;
  50750. /**
  50751. * The original value of the runtime animation
  50752. */
  50753. this._originalValue = new Array();
  50754. /**
  50755. * The offsets cache of the runtime animation
  50756. */
  50757. this._offsetsCache = {};
  50758. /**
  50759. * The high limits cache of the runtime animation
  50760. */
  50761. this._highLimitsCache = {};
  50762. /**
  50763. * Specifies if the runtime animation has been stopped
  50764. */
  50765. this._stopped = false;
  50766. /**
  50767. * The blending factor of the runtime animation
  50768. */
  50769. this._blendingFactor = 0;
  50770. /**
  50771. * The target path of the runtime animation
  50772. */
  50773. this._targetPath = "";
  50774. /**
  50775. * The weight of the runtime animation
  50776. */
  50777. this._weight = 1.0;
  50778. /**
  50779. * The ratio offset of the runtime animation
  50780. */
  50781. this._ratioOffset = 0;
  50782. /**
  50783. * The previous delay of the runtime animation
  50784. */
  50785. this._previousDelay = 0;
  50786. /**
  50787. * The previous ratio of the runtime animation
  50788. */
  50789. this._previousRatio = 0;
  50790. this._animation = animation;
  50791. this._target = target;
  50792. this._scene = scene;
  50793. this._host = host;
  50794. animation._runtimeAnimations.push(this);
  50795. // Cloning events locally
  50796. var events = animation.getEvents();
  50797. if (events && events.length > 0) {
  50798. events.forEach(function (e) {
  50799. _this._events.push(e._clone());
  50800. });
  50801. }
  50802. }
  50803. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50804. /**
  50805. * Gets the current frame of the runtime animation
  50806. */
  50807. get: function () {
  50808. return this._currentFrame;
  50809. },
  50810. enumerable: true,
  50811. configurable: true
  50812. });
  50813. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50814. /**
  50815. * Gets the weight of the runtime animation
  50816. */
  50817. get: function () {
  50818. return this._weight;
  50819. },
  50820. enumerable: true,
  50821. configurable: true
  50822. });
  50823. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50824. /**
  50825. * Gets the current value of the runtime animation
  50826. */
  50827. get: function () {
  50828. return this._currentValue;
  50829. },
  50830. enumerable: true,
  50831. configurable: true
  50832. });
  50833. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50834. /**
  50835. * Gets the target path of the runtime animation
  50836. */
  50837. get: function () {
  50838. return this._targetPath;
  50839. },
  50840. enumerable: true,
  50841. configurable: true
  50842. });
  50843. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50844. /**
  50845. * Gets the actual target of the runtime animation
  50846. */
  50847. get: function () {
  50848. return this._activeTarget;
  50849. },
  50850. enumerable: true,
  50851. configurable: true
  50852. });
  50853. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50854. /**
  50855. * Gets the animation from the runtime animation
  50856. */
  50857. get: function () {
  50858. return this._animation;
  50859. },
  50860. enumerable: true,
  50861. configurable: true
  50862. });
  50863. /**
  50864. * Resets the runtime animation to the beginning
  50865. * @param restoreOriginal defines whether to restore the target property to the original value
  50866. */
  50867. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50868. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50869. if (restoreOriginal) {
  50870. if (this._target instanceof Array) {
  50871. var index = 0;
  50872. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50873. var target = _a[_i];
  50874. if (this._originalValue[index] !== undefined) {
  50875. this._setValue(target, this._originalValue[index], -1);
  50876. }
  50877. index++;
  50878. }
  50879. }
  50880. else {
  50881. if (this._originalValue[0] !== undefined) {
  50882. this._setValue(this._target, this._originalValue[0], -1);
  50883. }
  50884. }
  50885. }
  50886. this._offsetsCache = {};
  50887. this._highLimitsCache = {};
  50888. this._currentFrame = 0;
  50889. this._blendingFactor = 0;
  50890. this._originalValue = new Array();
  50891. // Events
  50892. for (var index = 0; index < this._events.length; index++) {
  50893. this._events[index].isDone = false;
  50894. }
  50895. };
  50896. /**
  50897. * Specifies if the runtime animation is stopped
  50898. * @returns Boolean specifying if the runtime animation is stopped
  50899. */
  50900. RuntimeAnimation.prototype.isStopped = function () {
  50901. return this._stopped;
  50902. };
  50903. /**
  50904. * Disposes of the runtime animation
  50905. */
  50906. RuntimeAnimation.prototype.dispose = function () {
  50907. var index = this._animation.runtimeAnimations.indexOf(this);
  50908. if (index > -1) {
  50909. this._animation.runtimeAnimations.splice(index, 1);
  50910. }
  50911. };
  50912. /**
  50913. * Interpolates the animation from the current frame
  50914. * @param currentFrame The frame to interpolate the animation to
  50915. * @param repeatCount The number of times that the animation should loop
  50916. * @param loopMode The type of looping mode to use
  50917. * @param offsetValue Animation offset value
  50918. * @param highLimitValue The high limit value
  50919. * @returns The interpolated value
  50920. */
  50921. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50922. this._currentFrame = currentFrame;
  50923. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50924. this._workValue = BABYLON.Matrix.Zero();
  50925. }
  50926. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50927. };
  50928. /**
  50929. * Apply the interpolated value to the target
  50930. * @param currentValue defines the value computed by the animation
  50931. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50932. */
  50933. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50934. if (weight === void 0) { weight = 1.0; }
  50935. if (this._target instanceof Array) {
  50936. var index = 0;
  50937. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50938. var target = _a[_i];
  50939. this._setValue(target, currentValue, weight, index);
  50940. index++;
  50941. }
  50942. }
  50943. else {
  50944. this._setValue(this._target, currentValue, weight);
  50945. }
  50946. };
  50947. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50948. if (targetIndex === void 0) { targetIndex = 0; }
  50949. // Set value
  50950. var path;
  50951. var destination;
  50952. var targetPropertyPath = this._animation.targetPropertyPath;
  50953. if (targetPropertyPath.length > 1) {
  50954. var property = target[targetPropertyPath[0]];
  50955. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50956. property = property[targetPropertyPath[index]];
  50957. }
  50958. path = targetPropertyPath[targetPropertyPath.length - 1];
  50959. destination = property;
  50960. }
  50961. else {
  50962. path = targetPropertyPath[0];
  50963. destination = target;
  50964. }
  50965. this._targetPath = path;
  50966. this._activeTarget = destination;
  50967. this._weight = weight;
  50968. if (this._originalValue[targetIndex] === undefined) {
  50969. var originalValue = void 0;
  50970. if (destination.getRestPose && path === "_matrix") { // For bones
  50971. originalValue = destination.getRestPose();
  50972. }
  50973. else {
  50974. originalValue = destination[path];
  50975. }
  50976. if (originalValue && originalValue.clone) {
  50977. this._originalValue[targetIndex] = originalValue.clone();
  50978. }
  50979. else {
  50980. this._originalValue[targetIndex] = originalValue;
  50981. }
  50982. }
  50983. // Blending
  50984. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50985. if (enableBlending && this._blendingFactor <= 1.0) {
  50986. if (!this._originalBlendValue) {
  50987. var originalValue = destination[path];
  50988. if (originalValue.clone) {
  50989. this._originalBlendValue = originalValue.clone();
  50990. }
  50991. else {
  50992. this._originalBlendValue = originalValue;
  50993. }
  50994. }
  50995. if (this._originalBlendValue.m) { // Matrix
  50996. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50997. if (this._currentValue) {
  50998. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50999. }
  51000. else {
  51001. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51002. }
  51003. }
  51004. else {
  51005. if (this._currentValue) {
  51006. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51007. }
  51008. else {
  51009. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51010. }
  51011. }
  51012. }
  51013. else {
  51014. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51015. }
  51016. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51017. this._blendingFactor += blendingSpeed;
  51018. }
  51019. else {
  51020. this._currentValue = currentValue;
  51021. }
  51022. if (weight !== -1.0) {
  51023. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51024. }
  51025. else {
  51026. destination[path] = this._currentValue;
  51027. }
  51028. if (target.markAsDirty) {
  51029. target.markAsDirty(this._animation.targetProperty);
  51030. }
  51031. };
  51032. /**
  51033. * Gets the loop pmode of the runtime animation
  51034. * @returns Loop Mode
  51035. */
  51036. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51037. if (this._target && this._target.animationPropertiesOverride) {
  51038. return this._target.animationPropertiesOverride.loopMode;
  51039. }
  51040. return this._animation.loopMode;
  51041. };
  51042. /**
  51043. * Move the current animation to a given frame
  51044. * @param frame defines the frame to move to
  51045. */
  51046. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51047. var keys = this._animation.getKeys();
  51048. if (frame < keys[0].frame) {
  51049. frame = keys[0].frame;
  51050. }
  51051. else if (frame > keys[keys.length - 1].frame) {
  51052. frame = keys[keys.length - 1].frame;
  51053. }
  51054. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51055. this.setValue(currentValue, -1);
  51056. };
  51057. /**
  51058. * @hidden Internal use only
  51059. */
  51060. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51061. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51062. this._ratioOffset = this._previousRatio - newRatio;
  51063. };
  51064. /**
  51065. * Execute the current animation
  51066. * @param delay defines the delay to add to the current frame
  51067. * @param from defines the lower bound of the animation range
  51068. * @param to defines the upper bound of the animation range
  51069. * @param loop defines if the current animation must loop
  51070. * @param speedRatio defines the current speed ratio
  51071. * @param weight defines the weight of the animation (default is -1 so no weight)
  51072. * @returns a boolean indicating if the animation has ended
  51073. */
  51074. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51075. if (weight === void 0) { weight = -1.0; }
  51076. var targetPropertyPath = this._animation.targetPropertyPath;
  51077. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51078. this._stopped = true;
  51079. return false;
  51080. }
  51081. var returnValue = true;
  51082. var keys = this._animation.getKeys();
  51083. // Adding a start key at frame 0 if missing
  51084. if (keys[0].frame !== 0) {
  51085. var newKey = { frame: 0, value: keys[0].value };
  51086. keys.splice(0, 0, newKey);
  51087. }
  51088. // Check limits
  51089. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51090. from = keys[0].frame;
  51091. }
  51092. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51093. to = keys[keys.length - 1].frame;
  51094. }
  51095. //to and from cannot be the same key
  51096. if (from === to) {
  51097. if (from > keys[0].frame) {
  51098. from--;
  51099. }
  51100. else if (to < keys[keys.length - 1].frame) {
  51101. to++;
  51102. }
  51103. }
  51104. // Compute ratio
  51105. var range = to - from;
  51106. var offsetValue;
  51107. // ratio represents the frame delta between from and to
  51108. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51109. var highLimitValue = 0;
  51110. this._previousDelay = delay;
  51111. this._previousRatio = ratio;
  51112. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51113. returnValue = false;
  51114. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51115. }
  51116. else {
  51117. // Get max value if required
  51118. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51119. var keyOffset = to.toString() + from.toString();
  51120. if (!this._offsetsCache[keyOffset]) {
  51121. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51122. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51123. switch (this._animation.dataType) {
  51124. // Float
  51125. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51126. this._offsetsCache[keyOffset] = toValue - fromValue;
  51127. break;
  51128. // Quaternion
  51129. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51130. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51131. break;
  51132. // Vector3
  51133. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51134. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51135. // Vector2
  51136. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51137. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51138. // Size
  51139. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51140. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51141. // Color3
  51142. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51143. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51144. default:
  51145. break;
  51146. }
  51147. this._highLimitsCache[keyOffset] = toValue;
  51148. }
  51149. highLimitValue = this._highLimitsCache[keyOffset];
  51150. offsetValue = this._offsetsCache[keyOffset];
  51151. }
  51152. }
  51153. if (offsetValue === undefined) {
  51154. switch (this._animation.dataType) {
  51155. // Float
  51156. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51157. offsetValue = 0;
  51158. break;
  51159. // Quaternion
  51160. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51161. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51162. break;
  51163. // Vector3
  51164. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51165. offsetValue = BABYLON.Vector3.Zero();
  51166. break;
  51167. // Vector2
  51168. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51169. offsetValue = BABYLON.Vector2.Zero();
  51170. break;
  51171. // Size
  51172. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51173. offsetValue = BABYLON.Size.Zero();
  51174. break;
  51175. // Color3
  51176. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51177. offsetValue = BABYLON.Color3.Black();
  51178. }
  51179. }
  51180. // Compute value
  51181. var repeatCount = (ratio / range) >> 0;
  51182. var currentFrame = returnValue ? from + ratio % range : to;
  51183. // Need to normalize?
  51184. if (this._host && this._host.syncRoot) {
  51185. var syncRoot = this._host.syncRoot;
  51186. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51187. currentFrame = from + (to - from) * hostNormalizedFrame;
  51188. }
  51189. // Reset events if looping
  51190. var events = this._events;
  51191. if (range > 0 && this.currentFrame > currentFrame ||
  51192. range < 0 && this.currentFrame < currentFrame) {
  51193. // Need to reset animation events
  51194. for (var index = 0; index < events.length; index++) {
  51195. if (!events[index].onlyOnce) {
  51196. // reset event, the animation is looping
  51197. events[index].isDone = false;
  51198. }
  51199. }
  51200. }
  51201. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51202. // Set value
  51203. this.setValue(currentValue, weight);
  51204. // Check events
  51205. for (var index = 0; index < events.length; index++) {
  51206. // Make sure current frame has passed event frame and that event frame is within the current range
  51207. // Also, handle both forward and reverse animations
  51208. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51209. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51210. var event = events[index];
  51211. if (!event.isDone) {
  51212. // If event should be done only once, remove it.
  51213. if (event.onlyOnce) {
  51214. events.splice(index, 1);
  51215. index--;
  51216. }
  51217. event.isDone = true;
  51218. event.action();
  51219. } // Don't do anything if the event has already be done.
  51220. }
  51221. }
  51222. if (!returnValue) {
  51223. this._stopped = true;
  51224. }
  51225. return returnValue;
  51226. };
  51227. return RuntimeAnimation;
  51228. }());
  51229. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51230. })(BABYLON || (BABYLON = {}));
  51231. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51232. var BABYLON;
  51233. (function (BABYLON) {
  51234. var Animatable = /** @class */ (function () {
  51235. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51236. if (fromFrame === void 0) { fromFrame = 0; }
  51237. if (toFrame === void 0) { toFrame = 100; }
  51238. if (loopAnimation === void 0) { loopAnimation = false; }
  51239. if (speedRatio === void 0) { speedRatio = 1.0; }
  51240. this.target = target;
  51241. this.fromFrame = fromFrame;
  51242. this.toFrame = toFrame;
  51243. this.loopAnimation = loopAnimation;
  51244. this.onAnimationEnd = onAnimationEnd;
  51245. this._localDelayOffset = null;
  51246. this._pausedDelay = null;
  51247. this._runtimeAnimations = new Array();
  51248. this._paused = false;
  51249. this._speedRatio = 1;
  51250. this._weight = -1.0;
  51251. this.animationStarted = false;
  51252. /**
  51253. * Observer raised when the animation ends
  51254. */
  51255. this.onAnimationEndObservable = new BABYLON.Observable();
  51256. this._scene = scene;
  51257. if (animations) {
  51258. this.appendAnimations(target, animations);
  51259. }
  51260. this._speedRatio = speedRatio;
  51261. scene._activeAnimatables.push(this);
  51262. }
  51263. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51264. /**
  51265. * Gets the root Animatable used to synchronize and normalize animations
  51266. */
  51267. get: function () {
  51268. return this._syncRoot;
  51269. },
  51270. enumerable: true,
  51271. configurable: true
  51272. });
  51273. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51274. /**
  51275. * Gets the current frame of the first RuntimeAnimation
  51276. * Used to synchronize Animatables
  51277. */
  51278. get: function () {
  51279. if (this._runtimeAnimations.length === 0) {
  51280. return 0;
  51281. }
  51282. return this._runtimeAnimations[0].currentFrame;
  51283. },
  51284. enumerable: true,
  51285. configurable: true
  51286. });
  51287. Object.defineProperty(Animatable.prototype, "weight", {
  51288. /**
  51289. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51290. */
  51291. get: function () {
  51292. return this._weight;
  51293. },
  51294. set: function (value) {
  51295. if (value === -1) { // -1 is ok and means no weight
  51296. this._weight = -1;
  51297. return;
  51298. }
  51299. // Else weight must be in [0, 1] range
  51300. this._weight = Math.min(Math.max(value, 0), 1.0);
  51301. },
  51302. enumerable: true,
  51303. configurable: true
  51304. });
  51305. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51306. /**
  51307. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51308. */
  51309. get: function () {
  51310. return this._speedRatio;
  51311. },
  51312. set: function (value) {
  51313. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51314. var animation = this._runtimeAnimations[index];
  51315. animation._prepareForSpeedRatioChange(value);
  51316. }
  51317. this._speedRatio = value;
  51318. },
  51319. enumerable: true,
  51320. configurable: true
  51321. });
  51322. // Methods
  51323. /**
  51324. * Synchronize and normalize current Animatable with a source Animatable
  51325. * This is useful when using animation weights and when animations are not of the same length
  51326. * @param root defines the root Animatable to synchronize with
  51327. * @returns the current Animatable
  51328. */
  51329. Animatable.prototype.syncWith = function (root) {
  51330. this._syncRoot = root;
  51331. if (root) {
  51332. // Make sure this animatable will animate after the root
  51333. var index = this._scene._activeAnimatables.indexOf(this);
  51334. if (index > -1) {
  51335. this._scene._activeAnimatables.splice(index, 1);
  51336. this._scene._activeAnimatables.push(this);
  51337. }
  51338. }
  51339. return this;
  51340. };
  51341. Animatable.prototype.getAnimations = function () {
  51342. return this._runtimeAnimations;
  51343. };
  51344. Animatable.prototype.appendAnimations = function (target, animations) {
  51345. for (var index = 0; index < animations.length; index++) {
  51346. var animation = animations[index];
  51347. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51348. }
  51349. };
  51350. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51351. var runtimeAnimations = this._runtimeAnimations;
  51352. for (var index = 0; index < runtimeAnimations.length; index++) {
  51353. if (runtimeAnimations[index].animation.targetProperty === property) {
  51354. return runtimeAnimations[index].animation;
  51355. }
  51356. }
  51357. return null;
  51358. };
  51359. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51360. var runtimeAnimations = this._runtimeAnimations;
  51361. for (var index = 0; index < runtimeAnimations.length; index++) {
  51362. if (runtimeAnimations[index].animation.targetProperty === property) {
  51363. return runtimeAnimations[index];
  51364. }
  51365. }
  51366. return null;
  51367. };
  51368. Animatable.prototype.reset = function () {
  51369. var runtimeAnimations = this._runtimeAnimations;
  51370. for (var index = 0; index < runtimeAnimations.length; index++) {
  51371. runtimeAnimations[index].reset(true);
  51372. }
  51373. this._localDelayOffset = null;
  51374. this._pausedDelay = null;
  51375. };
  51376. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51377. var runtimeAnimations = this._runtimeAnimations;
  51378. for (var index = 0; index < runtimeAnimations.length; index++) {
  51379. runtimeAnimations[index].animation.enableBlending = true;
  51380. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51381. }
  51382. };
  51383. Animatable.prototype.disableBlending = function () {
  51384. var runtimeAnimations = this._runtimeAnimations;
  51385. for (var index = 0; index < runtimeAnimations.length; index++) {
  51386. runtimeAnimations[index].animation.enableBlending = false;
  51387. }
  51388. };
  51389. Animatable.prototype.goToFrame = function (frame) {
  51390. var runtimeAnimations = this._runtimeAnimations;
  51391. if (runtimeAnimations[0]) {
  51392. var fps = runtimeAnimations[0].animation.framePerSecond;
  51393. var currentFrame = runtimeAnimations[0].currentFrame;
  51394. var adjustTime = frame - currentFrame;
  51395. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51396. if (this._localDelayOffset === null) {
  51397. this._localDelayOffset = 0;
  51398. }
  51399. this._localDelayOffset -= delay;
  51400. }
  51401. for (var index = 0; index < runtimeAnimations.length; index++) {
  51402. runtimeAnimations[index].goToFrame(frame);
  51403. }
  51404. };
  51405. Animatable.prototype.pause = function () {
  51406. if (this._paused) {
  51407. return;
  51408. }
  51409. this._paused = true;
  51410. };
  51411. Animatable.prototype.restart = function () {
  51412. this._paused = false;
  51413. };
  51414. Animatable.prototype._raiseOnAnimationEnd = function () {
  51415. if (this.onAnimationEnd) {
  51416. this.onAnimationEnd();
  51417. }
  51418. this.onAnimationEndObservable.notifyObservers(this);
  51419. };
  51420. Animatable.prototype.stop = function (animationName) {
  51421. if (animationName) {
  51422. var idx = this._scene._activeAnimatables.indexOf(this);
  51423. if (idx > -1) {
  51424. var runtimeAnimations = this._runtimeAnimations;
  51425. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51426. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51427. continue;
  51428. }
  51429. runtimeAnimations[index].dispose();
  51430. runtimeAnimations.splice(index, 1);
  51431. }
  51432. if (runtimeAnimations.length == 0) {
  51433. this._scene._activeAnimatables.splice(idx, 1);
  51434. this._raiseOnAnimationEnd();
  51435. }
  51436. }
  51437. }
  51438. else {
  51439. var index = this._scene._activeAnimatables.indexOf(this);
  51440. if (index > -1) {
  51441. this._scene._activeAnimatables.splice(index, 1);
  51442. var runtimeAnimations = this._runtimeAnimations;
  51443. for (var index = 0; index < runtimeAnimations.length; index++) {
  51444. runtimeAnimations[index].dispose();
  51445. }
  51446. this._raiseOnAnimationEnd();
  51447. }
  51448. }
  51449. };
  51450. /**
  51451. * Wait asynchronously for the animation to end
  51452. * @returns a promise which will be fullfilled when the animation ends
  51453. */
  51454. Animatable.prototype.waitAsync = function () {
  51455. var _this = this;
  51456. return new Promise(function (resolve, reject) {
  51457. _this.onAnimationEndObservable.add(function () {
  51458. resolve(_this);
  51459. }, undefined, undefined, _this, true);
  51460. });
  51461. };
  51462. /** @hidden */
  51463. Animatable.prototype._animate = function (delay) {
  51464. if (this._paused) {
  51465. this.animationStarted = false;
  51466. if (this._pausedDelay === null) {
  51467. this._pausedDelay = delay;
  51468. }
  51469. return true;
  51470. }
  51471. if (this._localDelayOffset === null) {
  51472. this._localDelayOffset = delay;
  51473. this._pausedDelay = null;
  51474. }
  51475. else if (this._pausedDelay !== null) {
  51476. this._localDelayOffset += delay - this._pausedDelay;
  51477. this._pausedDelay = null;
  51478. }
  51479. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51480. return true;
  51481. }
  51482. // Animating
  51483. var running = false;
  51484. var runtimeAnimations = this._runtimeAnimations;
  51485. var index;
  51486. for (index = 0; index < runtimeAnimations.length; index++) {
  51487. var animation = runtimeAnimations[index];
  51488. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51489. running = running || isRunning;
  51490. }
  51491. this.animationStarted = running;
  51492. if (!running) {
  51493. // Remove from active animatables
  51494. index = this._scene._activeAnimatables.indexOf(this);
  51495. this._scene._activeAnimatables.splice(index, 1);
  51496. // Dispose all runtime animations
  51497. for (index = 0; index < runtimeAnimations.length; index++) {
  51498. runtimeAnimations[index].dispose();
  51499. }
  51500. this._raiseOnAnimationEnd();
  51501. this.onAnimationEnd = null;
  51502. this.onAnimationEndObservable.clear();
  51503. }
  51504. return running;
  51505. };
  51506. return Animatable;
  51507. }());
  51508. BABYLON.Animatable = Animatable;
  51509. })(BABYLON || (BABYLON = {}));
  51510. //# sourceMappingURL=babylon.animatable.js.map
  51511. var BABYLON;
  51512. (function (BABYLON) {
  51513. var EasingFunction = /** @class */ (function () {
  51514. function EasingFunction() {
  51515. // Properties
  51516. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51517. }
  51518. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51519. get: function () {
  51520. return EasingFunction._EASINGMODE_EASEIN;
  51521. },
  51522. enumerable: true,
  51523. configurable: true
  51524. });
  51525. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51526. get: function () {
  51527. return EasingFunction._EASINGMODE_EASEOUT;
  51528. },
  51529. enumerable: true,
  51530. configurable: true
  51531. });
  51532. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51533. get: function () {
  51534. return EasingFunction._EASINGMODE_EASEINOUT;
  51535. },
  51536. enumerable: true,
  51537. configurable: true
  51538. });
  51539. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51540. var n = Math.min(Math.max(easingMode, 0), 2);
  51541. this._easingMode = n;
  51542. };
  51543. EasingFunction.prototype.getEasingMode = function () {
  51544. return this._easingMode;
  51545. };
  51546. EasingFunction.prototype.easeInCore = function (gradient) {
  51547. throw new Error('You must implement this method');
  51548. };
  51549. EasingFunction.prototype.ease = function (gradient) {
  51550. switch (this._easingMode) {
  51551. case EasingFunction.EASINGMODE_EASEIN:
  51552. return this.easeInCore(gradient);
  51553. case EasingFunction.EASINGMODE_EASEOUT:
  51554. return (1 - this.easeInCore(1 - gradient));
  51555. }
  51556. if (gradient >= 0.5) {
  51557. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51558. }
  51559. return (this.easeInCore(gradient * 2) * 0.5);
  51560. };
  51561. //Statics
  51562. EasingFunction._EASINGMODE_EASEIN = 0;
  51563. EasingFunction._EASINGMODE_EASEOUT = 1;
  51564. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51565. return EasingFunction;
  51566. }());
  51567. BABYLON.EasingFunction = EasingFunction;
  51568. var CircleEase = /** @class */ (function (_super) {
  51569. __extends(CircleEase, _super);
  51570. function CircleEase() {
  51571. return _super !== null && _super.apply(this, arguments) || this;
  51572. }
  51573. CircleEase.prototype.easeInCore = function (gradient) {
  51574. gradient = Math.max(0, Math.min(1, gradient));
  51575. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51576. };
  51577. return CircleEase;
  51578. }(EasingFunction));
  51579. BABYLON.CircleEase = CircleEase;
  51580. var BackEase = /** @class */ (function (_super) {
  51581. __extends(BackEase, _super);
  51582. function BackEase(amplitude) {
  51583. if (amplitude === void 0) { amplitude = 1; }
  51584. var _this = _super.call(this) || this;
  51585. _this.amplitude = amplitude;
  51586. return _this;
  51587. }
  51588. BackEase.prototype.easeInCore = function (gradient) {
  51589. var num = Math.max(0, this.amplitude);
  51590. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51591. };
  51592. return BackEase;
  51593. }(EasingFunction));
  51594. BABYLON.BackEase = BackEase;
  51595. var BounceEase = /** @class */ (function (_super) {
  51596. __extends(BounceEase, _super);
  51597. function BounceEase(bounces, bounciness) {
  51598. if (bounces === void 0) { bounces = 3; }
  51599. if (bounciness === void 0) { bounciness = 2; }
  51600. var _this = _super.call(this) || this;
  51601. _this.bounces = bounces;
  51602. _this.bounciness = bounciness;
  51603. return _this;
  51604. }
  51605. BounceEase.prototype.easeInCore = function (gradient) {
  51606. var y = Math.max(0.0, this.bounces);
  51607. var bounciness = this.bounciness;
  51608. if (bounciness <= 1.0) {
  51609. bounciness = 1.001;
  51610. }
  51611. var num9 = Math.pow(bounciness, y);
  51612. var num5 = 1.0 - bounciness;
  51613. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51614. var num15 = gradient * num4;
  51615. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51616. var num3 = Math.floor(num65);
  51617. var num13 = num3 + 1.0;
  51618. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51619. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51620. var num7 = (num8 + num12) * 0.5;
  51621. var num6 = gradient - num7;
  51622. var num2 = num7 - num8;
  51623. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51624. };
  51625. return BounceEase;
  51626. }(EasingFunction));
  51627. BABYLON.BounceEase = BounceEase;
  51628. var CubicEase = /** @class */ (function (_super) {
  51629. __extends(CubicEase, _super);
  51630. function CubicEase() {
  51631. return _super !== null && _super.apply(this, arguments) || this;
  51632. }
  51633. CubicEase.prototype.easeInCore = function (gradient) {
  51634. return (gradient * gradient * gradient);
  51635. };
  51636. return CubicEase;
  51637. }(EasingFunction));
  51638. BABYLON.CubicEase = CubicEase;
  51639. var ElasticEase = /** @class */ (function (_super) {
  51640. __extends(ElasticEase, _super);
  51641. function ElasticEase(oscillations, springiness) {
  51642. if (oscillations === void 0) { oscillations = 3; }
  51643. if (springiness === void 0) { springiness = 3; }
  51644. var _this = _super.call(this) || this;
  51645. _this.oscillations = oscillations;
  51646. _this.springiness = springiness;
  51647. return _this;
  51648. }
  51649. ElasticEase.prototype.easeInCore = function (gradient) {
  51650. var num2;
  51651. var num3 = Math.max(0.0, this.oscillations);
  51652. var num = Math.max(0.0, this.springiness);
  51653. if (num == 0) {
  51654. num2 = gradient;
  51655. }
  51656. else {
  51657. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51658. }
  51659. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51660. };
  51661. return ElasticEase;
  51662. }(EasingFunction));
  51663. BABYLON.ElasticEase = ElasticEase;
  51664. var ExponentialEase = /** @class */ (function (_super) {
  51665. __extends(ExponentialEase, _super);
  51666. function ExponentialEase(exponent) {
  51667. if (exponent === void 0) { exponent = 2; }
  51668. var _this = _super.call(this) || this;
  51669. _this.exponent = exponent;
  51670. return _this;
  51671. }
  51672. ExponentialEase.prototype.easeInCore = function (gradient) {
  51673. if (this.exponent <= 0) {
  51674. return gradient;
  51675. }
  51676. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51677. };
  51678. return ExponentialEase;
  51679. }(EasingFunction));
  51680. BABYLON.ExponentialEase = ExponentialEase;
  51681. var PowerEase = /** @class */ (function (_super) {
  51682. __extends(PowerEase, _super);
  51683. function PowerEase(power) {
  51684. if (power === void 0) { power = 2; }
  51685. var _this = _super.call(this) || this;
  51686. _this.power = power;
  51687. return _this;
  51688. }
  51689. PowerEase.prototype.easeInCore = function (gradient) {
  51690. var y = Math.max(0.0, this.power);
  51691. return Math.pow(gradient, y);
  51692. };
  51693. return PowerEase;
  51694. }(EasingFunction));
  51695. BABYLON.PowerEase = PowerEase;
  51696. var QuadraticEase = /** @class */ (function (_super) {
  51697. __extends(QuadraticEase, _super);
  51698. function QuadraticEase() {
  51699. return _super !== null && _super.apply(this, arguments) || this;
  51700. }
  51701. QuadraticEase.prototype.easeInCore = function (gradient) {
  51702. return (gradient * gradient);
  51703. };
  51704. return QuadraticEase;
  51705. }(EasingFunction));
  51706. BABYLON.QuadraticEase = QuadraticEase;
  51707. var QuarticEase = /** @class */ (function (_super) {
  51708. __extends(QuarticEase, _super);
  51709. function QuarticEase() {
  51710. return _super !== null && _super.apply(this, arguments) || this;
  51711. }
  51712. QuarticEase.prototype.easeInCore = function (gradient) {
  51713. return (gradient * gradient * gradient * gradient);
  51714. };
  51715. return QuarticEase;
  51716. }(EasingFunction));
  51717. BABYLON.QuarticEase = QuarticEase;
  51718. var QuinticEase = /** @class */ (function (_super) {
  51719. __extends(QuinticEase, _super);
  51720. function QuinticEase() {
  51721. return _super !== null && _super.apply(this, arguments) || this;
  51722. }
  51723. QuinticEase.prototype.easeInCore = function (gradient) {
  51724. return (gradient * gradient * gradient * gradient * gradient);
  51725. };
  51726. return QuinticEase;
  51727. }(EasingFunction));
  51728. BABYLON.QuinticEase = QuinticEase;
  51729. var SineEase = /** @class */ (function (_super) {
  51730. __extends(SineEase, _super);
  51731. function SineEase() {
  51732. return _super !== null && _super.apply(this, arguments) || this;
  51733. }
  51734. SineEase.prototype.easeInCore = function (gradient) {
  51735. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51736. };
  51737. return SineEase;
  51738. }(EasingFunction));
  51739. BABYLON.SineEase = SineEase;
  51740. var BezierCurveEase = /** @class */ (function (_super) {
  51741. __extends(BezierCurveEase, _super);
  51742. function BezierCurveEase(x1, y1, x2, y2) {
  51743. if (x1 === void 0) { x1 = 0; }
  51744. if (y1 === void 0) { y1 = 0; }
  51745. if (x2 === void 0) { x2 = 1; }
  51746. if (y2 === void 0) { y2 = 1; }
  51747. var _this = _super.call(this) || this;
  51748. _this.x1 = x1;
  51749. _this.y1 = y1;
  51750. _this.x2 = x2;
  51751. _this.y2 = y2;
  51752. return _this;
  51753. }
  51754. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51755. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51756. };
  51757. return BezierCurveEase;
  51758. }(EasingFunction));
  51759. BABYLON.BezierCurveEase = BezierCurveEase;
  51760. })(BABYLON || (BABYLON = {}));
  51761. //# sourceMappingURL=babylon.easing.js.map
  51762. var BABYLON;
  51763. (function (BABYLON) {
  51764. /**
  51765. * A Condition applied to an Action
  51766. */
  51767. var Condition = /** @class */ (function () {
  51768. /**
  51769. * Creates a new Condition
  51770. * @param actionManager the manager of the action the condition is applied to
  51771. */
  51772. function Condition(actionManager) {
  51773. this._actionManager = actionManager;
  51774. }
  51775. /**
  51776. * Check if the current condition is valid
  51777. * @returns a boolean
  51778. */
  51779. Condition.prototype.isValid = function () {
  51780. return true;
  51781. };
  51782. /**
  51783. * Internal only
  51784. * @hidden
  51785. */
  51786. Condition.prototype._getProperty = function (propertyPath) {
  51787. return this._actionManager._getProperty(propertyPath);
  51788. };
  51789. /**
  51790. * Internal only
  51791. * @hidden
  51792. */
  51793. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51794. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51795. };
  51796. /**
  51797. * Serialize placeholder for child classes
  51798. * @returns the serialized object
  51799. */
  51800. Condition.prototype.serialize = function () {
  51801. };
  51802. /**
  51803. * Internal only
  51804. * @hidden
  51805. */
  51806. Condition.prototype._serialize = function (serializedCondition) {
  51807. return {
  51808. type: 2,
  51809. children: [],
  51810. name: serializedCondition.name,
  51811. properties: serializedCondition.properties
  51812. };
  51813. };
  51814. return Condition;
  51815. }());
  51816. BABYLON.Condition = Condition;
  51817. /**
  51818. * Defines specific conditional operators as extensions of Condition
  51819. */
  51820. var ValueCondition = /** @class */ (function (_super) {
  51821. __extends(ValueCondition, _super);
  51822. /**
  51823. * Creates a new ValueCondition
  51824. * @param actionManager manager for the action the condition applies to
  51825. * @param target for the action
  51826. * @param propertyPath path to specify the property of the target the conditional operator uses
  51827. * @param value the value compared by the conditional operator against the current value of the property
  51828. * @param operator the conditional operator, default ValueCondition.IsEqual
  51829. */
  51830. function ValueCondition(actionManager, target,
  51831. /** path to specify the property of the target the conditional operator uses */
  51832. propertyPath,
  51833. /** the value compared by the conditional operator against the current value of the property */
  51834. value,
  51835. /** the conditional operator, default ValueCondition.IsEqual */
  51836. operator) {
  51837. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51838. var _this = _super.call(this, actionManager) || this;
  51839. _this.propertyPath = propertyPath;
  51840. _this.value = value;
  51841. _this.operator = operator;
  51842. _this._target = target;
  51843. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51844. _this._property = _this._getProperty(_this.propertyPath);
  51845. return _this;
  51846. }
  51847. Object.defineProperty(ValueCondition, "IsEqual", {
  51848. /**
  51849. * returns the number for IsEqual
  51850. */
  51851. get: function () {
  51852. return ValueCondition._IsEqual;
  51853. },
  51854. enumerable: true,
  51855. configurable: true
  51856. });
  51857. Object.defineProperty(ValueCondition, "IsDifferent", {
  51858. /**
  51859. * Returns the number for IsDifferent
  51860. */
  51861. get: function () {
  51862. return ValueCondition._IsDifferent;
  51863. },
  51864. enumerable: true,
  51865. configurable: true
  51866. });
  51867. Object.defineProperty(ValueCondition, "IsGreater", {
  51868. /**
  51869. * Returns the number for IsGreater
  51870. */
  51871. get: function () {
  51872. return ValueCondition._IsGreater;
  51873. },
  51874. enumerable: true,
  51875. configurable: true
  51876. });
  51877. Object.defineProperty(ValueCondition, "IsLesser", {
  51878. /**
  51879. * Returns the number for IsLesser
  51880. */
  51881. get: function () {
  51882. return ValueCondition._IsLesser;
  51883. },
  51884. enumerable: true,
  51885. configurable: true
  51886. });
  51887. /**
  51888. * Compares the given value with the property value for the specified conditional operator
  51889. * @returns the result of the comparison
  51890. */
  51891. ValueCondition.prototype.isValid = function () {
  51892. switch (this.operator) {
  51893. case ValueCondition.IsGreater:
  51894. return this._effectiveTarget[this._property] > this.value;
  51895. case ValueCondition.IsLesser:
  51896. return this._effectiveTarget[this._property] < this.value;
  51897. case ValueCondition.IsEqual:
  51898. case ValueCondition.IsDifferent:
  51899. var check;
  51900. if (this.value.equals) {
  51901. check = this.value.equals(this._effectiveTarget[this._property]);
  51902. }
  51903. else {
  51904. check = this.value === this._effectiveTarget[this._property];
  51905. }
  51906. return this.operator === ValueCondition.IsEqual ? check : !check;
  51907. }
  51908. return false;
  51909. };
  51910. /**
  51911. * Serialize the ValueCondition into a JSON compatible object
  51912. * @returns serialization object
  51913. */
  51914. ValueCondition.prototype.serialize = function () {
  51915. return this._serialize({
  51916. name: "ValueCondition",
  51917. properties: [
  51918. BABYLON.Action._GetTargetProperty(this._target),
  51919. { name: "propertyPath", value: this.propertyPath },
  51920. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51921. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51922. ]
  51923. });
  51924. };
  51925. /**
  51926. * Gets the name of the conditional operator for the ValueCondition
  51927. * @param operator the conditional operator
  51928. * @returns the name
  51929. */
  51930. ValueCondition.GetOperatorName = function (operator) {
  51931. switch (operator) {
  51932. case ValueCondition._IsEqual: return "IsEqual";
  51933. case ValueCondition._IsDifferent: return "IsDifferent";
  51934. case ValueCondition._IsGreater: return "IsGreater";
  51935. case ValueCondition._IsLesser: return "IsLesser";
  51936. default: return "";
  51937. }
  51938. };
  51939. /**
  51940. * Internal only
  51941. * @hidden
  51942. */
  51943. ValueCondition._IsEqual = 0;
  51944. /**
  51945. * Internal only
  51946. * @hidden
  51947. */
  51948. ValueCondition._IsDifferent = 1;
  51949. /**
  51950. * Internal only
  51951. * @hidden
  51952. */
  51953. ValueCondition._IsGreater = 2;
  51954. /**
  51955. * Internal only
  51956. * @hidden
  51957. */
  51958. ValueCondition._IsLesser = 3;
  51959. return ValueCondition;
  51960. }(Condition));
  51961. BABYLON.ValueCondition = ValueCondition;
  51962. /**
  51963. * Defines a predicate condition as an extension of Condition
  51964. */
  51965. var PredicateCondition = /** @class */ (function (_super) {
  51966. __extends(PredicateCondition, _super);
  51967. /**
  51968. * Creates a new PredicateCondition
  51969. * @param actionManager manager for the action the condition applies to
  51970. * @param predicate defines the predicate function used to validate the condition
  51971. */
  51972. function PredicateCondition(actionManager,
  51973. /** defines the predicate function used to validate the condition */
  51974. predicate) {
  51975. var _this = _super.call(this, actionManager) || this;
  51976. _this.predicate = predicate;
  51977. return _this;
  51978. }
  51979. /**
  51980. * @returns the validity of the predicate condition
  51981. */
  51982. PredicateCondition.prototype.isValid = function () {
  51983. return this.predicate();
  51984. };
  51985. return PredicateCondition;
  51986. }(Condition));
  51987. BABYLON.PredicateCondition = PredicateCondition;
  51988. /**
  51989. * Defines a state condition as an extension of Condition
  51990. */
  51991. var StateCondition = /** @class */ (function (_super) {
  51992. __extends(StateCondition, _super);
  51993. /**
  51994. * Creates a new StateCondition
  51995. * @param actionManager manager for the action the condition applies to
  51996. * @param target of the condition
  51997. * @param value to compare with target state
  51998. */
  51999. function StateCondition(actionManager, target, value) {
  52000. var _this = _super.call(this, actionManager) || this;
  52001. _this.value = value;
  52002. _this._target = target;
  52003. return _this;
  52004. }
  52005. /**
  52006. * @returns the validity of the state
  52007. */
  52008. StateCondition.prototype.isValid = function () {
  52009. return this._target.state === this.value;
  52010. };
  52011. /**
  52012. * Serialize the StateCondition into a JSON compatible object
  52013. * @returns serialization object
  52014. */
  52015. StateCondition.prototype.serialize = function () {
  52016. return this._serialize({
  52017. name: "StateCondition",
  52018. properties: [
  52019. BABYLON.Action._GetTargetProperty(this._target),
  52020. { name: "value", value: this.value }
  52021. ]
  52022. });
  52023. };
  52024. return StateCondition;
  52025. }(Condition));
  52026. BABYLON.StateCondition = StateCondition;
  52027. })(BABYLON || (BABYLON = {}));
  52028. //# sourceMappingURL=babylon.condition.js.map
  52029. var BABYLON;
  52030. (function (BABYLON) {
  52031. /**
  52032. * The action to be carried out following a trigger
  52033. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52034. */
  52035. var Action = /** @class */ (function () {
  52036. /**
  52037. * Creates a new Action
  52038. * @param triggerOptions the trigger, with or without parameters, for the action
  52039. * @param condition an optional determinant of action
  52040. */
  52041. function Action(
  52042. /** the trigger, with or without parameters, for the action */
  52043. triggerOptions, condition) {
  52044. this.triggerOptions = triggerOptions;
  52045. /**
  52046. * An event triggered prior to action being executed.
  52047. */
  52048. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52049. if (triggerOptions.parameter) {
  52050. this.trigger = triggerOptions.trigger;
  52051. this._triggerParameter = triggerOptions.parameter;
  52052. }
  52053. else {
  52054. this.trigger = triggerOptions;
  52055. }
  52056. this._nextActiveAction = this;
  52057. this._condition = condition;
  52058. }
  52059. /**
  52060. * Internal only
  52061. * @hidden
  52062. */
  52063. Action.prototype._prepare = function () {
  52064. };
  52065. /**
  52066. * Gets the trigger parameters
  52067. * @returns the trigger parameters
  52068. */
  52069. Action.prototype.getTriggerParameter = function () {
  52070. return this._triggerParameter;
  52071. };
  52072. /**
  52073. * Internal only - executes current action event
  52074. * @hidden
  52075. */
  52076. Action.prototype._executeCurrent = function (evt) {
  52077. if (this._nextActiveAction._condition) {
  52078. var condition = this._nextActiveAction._condition;
  52079. var currentRenderId = this._actionManager.getScene().getRenderId();
  52080. // We cache the current evaluation for the current frame
  52081. if (condition._evaluationId === currentRenderId) {
  52082. if (!condition._currentResult) {
  52083. return;
  52084. }
  52085. }
  52086. else {
  52087. condition._evaluationId = currentRenderId;
  52088. if (!condition.isValid()) {
  52089. condition._currentResult = false;
  52090. return;
  52091. }
  52092. condition._currentResult = true;
  52093. }
  52094. }
  52095. this.onBeforeExecuteObservable.notifyObservers(this);
  52096. this._nextActiveAction.execute(evt);
  52097. this.skipToNextActiveAction();
  52098. };
  52099. /**
  52100. * Execute placeholder for child classes
  52101. * @param evt optional action event
  52102. */
  52103. Action.prototype.execute = function (evt) {
  52104. };
  52105. /**
  52106. * Skips to next active action
  52107. */
  52108. Action.prototype.skipToNextActiveAction = function () {
  52109. if (this._nextActiveAction._child) {
  52110. if (!this._nextActiveAction._child._actionManager) {
  52111. this._nextActiveAction._child._actionManager = this._actionManager;
  52112. }
  52113. this._nextActiveAction = this._nextActiveAction._child;
  52114. }
  52115. else {
  52116. this._nextActiveAction = this;
  52117. }
  52118. };
  52119. /**
  52120. * Adds action to chain of actions, may be a DoNothingAction
  52121. * @param action defines the next action to execute
  52122. * @returns The action passed in
  52123. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52124. */
  52125. Action.prototype.then = function (action) {
  52126. this._child = action;
  52127. action._actionManager = this._actionManager;
  52128. action._prepare();
  52129. return action;
  52130. };
  52131. /**
  52132. * Internal only
  52133. * @hidden
  52134. */
  52135. Action.prototype._getProperty = function (propertyPath) {
  52136. return this._actionManager._getProperty(propertyPath);
  52137. };
  52138. /**
  52139. * Internal only
  52140. * @hidden
  52141. */
  52142. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52143. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52144. };
  52145. /**
  52146. * Serialize placeholder for child classes
  52147. * @param parent of child
  52148. * @returns the serialized object
  52149. */
  52150. Action.prototype.serialize = function (parent) {
  52151. };
  52152. /**
  52153. * Internal only called by serialize
  52154. * @hidden
  52155. */
  52156. Action.prototype._serialize = function (serializedAction, parent) {
  52157. var serializationObject = {
  52158. type: 1,
  52159. children: [],
  52160. name: serializedAction.name,
  52161. properties: serializedAction.properties || []
  52162. };
  52163. // Serialize child
  52164. if (this._child) {
  52165. this._child.serialize(serializationObject);
  52166. }
  52167. // Check if "this" has a condition
  52168. if (this._condition) {
  52169. var serializedCondition = this._condition.serialize();
  52170. serializedCondition.children.push(serializationObject);
  52171. if (parent) {
  52172. parent.children.push(serializedCondition);
  52173. }
  52174. return serializedCondition;
  52175. }
  52176. if (parent) {
  52177. parent.children.push(serializationObject);
  52178. }
  52179. return serializationObject;
  52180. };
  52181. /**
  52182. * Internal only
  52183. * @hidden
  52184. */
  52185. Action._SerializeValueAsString = function (value) {
  52186. if (typeof value === "number") {
  52187. return value.toString();
  52188. }
  52189. if (typeof value === "boolean") {
  52190. return value ? "true" : "false";
  52191. }
  52192. if (value instanceof BABYLON.Vector2) {
  52193. return value.x + ", " + value.y;
  52194. }
  52195. if (value instanceof BABYLON.Vector3) {
  52196. return value.x + ", " + value.y + ", " + value.z;
  52197. }
  52198. if (value instanceof BABYLON.Color3) {
  52199. return value.r + ", " + value.g + ", " + value.b;
  52200. }
  52201. if (value instanceof BABYLON.Color4) {
  52202. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52203. }
  52204. return value; // string
  52205. };
  52206. /**
  52207. * Internal only
  52208. * @hidden
  52209. */
  52210. Action._GetTargetProperty = function (target) {
  52211. return {
  52212. name: "target",
  52213. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52214. : target instanceof BABYLON.Light ? "LightProperties"
  52215. : target instanceof BABYLON.Camera ? "CameraProperties"
  52216. : "SceneProperties",
  52217. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52218. };
  52219. };
  52220. return Action;
  52221. }());
  52222. BABYLON.Action = Action;
  52223. })(BABYLON || (BABYLON = {}));
  52224. //# sourceMappingURL=babylon.action.js.map
  52225. var BABYLON;
  52226. (function (BABYLON) {
  52227. /**
  52228. * ActionEvent is the event being sent when an action is triggered.
  52229. */
  52230. var ActionEvent = /** @class */ (function () {
  52231. /**
  52232. * Creates a new ActionEvent
  52233. * @param source The mesh or sprite that triggered the action
  52234. * @param pointerX The X mouse cursor position at the time of the event
  52235. * @param pointerY The Y mouse cursor position at the time of the event
  52236. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52237. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52238. * @param additionalData additional data for the event
  52239. */
  52240. function ActionEvent(
  52241. /** The mesh or sprite that triggered the action */
  52242. source,
  52243. /** The X mouse cursor position at the time of the event */
  52244. pointerX,
  52245. /** The Y mouse cursor position at the time of the event */
  52246. pointerY,
  52247. /** The mesh that is currently pointed at (can be null) */
  52248. meshUnderPointer,
  52249. /** the original (browser) event that triggered the ActionEvent */
  52250. sourceEvent,
  52251. /** additional data for the event */
  52252. additionalData) {
  52253. this.source = source;
  52254. this.pointerX = pointerX;
  52255. this.pointerY = pointerY;
  52256. this.meshUnderPointer = meshUnderPointer;
  52257. this.sourceEvent = sourceEvent;
  52258. this.additionalData = additionalData;
  52259. }
  52260. /**
  52261. * Helper function to auto-create an ActionEvent from a source mesh.
  52262. * @param source The source mesh that triggered the event
  52263. * @param evt The original (browser) event
  52264. * @param additionalData additional data for the event
  52265. * @returns the new ActionEvent
  52266. */
  52267. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52268. var scene = source.getScene();
  52269. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52270. };
  52271. /**
  52272. * Helper function to auto-create an ActionEvent from a source sprite
  52273. * @param source The source sprite that triggered the event
  52274. * @param scene Scene associated with the sprite
  52275. * @param evt The original (browser) event
  52276. * @param additionalData additional data for the event
  52277. * @returns the new ActionEvent
  52278. */
  52279. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52280. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52281. };
  52282. /**
  52283. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52284. * @param scene the scene where the event occurred
  52285. * @param evt The original (browser) event
  52286. * @returns the new ActionEvent
  52287. */
  52288. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52289. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52290. };
  52291. /**
  52292. * Helper function to auto-create an ActionEvent from a primitive
  52293. * @param prim defines the target primitive
  52294. * @param pointerPos defines the pointer position
  52295. * @param evt The original (browser) event
  52296. * @param additionalData additional data for the event
  52297. * @returns the new ActionEvent
  52298. */
  52299. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52300. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52301. };
  52302. return ActionEvent;
  52303. }());
  52304. BABYLON.ActionEvent = ActionEvent;
  52305. /**
  52306. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52307. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52308. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52309. */
  52310. var ActionManager = /** @class */ (function () {
  52311. /**
  52312. * Creates a new action manager
  52313. * @param scene defines the hosting scene
  52314. */
  52315. function ActionManager(scene) {
  52316. // Members
  52317. /** Gets the list of actions */
  52318. this.actions = new Array();
  52319. /** Gets the cursor to use when hovering items */
  52320. this.hoverCursor = '';
  52321. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52322. scene._actionManagers.push(this);
  52323. }
  52324. Object.defineProperty(ActionManager, "NothingTrigger", {
  52325. /**
  52326. * Nothing
  52327. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52328. */
  52329. get: function () {
  52330. return ActionManager._NothingTrigger;
  52331. },
  52332. enumerable: true,
  52333. configurable: true
  52334. });
  52335. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52336. /**
  52337. * On pick
  52338. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52339. */
  52340. get: function () {
  52341. return ActionManager._OnPickTrigger;
  52342. },
  52343. enumerable: true,
  52344. configurable: true
  52345. });
  52346. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52347. /**
  52348. * On left pick
  52349. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52350. */
  52351. get: function () {
  52352. return ActionManager._OnLeftPickTrigger;
  52353. },
  52354. enumerable: true,
  52355. configurable: true
  52356. });
  52357. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52358. /**
  52359. * On right pick
  52360. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52361. */
  52362. get: function () {
  52363. return ActionManager._OnRightPickTrigger;
  52364. },
  52365. enumerable: true,
  52366. configurable: true
  52367. });
  52368. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52369. /**
  52370. * On center pick
  52371. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52372. */
  52373. get: function () {
  52374. return ActionManager._OnCenterPickTrigger;
  52375. },
  52376. enumerable: true,
  52377. configurable: true
  52378. });
  52379. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52380. /**
  52381. * On pick down
  52382. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52383. */
  52384. get: function () {
  52385. return ActionManager._OnPickDownTrigger;
  52386. },
  52387. enumerable: true,
  52388. configurable: true
  52389. });
  52390. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52391. /**
  52392. * On double pick
  52393. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52394. */
  52395. get: function () {
  52396. return ActionManager._OnDoublePickTrigger;
  52397. },
  52398. enumerable: true,
  52399. configurable: true
  52400. });
  52401. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52402. /**
  52403. * On pick up
  52404. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52405. */
  52406. get: function () {
  52407. return ActionManager._OnPickUpTrigger;
  52408. },
  52409. enumerable: true,
  52410. configurable: true
  52411. });
  52412. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52413. /**
  52414. * On pick out.
  52415. * This trigger will only be raised if you also declared a OnPickDown
  52416. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52417. */
  52418. get: function () {
  52419. return ActionManager._OnPickOutTrigger;
  52420. },
  52421. enumerable: true,
  52422. configurable: true
  52423. });
  52424. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52425. /**
  52426. * On long press
  52427. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52428. */
  52429. get: function () {
  52430. return ActionManager._OnLongPressTrigger;
  52431. },
  52432. enumerable: true,
  52433. configurable: true
  52434. });
  52435. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52436. /**
  52437. * On pointer over
  52438. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52439. */
  52440. get: function () {
  52441. return ActionManager._OnPointerOverTrigger;
  52442. },
  52443. enumerable: true,
  52444. configurable: true
  52445. });
  52446. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52447. /**
  52448. * On pointer out
  52449. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52450. */
  52451. get: function () {
  52452. return ActionManager._OnPointerOutTrigger;
  52453. },
  52454. enumerable: true,
  52455. configurable: true
  52456. });
  52457. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52458. /**
  52459. * On every frame
  52460. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52461. */
  52462. get: function () {
  52463. return ActionManager._OnEveryFrameTrigger;
  52464. },
  52465. enumerable: true,
  52466. configurable: true
  52467. });
  52468. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52469. /**
  52470. * On intersection enter
  52471. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52472. */
  52473. get: function () {
  52474. return ActionManager._OnIntersectionEnterTrigger;
  52475. },
  52476. enumerable: true,
  52477. configurable: true
  52478. });
  52479. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52480. /**
  52481. * On intersection exit
  52482. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52483. */
  52484. get: function () {
  52485. return ActionManager._OnIntersectionExitTrigger;
  52486. },
  52487. enumerable: true,
  52488. configurable: true
  52489. });
  52490. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52491. /**
  52492. * On key down
  52493. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52494. */
  52495. get: function () {
  52496. return ActionManager._OnKeyDownTrigger;
  52497. },
  52498. enumerable: true,
  52499. configurable: true
  52500. });
  52501. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52502. /**
  52503. * On key up
  52504. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52505. */
  52506. get: function () {
  52507. return ActionManager._OnKeyUpTrigger;
  52508. },
  52509. enumerable: true,
  52510. configurable: true
  52511. });
  52512. // Methods
  52513. /**
  52514. * Releases all associated resources
  52515. */
  52516. ActionManager.prototype.dispose = function () {
  52517. var index = this._scene._actionManagers.indexOf(this);
  52518. for (var i = 0; i < this.actions.length; i++) {
  52519. var action = this.actions[i];
  52520. ActionManager.Triggers[action.trigger]--;
  52521. if (ActionManager.Triggers[action.trigger] === 0) {
  52522. delete ActionManager.Triggers[action.trigger];
  52523. }
  52524. }
  52525. if (index > -1) {
  52526. this._scene._actionManagers.splice(index, 1);
  52527. }
  52528. };
  52529. /**
  52530. * Gets hosting scene
  52531. * @returns the hosting scene
  52532. */
  52533. ActionManager.prototype.getScene = function () {
  52534. return this._scene;
  52535. };
  52536. /**
  52537. * Does this action manager handles actions of any of the given triggers
  52538. * @param triggers defines the triggers to be tested
  52539. * @return a boolean indicating whether one (or more) of the triggers is handled
  52540. */
  52541. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52542. for (var index = 0; index < this.actions.length; index++) {
  52543. var action = this.actions[index];
  52544. if (triggers.indexOf(action.trigger) > -1) {
  52545. return true;
  52546. }
  52547. }
  52548. return false;
  52549. };
  52550. /**
  52551. * Does this action manager handles actions of a given trigger
  52552. * @param trigger defines the trigger to be tested
  52553. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52554. * @return whether the trigger is handled
  52555. */
  52556. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52557. for (var index = 0; index < this.actions.length; index++) {
  52558. var action = this.actions[index];
  52559. if (action.trigger === trigger) {
  52560. if (parameterPredicate) {
  52561. if (parameterPredicate(action.getTriggerParameter())) {
  52562. return true;
  52563. }
  52564. }
  52565. else {
  52566. return true;
  52567. }
  52568. }
  52569. }
  52570. return false;
  52571. };
  52572. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52573. /**
  52574. * Does this action manager has pointer triggers
  52575. */
  52576. get: function () {
  52577. for (var index = 0; index < this.actions.length; index++) {
  52578. var action = this.actions[index];
  52579. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52580. return true;
  52581. }
  52582. }
  52583. return false;
  52584. },
  52585. enumerable: true,
  52586. configurable: true
  52587. });
  52588. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52589. /**
  52590. * Does this action manager has pick triggers
  52591. */
  52592. get: function () {
  52593. for (var index = 0; index < this.actions.length; index++) {
  52594. var action = this.actions[index];
  52595. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52596. return true;
  52597. }
  52598. }
  52599. return false;
  52600. },
  52601. enumerable: true,
  52602. configurable: true
  52603. });
  52604. Object.defineProperty(ActionManager, "HasTriggers", {
  52605. /**
  52606. * Does exist one action manager with at least one trigger
  52607. **/
  52608. get: function () {
  52609. for (var t in ActionManager.Triggers) {
  52610. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52611. return true;
  52612. }
  52613. }
  52614. return false;
  52615. },
  52616. enumerable: true,
  52617. configurable: true
  52618. });
  52619. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52620. /**
  52621. * Does exist one action manager with at least one pick trigger
  52622. **/
  52623. get: function () {
  52624. for (var t in ActionManager.Triggers) {
  52625. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52626. var t_int = parseInt(t);
  52627. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52628. return true;
  52629. }
  52630. }
  52631. }
  52632. return false;
  52633. },
  52634. enumerable: true,
  52635. configurable: true
  52636. });
  52637. /**
  52638. * Does exist one action manager that handles actions of a given trigger
  52639. * @param trigger defines the trigger to be tested
  52640. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52641. **/
  52642. ActionManager.HasSpecificTrigger = function (trigger) {
  52643. for (var t in ActionManager.Triggers) {
  52644. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52645. var t_int = parseInt(t);
  52646. if (t_int === trigger) {
  52647. return true;
  52648. }
  52649. }
  52650. }
  52651. return false;
  52652. };
  52653. /**
  52654. * Registers an action to this action manager
  52655. * @param action defines the action to be registered
  52656. * @return the action amended (prepared) after registration
  52657. */
  52658. ActionManager.prototype.registerAction = function (action) {
  52659. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52660. if (this.getScene().actionManager !== this) {
  52661. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52662. return null;
  52663. }
  52664. }
  52665. this.actions.push(action);
  52666. if (ActionManager.Triggers[action.trigger]) {
  52667. ActionManager.Triggers[action.trigger]++;
  52668. }
  52669. else {
  52670. ActionManager.Triggers[action.trigger] = 1;
  52671. }
  52672. action._actionManager = this;
  52673. action._prepare();
  52674. return action;
  52675. };
  52676. /**
  52677. * Unregisters an action to this action manager
  52678. * @param action defines the action to be unregistered
  52679. * @return a boolean indicating whether the action has been unregistered
  52680. */
  52681. ActionManager.prototype.unregisterAction = function (action) {
  52682. var index = this.actions.indexOf(action);
  52683. if (index !== -1) {
  52684. this.actions.splice(index, 1);
  52685. ActionManager.Triggers[action.trigger] -= 1;
  52686. if (ActionManager.Triggers[action.trigger] === 0) {
  52687. delete ActionManager.Triggers[action.trigger];
  52688. }
  52689. delete action._actionManager;
  52690. return true;
  52691. }
  52692. return false;
  52693. };
  52694. /**
  52695. * Process a specific trigger
  52696. * @param trigger defines the trigger to process
  52697. * @param evt defines the event details to be processed
  52698. */
  52699. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52700. for (var index = 0; index < this.actions.length; index++) {
  52701. var action = this.actions[index];
  52702. if (action.trigger === trigger) {
  52703. if (evt) {
  52704. if (trigger === ActionManager.OnKeyUpTrigger
  52705. || trigger === ActionManager.OnKeyDownTrigger) {
  52706. var parameter = action.getTriggerParameter();
  52707. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52708. if (!parameter.toLowerCase) {
  52709. continue;
  52710. }
  52711. var lowerCase = parameter.toLowerCase();
  52712. if (lowerCase !== evt.sourceEvent.key) {
  52713. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52714. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52715. if (actualkey !== lowerCase) {
  52716. continue;
  52717. }
  52718. }
  52719. }
  52720. }
  52721. }
  52722. action._executeCurrent(evt);
  52723. }
  52724. }
  52725. };
  52726. /** @hidden */
  52727. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52728. var properties = propertyPath.split(".");
  52729. for (var index = 0; index < properties.length - 1; index++) {
  52730. target = target[properties[index]];
  52731. }
  52732. return target;
  52733. };
  52734. /** @hidden */
  52735. ActionManager.prototype._getProperty = function (propertyPath) {
  52736. var properties = propertyPath.split(".");
  52737. return properties[properties.length - 1];
  52738. };
  52739. /**
  52740. * Serialize this manager to a JSON object
  52741. * @param name defines the property name to store this manager
  52742. * @returns a JSON representation of this manager
  52743. */
  52744. ActionManager.prototype.serialize = function (name) {
  52745. var root = {
  52746. children: new Array(),
  52747. name: name,
  52748. type: 3,
  52749. properties: new Array() // Empty for root but required
  52750. };
  52751. for (var i = 0; i < this.actions.length; i++) {
  52752. var triggerObject = {
  52753. type: 0,
  52754. children: new Array(),
  52755. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52756. properties: new Array()
  52757. };
  52758. var triggerOptions = this.actions[i].triggerOptions;
  52759. if (triggerOptions && typeof triggerOptions !== "number") {
  52760. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52761. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52762. }
  52763. else {
  52764. var parameter = {};
  52765. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52766. if (triggerOptions.parameter.mesh) {
  52767. parameter._meshId = triggerOptions.parameter.mesh.id;
  52768. }
  52769. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52770. }
  52771. }
  52772. // Serialize child action, recursively
  52773. this.actions[i].serialize(triggerObject);
  52774. // Add serialized trigger
  52775. root.children.push(triggerObject);
  52776. }
  52777. return root;
  52778. };
  52779. /**
  52780. * Creates a new ActionManager from a JSON data
  52781. * @param parsedActions defines the JSON data to read from
  52782. * @param object defines the hosting mesh
  52783. * @param scene defines the hosting scene
  52784. */
  52785. ActionManager.Parse = function (parsedActions, object, scene) {
  52786. var actionManager = new ActionManager(scene);
  52787. if (object === null)
  52788. scene.actionManager = actionManager;
  52789. else
  52790. object.actionManager = actionManager;
  52791. // instanciate a new object
  52792. var instanciate = function (name, params) {
  52793. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52794. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52795. newInstance.constructor.apply(newInstance, params);
  52796. return newInstance;
  52797. };
  52798. var parseParameter = function (name, value, target, propertyPath) {
  52799. if (propertyPath === null) {
  52800. // String, boolean or float
  52801. var floatValue = parseFloat(value);
  52802. if (value === "true" || value === "false")
  52803. return value === "true";
  52804. else
  52805. return isNaN(floatValue) ? value : floatValue;
  52806. }
  52807. var effectiveTarget = propertyPath.split(".");
  52808. var values = value.split(",");
  52809. // Get effective Target
  52810. for (var i = 0; i < effectiveTarget.length; i++) {
  52811. target = target[effectiveTarget[i]];
  52812. }
  52813. // Return appropriate value with its type
  52814. if (typeof (target) === "boolean")
  52815. return values[0] === "true";
  52816. if (typeof (target) === "string")
  52817. return values[0];
  52818. // Parameters with multiple values such as Vector3 etc.
  52819. var split = new Array();
  52820. for (var i = 0; i < values.length; i++)
  52821. split.push(parseFloat(values[i]));
  52822. if (target instanceof BABYLON.Vector3)
  52823. return BABYLON.Vector3.FromArray(split);
  52824. if (target instanceof BABYLON.Vector4)
  52825. return BABYLON.Vector4.FromArray(split);
  52826. if (target instanceof BABYLON.Color3)
  52827. return BABYLON.Color3.FromArray(split);
  52828. if (target instanceof BABYLON.Color4)
  52829. return BABYLON.Color4.FromArray(split);
  52830. return parseFloat(values[0]);
  52831. };
  52832. // traverse graph per trigger
  52833. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52834. if (combineArray === void 0) { combineArray = null; }
  52835. if (parsedAction.detached)
  52836. return;
  52837. var parameters = new Array();
  52838. var target = null;
  52839. var propertyPath = null;
  52840. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52841. // Parameters
  52842. if (parsedAction.type === 2)
  52843. parameters.push(actionManager);
  52844. else
  52845. parameters.push(trigger);
  52846. if (combine) {
  52847. var actions = new Array();
  52848. for (var j = 0; j < parsedAction.combine.length; j++) {
  52849. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52850. }
  52851. parameters.push(actions);
  52852. }
  52853. else {
  52854. for (var i = 0; i < parsedAction.properties.length; i++) {
  52855. var value = parsedAction.properties[i].value;
  52856. var name = parsedAction.properties[i].name;
  52857. var targetType = parsedAction.properties[i].targetType;
  52858. if (name === "target")
  52859. if (targetType !== null && targetType === "SceneProperties")
  52860. value = target = scene;
  52861. else
  52862. value = target = scene.getNodeByName(value);
  52863. else if (name === "parent")
  52864. value = scene.getNodeByName(value);
  52865. else if (name === "sound")
  52866. value = scene.getSoundByName(value);
  52867. else if (name !== "propertyPath") {
  52868. if (parsedAction.type === 2 && name === "operator")
  52869. value = BABYLON.ValueCondition[value];
  52870. else
  52871. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52872. }
  52873. else {
  52874. propertyPath = value;
  52875. }
  52876. parameters.push(value);
  52877. }
  52878. }
  52879. if (combineArray === null) {
  52880. parameters.push(condition);
  52881. }
  52882. else {
  52883. parameters.push(null);
  52884. }
  52885. // If interpolate value action
  52886. if (parsedAction.name === "InterpolateValueAction") {
  52887. var param = parameters[parameters.length - 2];
  52888. parameters[parameters.length - 1] = param;
  52889. parameters[parameters.length - 2] = condition;
  52890. }
  52891. // Action or condition(s) and not CombineAction
  52892. var newAction = instanciate(parsedAction.name, parameters);
  52893. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52894. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52895. if (action)
  52896. action.then(nothing);
  52897. else
  52898. actionManager.registerAction(nothing);
  52899. action = nothing;
  52900. }
  52901. if (combineArray === null) {
  52902. if (newAction instanceof BABYLON.Condition) {
  52903. condition = newAction;
  52904. newAction = action;
  52905. }
  52906. else {
  52907. condition = null;
  52908. if (action)
  52909. action.then(newAction);
  52910. else
  52911. actionManager.registerAction(newAction);
  52912. }
  52913. }
  52914. else {
  52915. combineArray.push(newAction);
  52916. }
  52917. for (var i = 0; i < parsedAction.children.length; i++)
  52918. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52919. };
  52920. // triggers
  52921. for (var i = 0; i < parsedActions.children.length; i++) {
  52922. var triggerParams;
  52923. var trigger = parsedActions.children[i];
  52924. if (trigger.properties.length > 0) {
  52925. var param = trigger.properties[0].value;
  52926. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52927. if (value._meshId) {
  52928. value.mesh = scene.getMeshByID(value._meshId);
  52929. }
  52930. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52931. }
  52932. else
  52933. triggerParams = ActionManager[trigger.name];
  52934. for (var j = 0; j < trigger.children.length; j++) {
  52935. if (!trigger.detached)
  52936. traverse(trigger.children[j], triggerParams, null, null);
  52937. }
  52938. }
  52939. };
  52940. /**
  52941. * Get a trigger name by index
  52942. * @param trigger defines the trigger index
  52943. * @returns a trigger name
  52944. */
  52945. ActionManager.GetTriggerName = function (trigger) {
  52946. switch (trigger) {
  52947. case 0: return "NothingTrigger";
  52948. case 1: return "OnPickTrigger";
  52949. case 2: return "OnLeftPickTrigger";
  52950. case 3: return "OnRightPickTrigger";
  52951. case 4: return "OnCenterPickTrigger";
  52952. case 5: return "OnPickDownTrigger";
  52953. case 6: return "OnPickUpTrigger";
  52954. case 7: return "OnLongPressTrigger";
  52955. case 8: return "OnPointerOverTrigger";
  52956. case 9: return "OnPointerOutTrigger";
  52957. case 10: return "OnEveryFrameTrigger";
  52958. case 11: return "OnIntersectionEnterTrigger";
  52959. case 12: return "OnIntersectionExitTrigger";
  52960. case 13: return "OnKeyDownTrigger";
  52961. case 14: return "OnKeyUpTrigger";
  52962. case 15: return "OnPickOutTrigger";
  52963. default: return "";
  52964. }
  52965. };
  52966. // Statics
  52967. ActionManager._NothingTrigger = 0;
  52968. ActionManager._OnPickTrigger = 1;
  52969. ActionManager._OnLeftPickTrigger = 2;
  52970. ActionManager._OnRightPickTrigger = 3;
  52971. ActionManager._OnCenterPickTrigger = 4;
  52972. ActionManager._OnPickDownTrigger = 5;
  52973. ActionManager._OnDoublePickTrigger = 6;
  52974. ActionManager._OnPickUpTrigger = 7;
  52975. ActionManager._OnLongPressTrigger = 8;
  52976. ActionManager._OnPointerOverTrigger = 9;
  52977. ActionManager._OnPointerOutTrigger = 10;
  52978. ActionManager._OnEveryFrameTrigger = 11;
  52979. ActionManager._OnIntersectionEnterTrigger = 12;
  52980. ActionManager._OnIntersectionExitTrigger = 13;
  52981. ActionManager._OnKeyDownTrigger = 14;
  52982. ActionManager._OnKeyUpTrigger = 15;
  52983. ActionManager._OnPickOutTrigger = 16;
  52984. /** Gets the list of active triggers */
  52985. ActionManager.Triggers = {};
  52986. return ActionManager;
  52987. }());
  52988. BABYLON.ActionManager = ActionManager;
  52989. })(BABYLON || (BABYLON = {}));
  52990. //# sourceMappingURL=babylon.actionManager.js.map
  52991. var BABYLON;
  52992. (function (BABYLON) {
  52993. var InterpolateValueAction = /** @class */ (function (_super) {
  52994. __extends(InterpolateValueAction, _super);
  52995. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52996. if (duration === void 0) { duration = 1000; }
  52997. var _this = _super.call(this, triggerOptions, condition) || this;
  52998. _this.propertyPath = propertyPath;
  52999. _this.value = value;
  53000. _this.duration = duration;
  53001. _this.stopOtherAnimations = stopOtherAnimations;
  53002. _this.onInterpolationDone = onInterpolationDone;
  53003. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53004. _this._target = _this._effectiveTarget = target;
  53005. return _this;
  53006. }
  53007. InterpolateValueAction.prototype._prepare = function () {
  53008. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53009. this._property = this._getProperty(this.propertyPath);
  53010. };
  53011. InterpolateValueAction.prototype.execute = function () {
  53012. var _this = this;
  53013. var scene = this._actionManager.getScene();
  53014. var keys = [
  53015. {
  53016. frame: 0,
  53017. value: this._effectiveTarget[this._property]
  53018. }, {
  53019. frame: 100,
  53020. value: this.value
  53021. }
  53022. ];
  53023. var dataType;
  53024. if (typeof this.value === "number") {
  53025. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53026. }
  53027. else if (this.value instanceof BABYLON.Color3) {
  53028. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53029. }
  53030. else if (this.value instanceof BABYLON.Vector3) {
  53031. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53032. }
  53033. else if (this.value instanceof BABYLON.Matrix) {
  53034. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53035. }
  53036. else if (this.value instanceof BABYLON.Quaternion) {
  53037. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53038. }
  53039. else {
  53040. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53041. return;
  53042. }
  53043. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53044. animation.setKeys(keys);
  53045. if (this.stopOtherAnimations) {
  53046. scene.stopAnimation(this._effectiveTarget);
  53047. }
  53048. var wrapper = function () {
  53049. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53050. if (_this.onInterpolationDone) {
  53051. _this.onInterpolationDone();
  53052. }
  53053. };
  53054. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53055. };
  53056. InterpolateValueAction.prototype.serialize = function (parent) {
  53057. return _super.prototype._serialize.call(this, {
  53058. name: "InterpolateValueAction",
  53059. properties: [
  53060. BABYLON.Action._GetTargetProperty(this._target),
  53061. { name: "propertyPath", value: this.propertyPath },
  53062. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53063. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53064. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53065. ]
  53066. }, parent);
  53067. };
  53068. return InterpolateValueAction;
  53069. }(BABYLON.Action));
  53070. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53071. })(BABYLON || (BABYLON = {}));
  53072. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53073. var BABYLON;
  53074. (function (BABYLON) {
  53075. var SwitchBooleanAction = /** @class */ (function (_super) {
  53076. __extends(SwitchBooleanAction, _super);
  53077. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53078. var _this = _super.call(this, triggerOptions, condition) || this;
  53079. _this.propertyPath = propertyPath;
  53080. _this._target = _this._effectiveTarget = target;
  53081. return _this;
  53082. }
  53083. SwitchBooleanAction.prototype._prepare = function () {
  53084. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53085. this._property = this._getProperty(this.propertyPath);
  53086. };
  53087. SwitchBooleanAction.prototype.execute = function () {
  53088. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53089. };
  53090. SwitchBooleanAction.prototype.serialize = function (parent) {
  53091. return _super.prototype._serialize.call(this, {
  53092. name: "SwitchBooleanAction",
  53093. properties: [
  53094. BABYLON.Action._GetTargetProperty(this._target),
  53095. { name: "propertyPath", value: this.propertyPath }
  53096. ]
  53097. }, parent);
  53098. };
  53099. return SwitchBooleanAction;
  53100. }(BABYLON.Action));
  53101. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53102. var SetStateAction = /** @class */ (function (_super) {
  53103. __extends(SetStateAction, _super);
  53104. function SetStateAction(triggerOptions, target, value, condition) {
  53105. var _this = _super.call(this, triggerOptions, condition) || this;
  53106. _this.value = value;
  53107. _this._target = target;
  53108. return _this;
  53109. }
  53110. SetStateAction.prototype.execute = function () {
  53111. this._target.state = this.value;
  53112. };
  53113. SetStateAction.prototype.serialize = function (parent) {
  53114. return _super.prototype._serialize.call(this, {
  53115. name: "SetStateAction",
  53116. properties: [
  53117. BABYLON.Action._GetTargetProperty(this._target),
  53118. { name: "value", value: this.value }
  53119. ]
  53120. }, parent);
  53121. };
  53122. return SetStateAction;
  53123. }(BABYLON.Action));
  53124. BABYLON.SetStateAction = SetStateAction;
  53125. var SetValueAction = /** @class */ (function (_super) {
  53126. __extends(SetValueAction, _super);
  53127. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53128. var _this = _super.call(this, triggerOptions, condition) || this;
  53129. _this.propertyPath = propertyPath;
  53130. _this.value = value;
  53131. _this._target = _this._effectiveTarget = target;
  53132. return _this;
  53133. }
  53134. SetValueAction.prototype._prepare = function () {
  53135. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53136. this._property = this._getProperty(this.propertyPath);
  53137. };
  53138. SetValueAction.prototype.execute = function () {
  53139. this._effectiveTarget[this._property] = this.value;
  53140. if (this._target.markAsDirty) {
  53141. this._target.markAsDirty(this._property);
  53142. }
  53143. };
  53144. SetValueAction.prototype.serialize = function (parent) {
  53145. return _super.prototype._serialize.call(this, {
  53146. name: "SetValueAction",
  53147. properties: [
  53148. BABYLON.Action._GetTargetProperty(this._target),
  53149. { name: "propertyPath", value: this.propertyPath },
  53150. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53151. ]
  53152. }, parent);
  53153. };
  53154. return SetValueAction;
  53155. }(BABYLON.Action));
  53156. BABYLON.SetValueAction = SetValueAction;
  53157. var IncrementValueAction = /** @class */ (function (_super) {
  53158. __extends(IncrementValueAction, _super);
  53159. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53160. var _this = _super.call(this, triggerOptions, condition) || this;
  53161. _this.propertyPath = propertyPath;
  53162. _this.value = value;
  53163. _this._target = _this._effectiveTarget = target;
  53164. return _this;
  53165. }
  53166. IncrementValueAction.prototype._prepare = function () {
  53167. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53168. this._property = this._getProperty(this.propertyPath);
  53169. if (typeof this._effectiveTarget[this._property] !== "number") {
  53170. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53171. }
  53172. };
  53173. IncrementValueAction.prototype.execute = function () {
  53174. this._effectiveTarget[this._property] += this.value;
  53175. if (this._target.markAsDirty) {
  53176. this._target.markAsDirty(this._property);
  53177. }
  53178. };
  53179. IncrementValueAction.prototype.serialize = function (parent) {
  53180. return _super.prototype._serialize.call(this, {
  53181. name: "IncrementValueAction",
  53182. properties: [
  53183. BABYLON.Action._GetTargetProperty(this._target),
  53184. { name: "propertyPath", value: this.propertyPath },
  53185. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53186. ]
  53187. }, parent);
  53188. };
  53189. return IncrementValueAction;
  53190. }(BABYLON.Action));
  53191. BABYLON.IncrementValueAction = IncrementValueAction;
  53192. var PlayAnimationAction = /** @class */ (function (_super) {
  53193. __extends(PlayAnimationAction, _super);
  53194. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53195. var _this = _super.call(this, triggerOptions, condition) || this;
  53196. _this.from = from;
  53197. _this.to = to;
  53198. _this.loop = loop;
  53199. _this._target = target;
  53200. return _this;
  53201. }
  53202. PlayAnimationAction.prototype._prepare = function () {
  53203. };
  53204. PlayAnimationAction.prototype.execute = function () {
  53205. var scene = this._actionManager.getScene();
  53206. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53207. };
  53208. PlayAnimationAction.prototype.serialize = function (parent) {
  53209. return _super.prototype._serialize.call(this, {
  53210. name: "PlayAnimationAction",
  53211. properties: [
  53212. BABYLON.Action._GetTargetProperty(this._target),
  53213. { name: "from", value: String(this.from) },
  53214. { name: "to", value: String(this.to) },
  53215. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53216. ]
  53217. }, parent);
  53218. };
  53219. return PlayAnimationAction;
  53220. }(BABYLON.Action));
  53221. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53222. var StopAnimationAction = /** @class */ (function (_super) {
  53223. __extends(StopAnimationAction, _super);
  53224. function StopAnimationAction(triggerOptions, target, condition) {
  53225. var _this = _super.call(this, triggerOptions, condition) || this;
  53226. _this._target = target;
  53227. return _this;
  53228. }
  53229. StopAnimationAction.prototype._prepare = function () {
  53230. };
  53231. StopAnimationAction.prototype.execute = function () {
  53232. var scene = this._actionManager.getScene();
  53233. scene.stopAnimation(this._target);
  53234. };
  53235. StopAnimationAction.prototype.serialize = function (parent) {
  53236. return _super.prototype._serialize.call(this, {
  53237. name: "StopAnimationAction",
  53238. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53239. }, parent);
  53240. };
  53241. return StopAnimationAction;
  53242. }(BABYLON.Action));
  53243. BABYLON.StopAnimationAction = StopAnimationAction;
  53244. var DoNothingAction = /** @class */ (function (_super) {
  53245. __extends(DoNothingAction, _super);
  53246. function DoNothingAction(triggerOptions, condition) {
  53247. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53248. return _super.call(this, triggerOptions, condition) || this;
  53249. }
  53250. DoNothingAction.prototype.execute = function () {
  53251. };
  53252. DoNothingAction.prototype.serialize = function (parent) {
  53253. return _super.prototype._serialize.call(this, {
  53254. name: "DoNothingAction",
  53255. properties: []
  53256. }, parent);
  53257. };
  53258. return DoNothingAction;
  53259. }(BABYLON.Action));
  53260. BABYLON.DoNothingAction = DoNothingAction;
  53261. var CombineAction = /** @class */ (function (_super) {
  53262. __extends(CombineAction, _super);
  53263. function CombineAction(triggerOptions, children, condition) {
  53264. var _this = _super.call(this, triggerOptions, condition) || this;
  53265. _this.children = children;
  53266. return _this;
  53267. }
  53268. CombineAction.prototype._prepare = function () {
  53269. for (var index = 0; index < this.children.length; index++) {
  53270. this.children[index]._actionManager = this._actionManager;
  53271. this.children[index]._prepare();
  53272. }
  53273. };
  53274. CombineAction.prototype.execute = function (evt) {
  53275. for (var index = 0; index < this.children.length; index++) {
  53276. this.children[index].execute(evt);
  53277. }
  53278. };
  53279. CombineAction.prototype.serialize = function (parent) {
  53280. var serializationObject = _super.prototype._serialize.call(this, {
  53281. name: "CombineAction",
  53282. properties: [],
  53283. combine: []
  53284. }, parent);
  53285. for (var i = 0; i < this.children.length; i++) {
  53286. serializationObject.combine.push(this.children[i].serialize(null));
  53287. }
  53288. return serializationObject;
  53289. };
  53290. return CombineAction;
  53291. }(BABYLON.Action));
  53292. BABYLON.CombineAction = CombineAction;
  53293. var ExecuteCodeAction = /** @class */ (function (_super) {
  53294. __extends(ExecuteCodeAction, _super);
  53295. function ExecuteCodeAction(triggerOptions, func, condition) {
  53296. var _this = _super.call(this, triggerOptions, condition) || this;
  53297. _this.func = func;
  53298. return _this;
  53299. }
  53300. ExecuteCodeAction.prototype.execute = function (evt) {
  53301. this.func(evt);
  53302. };
  53303. return ExecuteCodeAction;
  53304. }(BABYLON.Action));
  53305. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53306. var SetParentAction = /** @class */ (function (_super) {
  53307. __extends(SetParentAction, _super);
  53308. function SetParentAction(triggerOptions, target, parent, condition) {
  53309. var _this = _super.call(this, triggerOptions, condition) || this;
  53310. _this._target = target;
  53311. _this._parent = parent;
  53312. return _this;
  53313. }
  53314. SetParentAction.prototype._prepare = function () {
  53315. };
  53316. SetParentAction.prototype.execute = function () {
  53317. if (this._target.parent === this._parent) {
  53318. return;
  53319. }
  53320. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53321. invertParentWorldMatrix.invert();
  53322. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53323. this._target.parent = this._parent;
  53324. };
  53325. SetParentAction.prototype.serialize = function (parent) {
  53326. return _super.prototype._serialize.call(this, {
  53327. name: "SetParentAction",
  53328. properties: [
  53329. BABYLON.Action._GetTargetProperty(this._target),
  53330. BABYLON.Action._GetTargetProperty(this._parent),
  53331. ]
  53332. }, parent);
  53333. };
  53334. return SetParentAction;
  53335. }(BABYLON.Action));
  53336. BABYLON.SetParentAction = SetParentAction;
  53337. var PlaySoundAction = /** @class */ (function (_super) {
  53338. __extends(PlaySoundAction, _super);
  53339. function PlaySoundAction(triggerOptions, sound, condition) {
  53340. var _this = _super.call(this, triggerOptions, condition) || this;
  53341. _this._sound = sound;
  53342. return _this;
  53343. }
  53344. PlaySoundAction.prototype._prepare = function () {
  53345. };
  53346. PlaySoundAction.prototype.execute = function () {
  53347. if (this._sound !== undefined)
  53348. this._sound.play();
  53349. };
  53350. PlaySoundAction.prototype.serialize = function (parent) {
  53351. return _super.prototype._serialize.call(this, {
  53352. name: "PlaySoundAction",
  53353. properties: [{ name: "sound", value: this._sound.name }]
  53354. }, parent);
  53355. };
  53356. return PlaySoundAction;
  53357. }(BABYLON.Action));
  53358. BABYLON.PlaySoundAction = PlaySoundAction;
  53359. var StopSoundAction = /** @class */ (function (_super) {
  53360. __extends(StopSoundAction, _super);
  53361. function StopSoundAction(triggerOptions, sound, condition) {
  53362. var _this = _super.call(this, triggerOptions, condition) || this;
  53363. _this._sound = sound;
  53364. return _this;
  53365. }
  53366. StopSoundAction.prototype._prepare = function () {
  53367. };
  53368. StopSoundAction.prototype.execute = function () {
  53369. if (this._sound !== undefined)
  53370. this._sound.stop();
  53371. };
  53372. StopSoundAction.prototype.serialize = function (parent) {
  53373. return _super.prototype._serialize.call(this, {
  53374. name: "StopSoundAction",
  53375. properties: [{ name: "sound", value: this._sound.name }]
  53376. }, parent);
  53377. };
  53378. return StopSoundAction;
  53379. }(BABYLON.Action));
  53380. BABYLON.StopSoundAction = StopSoundAction;
  53381. })(BABYLON || (BABYLON = {}));
  53382. //# sourceMappingURL=babylon.directActions.js.map
  53383. var BABYLON;
  53384. (function (BABYLON) {
  53385. var SpriteManager = /** @class */ (function () {
  53386. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53387. if (epsilon === void 0) { epsilon = 0.01; }
  53388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53389. this.name = name;
  53390. this.sprites = new Array();
  53391. this.renderingGroupId = 0;
  53392. this.layerMask = 0x0FFFFFFF;
  53393. this.fogEnabled = true;
  53394. this.isPickable = false;
  53395. /**
  53396. * An event triggered when the manager is disposed.
  53397. */
  53398. this.onDisposeObservable = new BABYLON.Observable();
  53399. this._vertexBuffers = {};
  53400. this._capacity = capacity;
  53401. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53402. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53403. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53404. if (cellSize.width && cellSize.height) {
  53405. this.cellWidth = cellSize.width;
  53406. this.cellHeight = cellSize.height;
  53407. }
  53408. else if (cellSize !== undefined) {
  53409. this.cellWidth = cellSize;
  53410. this.cellHeight = cellSize;
  53411. }
  53412. else {
  53413. return;
  53414. }
  53415. this._epsilon = epsilon;
  53416. this._scene = scene;
  53417. this._scene.spriteManagers.push(this);
  53418. var indices = [];
  53419. var index = 0;
  53420. for (var count = 0; count < capacity; count++) {
  53421. indices.push(index);
  53422. indices.push(index + 1);
  53423. indices.push(index + 2);
  53424. indices.push(index);
  53425. indices.push(index + 2);
  53426. indices.push(index + 3);
  53427. index += 4;
  53428. }
  53429. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53430. // VBO
  53431. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53432. this._vertexData = new Float32Array(capacity * 16 * 4);
  53433. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53434. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53435. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53436. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53437. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53438. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53439. this._vertexBuffers["options"] = options;
  53440. this._vertexBuffers["cellInfo"] = cellInfo;
  53441. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53442. // Effects
  53443. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53444. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53445. }
  53446. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53447. set: function (callback) {
  53448. if (this._onDisposeObserver) {
  53449. this.onDisposeObservable.remove(this._onDisposeObserver);
  53450. }
  53451. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53452. },
  53453. enumerable: true,
  53454. configurable: true
  53455. });
  53456. Object.defineProperty(SpriteManager.prototype, "texture", {
  53457. get: function () {
  53458. return this._spriteTexture;
  53459. },
  53460. set: function (value) {
  53461. this._spriteTexture = value;
  53462. },
  53463. enumerable: true,
  53464. configurable: true
  53465. });
  53466. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53467. var arrayOffset = index * 16;
  53468. if (offsetX === 0)
  53469. offsetX = this._epsilon;
  53470. else if (offsetX === 1)
  53471. offsetX = 1 - this._epsilon;
  53472. if (offsetY === 0)
  53473. offsetY = this._epsilon;
  53474. else if (offsetY === 1)
  53475. offsetY = 1 - this._epsilon;
  53476. this._vertexData[arrayOffset] = sprite.position.x;
  53477. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53478. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53479. this._vertexData[arrayOffset + 3] = sprite.angle;
  53480. this._vertexData[arrayOffset + 4] = sprite.width;
  53481. this._vertexData[arrayOffset + 5] = sprite.height;
  53482. this._vertexData[arrayOffset + 6] = offsetX;
  53483. this._vertexData[arrayOffset + 7] = offsetY;
  53484. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53485. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53486. var offset = (sprite.cellIndex / rowSize) >> 0;
  53487. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53488. this._vertexData[arrayOffset + 11] = offset;
  53489. // Color
  53490. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53491. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53492. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53493. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53494. };
  53495. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53496. var count = Math.min(this._capacity, this.sprites.length);
  53497. var min = BABYLON.Vector3.Zero();
  53498. var max = BABYLON.Vector3.Zero();
  53499. var distance = Number.MAX_VALUE;
  53500. var currentSprite = null;
  53501. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53502. var cameraView = camera.getViewMatrix();
  53503. for (var index = 0; index < count; index++) {
  53504. var sprite = this.sprites[index];
  53505. if (!sprite) {
  53506. continue;
  53507. }
  53508. if (predicate) {
  53509. if (!predicate(sprite)) {
  53510. continue;
  53511. }
  53512. }
  53513. else if (!sprite.isPickable) {
  53514. continue;
  53515. }
  53516. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53517. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53518. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53519. if (ray.intersectsBoxMinMax(min, max)) {
  53520. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53521. if (distance > currentDistance) {
  53522. distance = currentDistance;
  53523. currentSprite = sprite;
  53524. if (fastCheck) {
  53525. break;
  53526. }
  53527. }
  53528. }
  53529. }
  53530. if (currentSprite) {
  53531. var result = new BABYLON.PickingInfo();
  53532. result.hit = true;
  53533. result.pickedSprite = currentSprite;
  53534. result.distance = distance;
  53535. return result;
  53536. }
  53537. return null;
  53538. };
  53539. SpriteManager.prototype.render = function () {
  53540. // Check
  53541. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53542. return;
  53543. var engine = this._scene.getEngine();
  53544. var baseSize = this._spriteTexture.getBaseSize();
  53545. // Sprites
  53546. var deltaTime = engine.getDeltaTime();
  53547. var max = Math.min(this._capacity, this.sprites.length);
  53548. var rowSize = baseSize.width / this.cellWidth;
  53549. var offset = 0;
  53550. for (var index = 0; index < max; index++) {
  53551. var sprite = this.sprites[index];
  53552. if (!sprite || !sprite.isVisible) {
  53553. continue;
  53554. }
  53555. sprite._animate(deltaTime);
  53556. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53557. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53558. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53559. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53560. }
  53561. this._buffer.update(this._vertexData);
  53562. // Render
  53563. var effect = this._effectBase;
  53564. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53565. effect = this._effectFog;
  53566. }
  53567. engine.enableEffect(effect);
  53568. var viewMatrix = this._scene.getViewMatrix();
  53569. effect.setTexture("diffuseSampler", this._spriteTexture);
  53570. effect.setMatrix("view", viewMatrix);
  53571. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53572. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53573. // Fog
  53574. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53575. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53576. effect.setColor3("vFogColor", this._scene.fogColor);
  53577. }
  53578. // VBOs
  53579. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53580. // Draw order
  53581. engine.setDepthFunctionToLessOrEqual();
  53582. effect.setBool("alphaTest", true);
  53583. engine.setColorWrite(false);
  53584. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53585. engine.setColorWrite(true);
  53586. effect.setBool("alphaTest", false);
  53587. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53588. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53589. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53590. };
  53591. SpriteManager.prototype.dispose = function () {
  53592. if (this._buffer) {
  53593. this._buffer.dispose();
  53594. this._buffer = null;
  53595. }
  53596. if (this._indexBuffer) {
  53597. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53598. this._indexBuffer = null;
  53599. }
  53600. if (this._spriteTexture) {
  53601. this._spriteTexture.dispose();
  53602. this._spriteTexture = null;
  53603. }
  53604. // Remove from scene
  53605. var index = this._scene.spriteManagers.indexOf(this);
  53606. this._scene.spriteManagers.splice(index, 1);
  53607. // Callback
  53608. this.onDisposeObservable.notifyObservers(this);
  53609. this.onDisposeObservable.clear();
  53610. };
  53611. return SpriteManager;
  53612. }());
  53613. BABYLON.SpriteManager = SpriteManager;
  53614. })(BABYLON || (BABYLON = {}));
  53615. //# sourceMappingURL=babylon.spriteManager.js.map
  53616. var BABYLON;
  53617. (function (BABYLON) {
  53618. var Sprite = /** @class */ (function () {
  53619. function Sprite(name, manager) {
  53620. this.name = name;
  53621. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53622. this.width = 1.0;
  53623. this.height = 1.0;
  53624. this.angle = 0;
  53625. this.cellIndex = 0;
  53626. this.invertU = 0;
  53627. this.invertV = 0;
  53628. this.animations = new Array();
  53629. this.isPickable = false;
  53630. this._animationStarted = false;
  53631. this._loopAnimation = false;
  53632. this._fromIndex = 0;
  53633. this._toIndex = 0;
  53634. this._delay = 0;
  53635. this._direction = 1;
  53636. this._time = 0;
  53637. /**
  53638. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53639. */
  53640. this.isVisible = true;
  53641. this._manager = manager;
  53642. this._manager.sprites.push(this);
  53643. this.position = BABYLON.Vector3.Zero();
  53644. }
  53645. Object.defineProperty(Sprite.prototype, "size", {
  53646. get: function () {
  53647. return this.width;
  53648. },
  53649. set: function (value) {
  53650. this.width = value;
  53651. this.height = value;
  53652. },
  53653. enumerable: true,
  53654. configurable: true
  53655. });
  53656. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53657. this._fromIndex = from;
  53658. this._toIndex = to;
  53659. this._loopAnimation = loop;
  53660. this._delay = delay;
  53661. this._animationStarted = true;
  53662. this._direction = from < to ? 1 : -1;
  53663. this.cellIndex = from;
  53664. this._time = 0;
  53665. this._onAnimationEnd = onAnimationEnd;
  53666. };
  53667. Sprite.prototype.stopAnimation = function () {
  53668. this._animationStarted = false;
  53669. };
  53670. Sprite.prototype._animate = function (deltaTime) {
  53671. if (!this._animationStarted)
  53672. return;
  53673. this._time += deltaTime;
  53674. if (this._time > this._delay) {
  53675. this._time = this._time % this._delay;
  53676. this.cellIndex += this._direction;
  53677. if (this.cellIndex > this._toIndex) {
  53678. if (this._loopAnimation) {
  53679. this.cellIndex = this._fromIndex;
  53680. }
  53681. else {
  53682. this.cellIndex = this._toIndex;
  53683. this._animationStarted = false;
  53684. if (this._onAnimationEnd) {
  53685. this._onAnimationEnd();
  53686. }
  53687. if (this.disposeWhenFinishedAnimating) {
  53688. this.dispose();
  53689. }
  53690. }
  53691. }
  53692. }
  53693. };
  53694. Sprite.prototype.dispose = function () {
  53695. for (var i = 0; i < this._manager.sprites.length; i++) {
  53696. if (this._manager.sprites[i] == this) {
  53697. this._manager.sprites.splice(i, 1);
  53698. }
  53699. }
  53700. };
  53701. return Sprite;
  53702. }());
  53703. BABYLON.Sprite = Sprite;
  53704. })(BABYLON || (BABYLON = {}));
  53705. //# sourceMappingURL=babylon.sprite.js.map
  53706. var BABYLON;
  53707. (function (BABYLON) {
  53708. var IntersectionInfo = /** @class */ (function () {
  53709. function IntersectionInfo(bu, bv, distance) {
  53710. this.bu = bu;
  53711. this.bv = bv;
  53712. this.distance = distance;
  53713. this.faceId = 0;
  53714. this.subMeshId = 0;
  53715. }
  53716. return IntersectionInfo;
  53717. }());
  53718. BABYLON.IntersectionInfo = IntersectionInfo;
  53719. /**
  53720. * Information about the result of picking within a scene
  53721. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53722. */
  53723. var PickingInfo = /** @class */ (function () {
  53724. function PickingInfo() {
  53725. /**
  53726. * If the pick collided with an object
  53727. */
  53728. this.hit = false;
  53729. /**
  53730. * Distance away where the pick collided
  53731. */
  53732. this.distance = 0;
  53733. /**
  53734. * The location of pick collision
  53735. */
  53736. this.pickedPoint = null;
  53737. /**
  53738. * The mesh corrisponding the the pick collision
  53739. */
  53740. this.pickedMesh = null;
  53741. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53742. this.bu = 0;
  53743. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53744. this.bv = 0;
  53745. /** The id of the face on the mesh that was picked */
  53746. this.faceId = -1;
  53747. /** Id of the the submesh that was picked */
  53748. this.subMeshId = 0;
  53749. /** If a sprite was picked, this will be the sprite the pick collided with */
  53750. this.pickedSprite = null;
  53751. /**
  53752. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53753. */
  53754. this.originMesh = null;
  53755. /**
  53756. * The ray that was used to perform the picking.
  53757. */
  53758. this.ray = null;
  53759. }
  53760. /**
  53761. * Gets the normal corrispodning to the face the pick collided with
  53762. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53763. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53764. * @returns The normal corrispodning to the face the pick collided with
  53765. */
  53766. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53767. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53768. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53769. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53770. return null;
  53771. }
  53772. var indices = this.pickedMesh.getIndices();
  53773. if (!indices) {
  53774. return null;
  53775. }
  53776. var result;
  53777. if (useVerticesNormals) {
  53778. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53779. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53780. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53781. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53782. normal0 = normal0.scale(this.bu);
  53783. normal1 = normal1.scale(this.bv);
  53784. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53785. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53786. }
  53787. else {
  53788. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53789. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53790. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53791. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53792. var p1p2 = vertex1.subtract(vertex2);
  53793. var p3p2 = vertex3.subtract(vertex2);
  53794. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53795. }
  53796. if (useWorldCoordinates) {
  53797. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53798. }
  53799. return BABYLON.Vector3.Normalize(result);
  53800. };
  53801. /**
  53802. * Gets the texture coordinates of where the pick occured
  53803. * @returns the vector containing the coordnates of the texture
  53804. */
  53805. PickingInfo.prototype.getTextureCoordinates = function () {
  53806. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53807. return null;
  53808. }
  53809. var indices = this.pickedMesh.getIndices();
  53810. if (!indices) {
  53811. return null;
  53812. }
  53813. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53814. if (!uvs) {
  53815. return null;
  53816. }
  53817. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53818. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53819. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53820. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53821. uv1 = uv1.scale(this.bu);
  53822. uv2 = uv2.scale(this.bv);
  53823. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53824. };
  53825. return PickingInfo;
  53826. }());
  53827. BABYLON.PickingInfo = PickingInfo;
  53828. })(BABYLON || (BABYLON = {}));
  53829. //# sourceMappingURL=babylon.pickingInfo.js.map
  53830. var BABYLON;
  53831. (function (BABYLON) {
  53832. var Ray = /** @class */ (function () {
  53833. function Ray(origin, direction, length) {
  53834. if (length === void 0) { length = Number.MAX_VALUE; }
  53835. this.origin = origin;
  53836. this.direction = direction;
  53837. this.length = length;
  53838. }
  53839. // Methods
  53840. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53841. var d = 0.0;
  53842. var maxValue = Number.MAX_VALUE;
  53843. var inv;
  53844. var min;
  53845. var max;
  53846. var temp;
  53847. if (Math.abs(this.direction.x) < 0.0000001) {
  53848. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53849. return false;
  53850. }
  53851. }
  53852. else {
  53853. inv = 1.0 / this.direction.x;
  53854. min = (minimum.x - this.origin.x) * inv;
  53855. max = (maximum.x - this.origin.x) * inv;
  53856. if (max === -Infinity) {
  53857. max = Infinity;
  53858. }
  53859. if (min > max) {
  53860. temp = min;
  53861. min = max;
  53862. max = temp;
  53863. }
  53864. d = Math.max(min, d);
  53865. maxValue = Math.min(max, maxValue);
  53866. if (d > maxValue) {
  53867. return false;
  53868. }
  53869. }
  53870. if (Math.abs(this.direction.y) < 0.0000001) {
  53871. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53872. return false;
  53873. }
  53874. }
  53875. else {
  53876. inv = 1.0 / this.direction.y;
  53877. min = (minimum.y - this.origin.y) * inv;
  53878. max = (maximum.y - this.origin.y) * inv;
  53879. if (max === -Infinity) {
  53880. max = Infinity;
  53881. }
  53882. if (min > max) {
  53883. temp = min;
  53884. min = max;
  53885. max = temp;
  53886. }
  53887. d = Math.max(min, d);
  53888. maxValue = Math.min(max, maxValue);
  53889. if (d > maxValue) {
  53890. return false;
  53891. }
  53892. }
  53893. if (Math.abs(this.direction.z) < 0.0000001) {
  53894. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53895. return false;
  53896. }
  53897. }
  53898. else {
  53899. inv = 1.0 / this.direction.z;
  53900. min = (minimum.z - this.origin.z) * inv;
  53901. max = (maximum.z - this.origin.z) * inv;
  53902. if (max === -Infinity) {
  53903. max = Infinity;
  53904. }
  53905. if (min > max) {
  53906. temp = min;
  53907. min = max;
  53908. max = temp;
  53909. }
  53910. d = Math.max(min, d);
  53911. maxValue = Math.min(max, maxValue);
  53912. if (d > maxValue) {
  53913. return false;
  53914. }
  53915. }
  53916. return true;
  53917. };
  53918. Ray.prototype.intersectsBox = function (box) {
  53919. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53920. };
  53921. Ray.prototype.intersectsSphere = function (sphere) {
  53922. var x = sphere.center.x - this.origin.x;
  53923. var y = sphere.center.y - this.origin.y;
  53924. var z = sphere.center.z - this.origin.z;
  53925. var pyth = (x * x) + (y * y) + (z * z);
  53926. var rr = sphere.radius * sphere.radius;
  53927. if (pyth <= rr) {
  53928. return true;
  53929. }
  53930. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53931. if (dot < 0.0) {
  53932. return false;
  53933. }
  53934. var temp = pyth - (dot * dot);
  53935. return temp <= rr;
  53936. };
  53937. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53938. if (!this._edge1) {
  53939. this._edge1 = BABYLON.Vector3.Zero();
  53940. this._edge2 = BABYLON.Vector3.Zero();
  53941. this._pvec = BABYLON.Vector3.Zero();
  53942. this._tvec = BABYLON.Vector3.Zero();
  53943. this._qvec = BABYLON.Vector3.Zero();
  53944. }
  53945. vertex1.subtractToRef(vertex0, this._edge1);
  53946. vertex2.subtractToRef(vertex0, this._edge2);
  53947. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53948. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53949. if (det === 0) {
  53950. return null;
  53951. }
  53952. var invdet = 1 / det;
  53953. this.origin.subtractToRef(vertex0, this._tvec);
  53954. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53955. if (bu < 0 || bu > 1.0) {
  53956. return null;
  53957. }
  53958. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53959. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53960. if (bv < 0 || bu + bv > 1.0) {
  53961. return null;
  53962. }
  53963. //check if the distance is longer than the predefined length.
  53964. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53965. if (distance > this.length) {
  53966. return null;
  53967. }
  53968. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53969. };
  53970. Ray.prototype.intersectsPlane = function (plane) {
  53971. var distance;
  53972. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53973. if (Math.abs(result1) < 9.99999997475243E-07) {
  53974. return null;
  53975. }
  53976. else {
  53977. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53978. distance = (-plane.d - result2) / result1;
  53979. if (distance < 0.0) {
  53980. if (distance < -9.99999997475243E-07) {
  53981. return null;
  53982. }
  53983. else {
  53984. return 0;
  53985. }
  53986. }
  53987. return distance;
  53988. }
  53989. };
  53990. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53991. var tm = BABYLON.Tmp.Matrix[0];
  53992. mesh.getWorldMatrix().invertToRef(tm);
  53993. if (this._tmpRay) {
  53994. Ray.TransformToRef(this, tm, this._tmpRay);
  53995. }
  53996. else {
  53997. this._tmpRay = Ray.Transform(this, tm);
  53998. }
  53999. return mesh.intersects(this._tmpRay, fastCheck);
  54000. };
  54001. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54002. if (results) {
  54003. results.length = 0;
  54004. }
  54005. else {
  54006. results = [];
  54007. }
  54008. for (var i = 0; i < meshes.length; i++) {
  54009. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54010. if (pickInfo.hit) {
  54011. results.push(pickInfo);
  54012. }
  54013. }
  54014. results.sort(this._comparePickingInfo);
  54015. return results;
  54016. };
  54017. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54018. if (pickingInfoA.distance < pickingInfoB.distance) {
  54019. return -1;
  54020. }
  54021. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54022. return 1;
  54023. }
  54024. else {
  54025. return 0;
  54026. }
  54027. };
  54028. /**
  54029. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54030. * @param sega the first point of the segment to test the intersection against
  54031. * @param segb the second point of the segment to test the intersection against
  54032. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54033. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54034. */
  54035. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54036. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54037. var u = segb.subtract(sega);
  54038. var v = rsegb.subtract(this.origin);
  54039. var w = sega.subtract(this.origin);
  54040. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54041. var b = BABYLON.Vector3.Dot(u, v);
  54042. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54043. var d = BABYLON.Vector3.Dot(u, w);
  54044. var e = BABYLON.Vector3.Dot(v, w);
  54045. var D = a * c - b * b; // always >= 0
  54046. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54047. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54048. // compute the line parameters of the two closest points
  54049. if (D < Ray.smallnum) { // the lines are almost parallel
  54050. sN = 0.0; // force using point P0 on segment S1
  54051. sD = 1.0; // to prevent possible division by 0.0 later
  54052. tN = e;
  54053. tD = c;
  54054. }
  54055. else { // get the closest points on the infinite lines
  54056. sN = (b * e - c * d);
  54057. tN = (a * e - b * d);
  54058. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54059. sN = 0.0;
  54060. tN = e;
  54061. tD = c;
  54062. }
  54063. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54064. sN = sD;
  54065. tN = e + b;
  54066. tD = c;
  54067. }
  54068. }
  54069. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54070. tN = 0.0;
  54071. // recompute sc for this edge
  54072. if (-d < 0.0) {
  54073. sN = 0.0;
  54074. }
  54075. else if (-d > a)
  54076. sN = sD;
  54077. else {
  54078. sN = -d;
  54079. sD = a;
  54080. }
  54081. }
  54082. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54083. tN = tD;
  54084. // recompute sc for this edge
  54085. if ((-d + b) < 0.0) {
  54086. sN = 0;
  54087. }
  54088. else if ((-d + b) > a) {
  54089. sN = sD;
  54090. }
  54091. else {
  54092. sN = (-d + b);
  54093. sD = a;
  54094. }
  54095. }
  54096. // finally do the division to get sc and tc
  54097. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54098. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54099. // get the difference of the two closest points
  54100. var qtc = v.multiplyByFloats(tc, tc, tc);
  54101. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54102. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54103. if (isIntersected) {
  54104. return qtc.length();
  54105. }
  54106. return -1;
  54107. };
  54108. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54109. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54110. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54111. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54112. this.direction.normalize();
  54113. return this;
  54114. };
  54115. // Statics
  54116. Ray.Zero = function () {
  54117. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54118. };
  54119. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54120. var result = Ray.Zero();
  54121. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54122. };
  54123. /**
  54124. * 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
  54125. * transformed to the given world matrix.
  54126. * @param origin The origin point
  54127. * @param end The end point
  54128. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54129. */
  54130. Ray.CreateNewFromTo = function (origin, end, world) {
  54131. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54132. var direction = end.subtract(origin);
  54133. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54134. direction.normalize();
  54135. return Ray.Transform(new Ray(origin, direction, length), world);
  54136. };
  54137. Ray.Transform = function (ray, matrix) {
  54138. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54139. Ray.TransformToRef(ray, matrix, result);
  54140. return result;
  54141. };
  54142. Ray.TransformToRef = function (ray, matrix, result) {
  54143. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54144. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54145. result.length = ray.length;
  54146. var dir = result.direction;
  54147. var len = dir.length();
  54148. if (!(len === 0 || len === 1)) {
  54149. var num = 1.0 / len;
  54150. dir.x *= num;
  54151. dir.y *= num;
  54152. dir.z *= num;
  54153. result.length *= len;
  54154. }
  54155. };
  54156. Ray.smallnum = 0.00000001;
  54157. Ray.rayl = 10e8;
  54158. return Ray;
  54159. }());
  54160. BABYLON.Ray = Ray;
  54161. })(BABYLON || (BABYLON = {}));
  54162. //# sourceMappingURL=babylon.ray.js.map
  54163. var BABYLON;
  54164. (function (BABYLON) {
  54165. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54166. if (boxMin.x > sphereCenter.x + sphereRadius)
  54167. return false;
  54168. if (sphereCenter.x - sphereRadius > boxMax.x)
  54169. return false;
  54170. if (boxMin.y > sphereCenter.y + sphereRadius)
  54171. return false;
  54172. if (sphereCenter.y - sphereRadius > boxMax.y)
  54173. return false;
  54174. if (boxMin.z > sphereCenter.z + sphereRadius)
  54175. return false;
  54176. if (sphereCenter.z - sphereRadius > boxMax.z)
  54177. return false;
  54178. return true;
  54179. };
  54180. var getLowestRoot = (function () {
  54181. var result = { root: 0, found: false };
  54182. return function (a, b, c, maxR) {
  54183. result.root = 0;
  54184. result.found = false;
  54185. var determinant = b * b - 4.0 * a * c;
  54186. if (determinant < 0)
  54187. return result;
  54188. var sqrtD = Math.sqrt(determinant);
  54189. var r1 = (-b - sqrtD) / (2.0 * a);
  54190. var r2 = (-b + sqrtD) / (2.0 * a);
  54191. if (r1 > r2) {
  54192. var temp = r2;
  54193. r2 = r1;
  54194. r1 = temp;
  54195. }
  54196. if (r1 > 0 && r1 < maxR) {
  54197. result.root = r1;
  54198. result.found = true;
  54199. return result;
  54200. }
  54201. if (r2 > 0 && r2 < maxR) {
  54202. result.root = r2;
  54203. result.found = true;
  54204. return result;
  54205. }
  54206. return result;
  54207. };
  54208. })();
  54209. var Collider = /** @class */ (function () {
  54210. function Collider() {
  54211. this._collisionPoint = BABYLON.Vector3.Zero();
  54212. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54213. this._tempVector = BABYLON.Vector3.Zero();
  54214. this._tempVector2 = BABYLON.Vector3.Zero();
  54215. this._tempVector3 = BABYLON.Vector3.Zero();
  54216. this._tempVector4 = BABYLON.Vector3.Zero();
  54217. this._edge = BABYLON.Vector3.Zero();
  54218. this._baseToVertex = BABYLON.Vector3.Zero();
  54219. this._destinationPoint = BABYLON.Vector3.Zero();
  54220. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54221. this._displacementVector = BABYLON.Vector3.Zero();
  54222. this._radius = BABYLON.Vector3.One();
  54223. this._retry = 0;
  54224. this._basePointWorld = BABYLON.Vector3.Zero();
  54225. this._velocityWorld = BABYLON.Vector3.Zero();
  54226. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54227. this._collisionMask = -1;
  54228. }
  54229. Object.defineProperty(Collider.prototype, "collisionMask", {
  54230. get: function () {
  54231. return this._collisionMask;
  54232. },
  54233. set: function (mask) {
  54234. this._collisionMask = !isNaN(mask) ? mask : -1;
  54235. },
  54236. enumerable: true,
  54237. configurable: true
  54238. });
  54239. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54240. /**
  54241. * Gets the plane normal used to compute the sliding response (in local space)
  54242. */
  54243. get: function () {
  54244. return this._slidePlaneNormal;
  54245. },
  54246. enumerable: true,
  54247. configurable: true
  54248. });
  54249. // Methods
  54250. Collider.prototype._initialize = function (source, dir, e) {
  54251. this._velocity = dir;
  54252. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54253. this._basePoint = source;
  54254. source.multiplyToRef(this._radius, this._basePointWorld);
  54255. dir.multiplyToRef(this._radius, this._velocityWorld);
  54256. this._velocityWorldLength = this._velocityWorld.length();
  54257. this._epsilon = e;
  54258. this.collisionFound = false;
  54259. };
  54260. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54261. pa.subtractToRef(point, this._tempVector);
  54262. pb.subtractToRef(point, this._tempVector2);
  54263. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54264. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54265. if (d < 0)
  54266. return false;
  54267. pc.subtractToRef(point, this._tempVector3);
  54268. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54269. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54270. if (d < 0)
  54271. return false;
  54272. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54273. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54274. return d >= 0;
  54275. };
  54276. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54277. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54278. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54279. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54280. return false;
  54281. }
  54282. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54283. return false;
  54284. return true;
  54285. };
  54286. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54287. var t0;
  54288. var embeddedInPlane = false;
  54289. //defensive programming, actually not needed.
  54290. if (!trianglePlaneArray) {
  54291. trianglePlaneArray = [];
  54292. }
  54293. if (!trianglePlaneArray[faceIndex]) {
  54294. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54295. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54296. }
  54297. var trianglePlane = trianglePlaneArray[faceIndex];
  54298. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54299. return;
  54300. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54301. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54302. if (normalDotVelocity == 0) {
  54303. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54304. return;
  54305. embeddedInPlane = true;
  54306. t0 = 0;
  54307. }
  54308. else {
  54309. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54310. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54311. if (t0 > t1) {
  54312. var temp = t1;
  54313. t1 = t0;
  54314. t0 = temp;
  54315. }
  54316. if (t0 > 1.0 || t1 < 0.0)
  54317. return;
  54318. if (t0 < 0)
  54319. t0 = 0;
  54320. if (t0 > 1.0)
  54321. t0 = 1.0;
  54322. }
  54323. this._collisionPoint.copyFromFloats(0, 0, 0);
  54324. var found = false;
  54325. var t = 1.0;
  54326. if (!embeddedInPlane) {
  54327. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54328. this._velocity.scaleToRef(t0, this._tempVector);
  54329. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54330. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54331. found = true;
  54332. t = t0;
  54333. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54334. }
  54335. }
  54336. if (!found) {
  54337. var velocitySquaredLength = this._velocity.lengthSquared();
  54338. var a = velocitySquaredLength;
  54339. this._basePoint.subtractToRef(p1, this._tempVector);
  54340. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54341. var c = this._tempVector.lengthSquared() - 1.0;
  54342. var lowestRoot = getLowestRoot(a, b, c, t);
  54343. if (lowestRoot.found) {
  54344. t = lowestRoot.root;
  54345. found = true;
  54346. this._collisionPoint.copyFrom(p1);
  54347. }
  54348. this._basePoint.subtractToRef(p2, this._tempVector);
  54349. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54350. c = this._tempVector.lengthSquared() - 1.0;
  54351. lowestRoot = getLowestRoot(a, b, c, t);
  54352. if (lowestRoot.found) {
  54353. t = lowestRoot.root;
  54354. found = true;
  54355. this._collisionPoint.copyFrom(p2);
  54356. }
  54357. this._basePoint.subtractToRef(p3, this._tempVector);
  54358. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54359. c = this._tempVector.lengthSquared() - 1.0;
  54360. lowestRoot = getLowestRoot(a, b, c, t);
  54361. if (lowestRoot.found) {
  54362. t = lowestRoot.root;
  54363. found = true;
  54364. this._collisionPoint.copyFrom(p3);
  54365. }
  54366. p2.subtractToRef(p1, this._edge);
  54367. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54368. var edgeSquaredLength = this._edge.lengthSquared();
  54369. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54370. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54371. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54372. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54373. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54374. lowestRoot = getLowestRoot(a, b, c, t);
  54375. if (lowestRoot.found) {
  54376. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54377. if (f >= 0.0 && f <= 1.0) {
  54378. t = lowestRoot.root;
  54379. found = true;
  54380. this._edge.scaleInPlace(f);
  54381. p1.addToRef(this._edge, this._collisionPoint);
  54382. }
  54383. }
  54384. p3.subtractToRef(p2, this._edge);
  54385. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54386. edgeSquaredLength = this._edge.lengthSquared();
  54387. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54388. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54389. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54390. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54391. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54392. lowestRoot = getLowestRoot(a, b, c, t);
  54393. if (lowestRoot.found) {
  54394. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54395. if (f >= 0.0 && f <= 1.0) {
  54396. t = lowestRoot.root;
  54397. found = true;
  54398. this._edge.scaleInPlace(f);
  54399. p2.addToRef(this._edge, this._collisionPoint);
  54400. }
  54401. }
  54402. p1.subtractToRef(p3, this._edge);
  54403. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54404. edgeSquaredLength = this._edge.lengthSquared();
  54405. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54406. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54407. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54408. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54409. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54410. lowestRoot = getLowestRoot(a, b, c, t);
  54411. if (lowestRoot.found) {
  54412. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54413. if (f >= 0.0 && f <= 1.0) {
  54414. t = lowestRoot.root;
  54415. found = true;
  54416. this._edge.scaleInPlace(f);
  54417. p3.addToRef(this._edge, this._collisionPoint);
  54418. }
  54419. }
  54420. }
  54421. if (found) {
  54422. var distToCollision = t * this._velocity.length();
  54423. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54424. if (!this.intersectionPoint) {
  54425. this.intersectionPoint = this._collisionPoint.clone();
  54426. }
  54427. else {
  54428. this.intersectionPoint.copyFrom(this._collisionPoint);
  54429. }
  54430. this._nearestDistance = distToCollision;
  54431. this.collisionFound = true;
  54432. }
  54433. }
  54434. };
  54435. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54436. for (var i = indexStart; i < indexEnd; i += 3) {
  54437. var p1 = pts[indices[i] - decal];
  54438. var p2 = pts[indices[i + 1] - decal];
  54439. var p3 = pts[indices[i + 2] - decal];
  54440. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54441. }
  54442. };
  54443. Collider.prototype._getResponse = function (pos, vel) {
  54444. pos.addToRef(vel, this._destinationPoint);
  54445. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54446. this._basePoint.addToRef(vel, pos);
  54447. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54448. this._slidePlaneNormal.normalize();
  54449. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54450. pos.addInPlace(this._displacementVector);
  54451. this.intersectionPoint.addInPlace(this._displacementVector);
  54452. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54453. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54454. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54455. };
  54456. return Collider;
  54457. }());
  54458. BABYLON.Collider = Collider;
  54459. })(BABYLON || (BABYLON = {}));
  54460. //# sourceMappingURL=babylon.collider.js.map
  54461. var BABYLON;
  54462. (function (BABYLON) {
  54463. //WebWorker code will be inserted to this variable.
  54464. BABYLON.CollisionWorker = "";
  54465. /** Defines supported task for worker process */
  54466. var WorkerTaskType;
  54467. (function (WorkerTaskType) {
  54468. /** Initialization */
  54469. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54470. /** Update of geometry */
  54471. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54472. /** Evaluate collision */
  54473. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54474. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54475. /** Defines kind of replies returned by worker */
  54476. var WorkerReplyType;
  54477. (function (WorkerReplyType) {
  54478. /** Success */
  54479. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54480. /** Unkown error */
  54481. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54482. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54483. var CollisionCoordinatorWorker = /** @class */ (function () {
  54484. function CollisionCoordinatorWorker() {
  54485. var _this = this;
  54486. this._scaledPosition = BABYLON.Vector3.Zero();
  54487. this._scaledVelocity = BABYLON.Vector3.Zero();
  54488. this.onMeshUpdated = function (transformNode) {
  54489. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54490. };
  54491. this.onGeometryUpdated = function (geometry) {
  54492. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54493. };
  54494. this._afterRender = function () {
  54495. if (!_this._init)
  54496. return;
  54497. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54498. return;
  54499. }
  54500. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54501. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54502. if (_this._runningUpdated > 4) {
  54503. return;
  54504. }
  54505. ++_this._runningUpdated;
  54506. var payload = {
  54507. updatedMeshes: _this._addUpdateMeshesList,
  54508. updatedGeometries: _this._addUpdateGeometriesList,
  54509. removedGeometries: _this._toRemoveGeometryArray,
  54510. removedMeshes: _this._toRemoveMeshesArray
  54511. };
  54512. var message = {
  54513. payload: payload,
  54514. taskType: WorkerTaskType.UPDATE
  54515. };
  54516. var serializable = [];
  54517. for (var id in payload.updatedGeometries) {
  54518. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54519. //prepare transferables
  54520. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54521. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54522. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54523. }
  54524. }
  54525. _this._worker.postMessage(message, serializable);
  54526. _this._addUpdateMeshesList = {};
  54527. _this._addUpdateGeometriesList = {};
  54528. _this._toRemoveGeometryArray = [];
  54529. _this._toRemoveMeshesArray = [];
  54530. };
  54531. this._onMessageFromWorker = function (e) {
  54532. var returnData = e.data;
  54533. if (returnData.error != WorkerReplyType.SUCCESS) {
  54534. //TODO what errors can be returned from the worker?
  54535. BABYLON.Tools.Warn("error returned from worker!");
  54536. return;
  54537. }
  54538. switch (returnData.taskType) {
  54539. case WorkerTaskType.INIT:
  54540. _this._init = true;
  54541. //Update the worked with ALL of the scene's current state
  54542. _this._scene.meshes.forEach(function (mesh) {
  54543. _this.onMeshAdded(mesh);
  54544. });
  54545. _this._scene.getGeometries().forEach(function (geometry) {
  54546. _this.onGeometryAdded(geometry);
  54547. });
  54548. break;
  54549. case WorkerTaskType.UPDATE:
  54550. _this._runningUpdated--;
  54551. break;
  54552. case WorkerTaskType.COLLIDE:
  54553. var returnPayload = returnData.payload;
  54554. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54555. return;
  54556. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54557. if (callback) {
  54558. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54559. if (mesh) {
  54560. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54561. }
  54562. }
  54563. //cleanup
  54564. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54565. break;
  54566. }
  54567. };
  54568. this._collisionsCallbackArray = [];
  54569. this._init = false;
  54570. this._runningUpdated = 0;
  54571. this._addUpdateMeshesList = {};
  54572. this._addUpdateGeometriesList = {};
  54573. this._toRemoveGeometryArray = [];
  54574. this._toRemoveMeshesArray = [];
  54575. }
  54576. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54577. if (!this._init)
  54578. return;
  54579. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54580. return;
  54581. position.divideToRef(collider._radius, this._scaledPosition);
  54582. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54583. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54584. var payload = {
  54585. collider: {
  54586. position: this._scaledPosition.asArray(),
  54587. velocity: this._scaledVelocity.asArray(),
  54588. radius: collider._radius.asArray()
  54589. },
  54590. collisionId: collisionIndex,
  54591. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54592. maximumRetry: maximumRetry
  54593. };
  54594. var message = {
  54595. payload: payload,
  54596. taskType: WorkerTaskType.COLLIDE
  54597. };
  54598. this._worker.postMessage(message);
  54599. };
  54600. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54601. this._scene = scene;
  54602. this._scene.registerAfterRender(this._afterRender);
  54603. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54604. this._worker = new Worker(workerUrl);
  54605. this._worker.onmessage = this._onMessageFromWorker;
  54606. var message = {
  54607. payload: {},
  54608. taskType: WorkerTaskType.INIT
  54609. };
  54610. this._worker.postMessage(message);
  54611. };
  54612. CollisionCoordinatorWorker.prototype.destroy = function () {
  54613. this._scene.unregisterAfterRender(this._afterRender);
  54614. this._worker.terminate();
  54615. };
  54616. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54617. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54618. this.onMeshUpdated(mesh);
  54619. };
  54620. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54621. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54622. };
  54623. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54624. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54625. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54626. this.onGeometryUpdated(geometry);
  54627. };
  54628. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54629. this._toRemoveGeometryArray.push(geometry.id);
  54630. };
  54631. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54632. var submeshes = [];
  54633. if (mesh.subMeshes) {
  54634. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54635. var boundingInfo = sm.getBoundingInfo();
  54636. return {
  54637. position: idx,
  54638. verticesStart: sm.verticesStart,
  54639. verticesCount: sm.verticesCount,
  54640. indexStart: sm.indexStart,
  54641. indexCount: sm.indexCount,
  54642. hasMaterial: !!sm.getMaterial(),
  54643. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54644. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54645. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54646. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54647. };
  54648. });
  54649. }
  54650. var geometryId = null;
  54651. if (mesh instanceof BABYLON.Mesh) {
  54652. var geometry = mesh.geometry;
  54653. geometryId = geometry ? geometry.id : null;
  54654. }
  54655. else if (mesh instanceof BABYLON.InstancedMesh) {
  54656. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54657. geometryId = geometry ? geometry.id : null;
  54658. }
  54659. var boundingInfo = mesh.getBoundingInfo();
  54660. return {
  54661. uniqueId: mesh.uniqueId,
  54662. id: mesh.id,
  54663. name: mesh.name,
  54664. geometryId: geometryId,
  54665. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54666. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54667. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54668. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54669. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54670. subMeshes: submeshes,
  54671. checkCollisions: mesh.checkCollisions
  54672. };
  54673. };
  54674. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54675. return {
  54676. id: geometry.id,
  54677. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54678. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54679. indices: new Uint32Array(geometry.getIndices() || []),
  54680. };
  54681. };
  54682. return CollisionCoordinatorWorker;
  54683. }());
  54684. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54685. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54686. function CollisionCoordinatorLegacy() {
  54687. this._scaledPosition = BABYLON.Vector3.Zero();
  54688. this._scaledVelocity = BABYLON.Vector3.Zero();
  54689. this._finalPosition = BABYLON.Vector3.Zero();
  54690. }
  54691. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54692. position.divideToRef(collider._radius, this._scaledPosition);
  54693. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54694. collider.collidedMesh = null;
  54695. collider._retry = 0;
  54696. collider._initialVelocity = this._scaledVelocity;
  54697. collider._initialPosition = this._scaledPosition;
  54698. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54699. this._finalPosition.multiplyInPlace(collider._radius);
  54700. //run the callback
  54701. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54702. };
  54703. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54704. this._scene = scene;
  54705. };
  54706. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54707. //Legacy need no destruction method.
  54708. };
  54709. //No update in legacy mode
  54710. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54711. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54712. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54713. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54714. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54715. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54716. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54717. if (excludedMesh === void 0) { excludedMesh = null; }
  54718. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54719. if (collider._retry >= maximumRetry) {
  54720. finalPosition.copyFrom(position);
  54721. return;
  54722. }
  54723. // Check if this is a mesh else camera or -1
  54724. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54725. collider._initialize(position, velocity, closeDistance);
  54726. // Check all meshes
  54727. for (var index = 0; index < this._scene.meshes.length; index++) {
  54728. var mesh = this._scene.meshes[index];
  54729. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54730. mesh._checkCollision(collider);
  54731. }
  54732. }
  54733. if (!collider.collisionFound) {
  54734. position.addToRef(velocity, finalPosition);
  54735. return;
  54736. }
  54737. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54738. collider._getResponse(position, velocity);
  54739. }
  54740. if (velocity.length() <= closeDistance) {
  54741. finalPosition.copyFrom(position);
  54742. return;
  54743. }
  54744. collider._retry++;
  54745. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54746. };
  54747. return CollisionCoordinatorLegacy;
  54748. }());
  54749. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54750. })(BABYLON || (BABYLON = {}));
  54751. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54752. var BABYLON;
  54753. (function (BABYLON) {
  54754. /**
  54755. * A particle represents one of the element emitted by a particle system.
  54756. * This is mainly define by its coordinates, direction, velocity and age.
  54757. */
  54758. var Particle = /** @class */ (function () {
  54759. /**
  54760. * Creates a new instance Particle
  54761. * @param particleSystem the particle system the particle belongs to
  54762. */
  54763. function Particle(
  54764. /**
  54765. * particleSystem the particle system the particle belongs to.
  54766. */
  54767. particleSystem) {
  54768. this.particleSystem = particleSystem;
  54769. /**
  54770. * The world position of the particle in the scene.
  54771. */
  54772. this.position = BABYLON.Vector3.Zero();
  54773. /**
  54774. * The world direction of the particle in the scene.
  54775. */
  54776. this.direction = BABYLON.Vector3.Zero();
  54777. /**
  54778. * The color of the particle.
  54779. */
  54780. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54781. /**
  54782. * The color change of the particle per step.
  54783. */
  54784. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54785. /**
  54786. * Defines how long will the life of the particle be.
  54787. */
  54788. this.lifeTime = 1.0;
  54789. /**
  54790. * The current age of the particle.
  54791. */
  54792. this.age = 0;
  54793. /**
  54794. * The current size of the particle.
  54795. */
  54796. this.size = 0;
  54797. /**
  54798. * The current scale of the particle.
  54799. */
  54800. this.scale = new BABYLON.Vector2(1, 1);
  54801. /**
  54802. * The current angle of the particle.
  54803. */
  54804. this.angle = 0;
  54805. /**
  54806. * Defines how fast is the angle changing.
  54807. */
  54808. this.angularSpeed = 0;
  54809. /**
  54810. * Defines the cell index used by the particle to be rendered from a sprite.
  54811. */
  54812. this.cellIndex = 0;
  54813. this._currentFrameCounter = 0;
  54814. if (!this.particleSystem.isAnimationSheetEnabled) {
  54815. return;
  54816. }
  54817. this.updateCellInfoFromSystem();
  54818. }
  54819. Particle.prototype.updateCellInfoFromSystem = function () {
  54820. this.cellIndex = this.particleSystem.startSpriteCellID;
  54821. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54822. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54823. }
  54824. else {
  54825. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54826. }
  54827. };
  54828. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54829. // (ageOffset / scaledUpdateSpeed) / available cells
  54830. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54831. this._currentFrameCounter += scaledUpdateSpeed;
  54832. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54833. this._currentFrameCounter = 0;
  54834. this.cellIndex++;
  54835. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54836. this.cellIndex = this.particleSystem.endSpriteCellID;
  54837. }
  54838. }
  54839. };
  54840. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54841. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54842. this.cellIndex++;
  54843. this._currentFrameCounter = 0;
  54844. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54845. if (this.particleSystem.spriteCellLoop) {
  54846. this.cellIndex = this.particleSystem.startSpriteCellID;
  54847. }
  54848. else {
  54849. this.cellIndex = this.particleSystem.endSpriteCellID;
  54850. }
  54851. }
  54852. }
  54853. else {
  54854. this._currentFrameCounter++;
  54855. }
  54856. };
  54857. /**
  54858. * Copy the properties of particle to another one.
  54859. * @param other the particle to copy the information to.
  54860. */
  54861. Particle.prototype.copyTo = function (other) {
  54862. other.position.copyFrom(this.position);
  54863. other.direction.copyFrom(this.direction);
  54864. other.color.copyFrom(this.color);
  54865. other.colorStep.copyFrom(this.colorStep);
  54866. other.lifeTime = this.lifeTime;
  54867. other.age = this.age;
  54868. other.size = this.size;
  54869. other.scale.copyFrom(this.scale);
  54870. other.angle = this.angle;
  54871. other.angularSpeed = this.angularSpeed;
  54872. other.particleSystem = this.particleSystem;
  54873. other.cellIndex = this.cellIndex;
  54874. };
  54875. return Particle;
  54876. }());
  54877. BABYLON.Particle = Particle;
  54878. })(BABYLON || (BABYLON = {}));
  54879. //# sourceMappingURL=babylon.particle.js.map
  54880. var BABYLON;
  54881. (function (BABYLON) {
  54882. /**
  54883. * This represents a particle system in Babylon.
  54884. * 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.
  54885. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54886. * @example https://doc.babylonjs.com/babylon101/particles
  54887. */
  54888. var ParticleSystem = /** @class */ (function () {
  54889. /**
  54890. * Instantiates a particle system.
  54891. * 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.
  54892. * @param name The name of the particle system
  54893. * @param capacity The max number of particles alive at the same time
  54894. * @param scene The scene the particle system belongs to
  54895. * @param customEffect a custom effect used to change the way particles are rendered by default
  54896. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54897. * @param epsilon Offset used to render the particles
  54898. */
  54899. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54900. if (customEffect === void 0) { customEffect = null; }
  54901. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54902. if (epsilon === void 0) { epsilon = 0.01; }
  54903. var _this = this;
  54904. /**
  54905. * List of animations used by the particle system.
  54906. */
  54907. this.animations = [];
  54908. /**
  54909. * The rendering group used by the Particle system to chose when to render.
  54910. */
  54911. this.renderingGroupId = 0;
  54912. /**
  54913. * The emitter represents the Mesh or position we are attaching the particle system to.
  54914. */
  54915. this.emitter = null;
  54916. /**
  54917. * The maximum number of particles to emit per frame
  54918. */
  54919. this.emitRate = 10;
  54920. /**
  54921. * If you want to launch only a few particles at once, that can be done, as well.
  54922. */
  54923. this.manualEmitCount = -1;
  54924. /**
  54925. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54926. */
  54927. this.updateSpeed = 0.01;
  54928. /**
  54929. * The amount of time the particle system is running (depends of the overall update speed).
  54930. */
  54931. this.targetStopDuration = 0;
  54932. /**
  54933. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54934. */
  54935. this.disposeOnStop = false;
  54936. /**
  54937. * Minimum power of emitting particles.
  54938. */
  54939. this.minEmitPower = 1;
  54940. /**
  54941. * Maximum power of emitting particles.
  54942. */
  54943. this.maxEmitPower = 1;
  54944. /**
  54945. * Minimum life time of emitting particles.
  54946. */
  54947. this.minLifeTime = 1;
  54948. /**
  54949. * Maximum life time of emitting particles.
  54950. */
  54951. this.maxLifeTime = 1;
  54952. /**
  54953. * Minimum Size of emitting particles.
  54954. */
  54955. this.minSize = 1;
  54956. /**
  54957. * Maximum Size of emitting particles.
  54958. */
  54959. this.maxSize = 1;
  54960. /**
  54961. * Minimum scale of emitting particles on X axis.
  54962. */
  54963. this.minScaleX = 1;
  54964. /**
  54965. * Maximum scale of emitting particles on X axis.
  54966. */
  54967. this.maxScaleX = 1;
  54968. /**
  54969. * Minimum scale of emitting particles on Y axis.
  54970. */
  54971. this.minScaleY = 1;
  54972. /**
  54973. * Maximum scale of emitting particles on Y axis.
  54974. */
  54975. this.maxScaleY = 1;
  54976. /**
  54977. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54978. */
  54979. this.minAngularSpeed = 0;
  54980. /**
  54981. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54982. */
  54983. this.maxAngularSpeed = 0;
  54984. /**
  54985. * The layer mask we are rendering the particles through.
  54986. */
  54987. this.layerMask = 0x0FFFFFFF;
  54988. /**
  54989. * This can help using your own shader to render the particle system.
  54990. * The according effect will be created
  54991. */
  54992. this.customShader = null;
  54993. /**
  54994. * By default particle system starts as soon as they are created. This prevents the
  54995. * automatic start to happen and let you decide when to start emitting particles.
  54996. */
  54997. this.preventAutoStart = false;
  54998. /**
  54999. * Callback triggered when the particle animation is ending.
  55000. */
  55001. this.onAnimationEnd = null;
  55002. /**
  55003. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55004. */
  55005. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55006. /**
  55007. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55008. * to override the particles.
  55009. */
  55010. this.forceDepthWrite = false;
  55011. /**
  55012. * You can use gravity if you want to give an orientation to your particles.
  55013. */
  55014. this.gravity = BABYLON.Vector3.Zero();
  55015. /**
  55016. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55017. */
  55018. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55019. /**
  55020. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55021. */
  55022. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55023. /**
  55024. * Color the particle will have at the end of its lifetime.
  55025. */
  55026. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55027. /**
  55028. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55029. */
  55030. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55031. /**
  55032. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55033. */
  55034. this.spriteCellLoop = true;
  55035. /**
  55036. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55037. */
  55038. this.spriteCellChangeSpeed = 0;
  55039. /**
  55040. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55041. */
  55042. this.startSpriteCellID = 0;
  55043. /**
  55044. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55045. */
  55046. this.endSpriteCellID = 0;
  55047. /**
  55048. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55049. */
  55050. this.spriteCellWidth = 0;
  55051. /**
  55052. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55053. */
  55054. this.spriteCellHeight = 0;
  55055. /**
  55056. * An event triggered when the system is disposed.
  55057. */
  55058. this.onDisposeObservable = new BABYLON.Observable();
  55059. this._particles = new Array();
  55060. this._stockParticles = new Array();
  55061. this._newPartsExcess = 0;
  55062. this._vertexBuffers = {};
  55063. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55064. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55065. this._scaledDirection = BABYLON.Vector3.Zero();
  55066. this._scaledGravity = BABYLON.Vector3.Zero();
  55067. this._currentRenderId = -1;
  55068. this._started = false;
  55069. this._stopped = false;
  55070. this._actualFrame = 0;
  55071. this._vertexBufferSize = 12;
  55072. // start of sub system methods
  55073. /**
  55074. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55075. * Its lifetime will start back at 0.
  55076. */
  55077. this.recycleParticle = function (particle) {
  55078. var lastParticle = _this._particles.pop();
  55079. if (lastParticle !== particle) {
  55080. lastParticle.copyTo(particle);
  55081. }
  55082. _this._stockParticles.push(lastParticle);
  55083. };
  55084. this._createParticle = function () {
  55085. var particle;
  55086. if (_this._stockParticles.length !== 0) {
  55087. particle = _this._stockParticles.pop();
  55088. particle.age = 0;
  55089. particle.cellIndex = _this.startSpriteCellID;
  55090. }
  55091. else {
  55092. particle = new BABYLON.Particle(_this);
  55093. }
  55094. return particle;
  55095. };
  55096. this._emitFromParticle = function (particle) {
  55097. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55098. return;
  55099. }
  55100. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55101. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55102. subSystem._rootParticleSystem = _this;
  55103. _this.activeSubSystems.push(subSystem);
  55104. subSystem.start();
  55105. };
  55106. this._appendParticleVertexes = null;
  55107. this.id = name;
  55108. this.name = name;
  55109. this._capacity = capacity;
  55110. this._epsilon = epsilon;
  55111. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55112. if (isAnimationSheetEnabled) {
  55113. this._vertexBufferSize = 13;
  55114. }
  55115. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55116. this._customEffect = customEffect;
  55117. scene.particleSystems.push(this);
  55118. this._createIndexBuffer();
  55119. // 13 floats per particle (x, y, z, r, g, b, a, angle, scaleX, scaleY, offsetX, offsetY) + 1 filler
  55120. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55121. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55122. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55123. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55124. var options = this._vertexBuffer.createVertexBuffer("options", 7, 3);
  55125. var size = this._vertexBuffer.createVertexBuffer("size", 10, 2);
  55126. if (this._isAnimationSheetEnabled) {
  55127. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 12, 1);
  55128. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55129. }
  55130. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55131. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55132. this._vertexBuffers["options"] = options;
  55133. this._vertexBuffers["size"] = size;
  55134. // Default emitter type
  55135. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55136. this.updateFunction = function (particles) {
  55137. for (var index = 0; index < particles.length; index++) {
  55138. var particle = particles[index];
  55139. particle.age += _this._scaledUpdateSpeed;
  55140. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55141. _this._emitFromParticle(particle);
  55142. _this.recycleParticle(particle);
  55143. index--;
  55144. continue;
  55145. }
  55146. else {
  55147. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55148. particle.color.addInPlace(_this._scaledColorStep);
  55149. if (particle.color.a < 0)
  55150. particle.color.a = 0;
  55151. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55152. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55153. particle.position.addInPlace(_this._scaledDirection);
  55154. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55155. particle.direction.addInPlace(_this._scaledGravity);
  55156. if (_this._isAnimationSheetEnabled) {
  55157. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55158. }
  55159. }
  55160. }
  55161. };
  55162. }
  55163. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55164. /**
  55165. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55166. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55167. */
  55168. get: function () {
  55169. if (this.particleEmitterType.direction1) {
  55170. return this.particleEmitterType.direction1;
  55171. }
  55172. return BABYLON.Vector3.Zero();
  55173. },
  55174. set: function (value) {
  55175. if (this.particleEmitterType.direction1) {
  55176. this.particleEmitterType.direction1 = value;
  55177. }
  55178. },
  55179. enumerable: true,
  55180. configurable: true
  55181. });
  55182. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55183. /**
  55184. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55185. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55186. */
  55187. get: function () {
  55188. if (this.particleEmitterType.direction2) {
  55189. return this.particleEmitterType.direction2;
  55190. }
  55191. return BABYLON.Vector3.Zero();
  55192. },
  55193. set: function (value) {
  55194. if (this.particleEmitterType.direction2) {
  55195. this.particleEmitterType.direction2 = value;
  55196. }
  55197. },
  55198. enumerable: true,
  55199. configurable: true
  55200. });
  55201. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55202. /**
  55203. * 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.
  55204. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55205. */
  55206. get: function () {
  55207. if (this.particleEmitterType.minEmitBox) {
  55208. return this.particleEmitterType.minEmitBox;
  55209. }
  55210. return BABYLON.Vector3.Zero();
  55211. },
  55212. set: function (value) {
  55213. if (this.particleEmitterType.minEmitBox) {
  55214. this.particleEmitterType.minEmitBox = value;
  55215. }
  55216. },
  55217. enumerable: true,
  55218. configurable: true
  55219. });
  55220. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55221. /**
  55222. * 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.
  55223. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55224. */
  55225. get: function () {
  55226. if (this.particleEmitterType.maxEmitBox) {
  55227. return this.particleEmitterType.maxEmitBox;
  55228. }
  55229. return BABYLON.Vector3.Zero();
  55230. },
  55231. set: function (value) {
  55232. if (this.particleEmitterType.maxEmitBox) {
  55233. this.particleEmitterType.maxEmitBox = value;
  55234. }
  55235. },
  55236. enumerable: true,
  55237. configurable: true
  55238. });
  55239. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55240. /**
  55241. * Sets a callback that will be triggered when the system is disposed.
  55242. */
  55243. set: function (callback) {
  55244. if (this._onDisposeObserver) {
  55245. this.onDisposeObservable.remove(this._onDisposeObserver);
  55246. }
  55247. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55248. },
  55249. enumerable: true,
  55250. configurable: true
  55251. });
  55252. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55253. /**
  55254. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55255. */
  55256. get: function () {
  55257. return this._isAnimationSheetEnabled;
  55258. },
  55259. enumerable: true,
  55260. configurable: true
  55261. });
  55262. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55263. //end of Sub-emitter
  55264. /**
  55265. * Gets the current list of active particles
  55266. */
  55267. get: function () {
  55268. return this._particles;
  55269. },
  55270. enumerable: true,
  55271. configurable: true
  55272. });
  55273. /**
  55274. * Returns the string "ParticleSystem"
  55275. * @returns a string containing the class name
  55276. */
  55277. ParticleSystem.prototype.getClassName = function () {
  55278. return "ParticleSystem";
  55279. };
  55280. ParticleSystem.prototype._createIndexBuffer = function () {
  55281. var indices = [];
  55282. var index = 0;
  55283. for (var count = 0; count < this._capacity; count++) {
  55284. indices.push(index);
  55285. indices.push(index + 1);
  55286. indices.push(index + 2);
  55287. indices.push(index);
  55288. indices.push(index + 2);
  55289. indices.push(index + 3);
  55290. index += 4;
  55291. }
  55292. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55293. };
  55294. /**
  55295. * Gets the maximum number of particles active at the same time.
  55296. * @returns The max number of active particles.
  55297. */
  55298. ParticleSystem.prototype.getCapacity = function () {
  55299. return this._capacity;
  55300. };
  55301. /**
  55302. * Gets Wether there are still active particles in the system.
  55303. * @returns True if it is alive, otherwise false.
  55304. */
  55305. ParticleSystem.prototype.isAlive = function () {
  55306. return this._alive;
  55307. };
  55308. /**
  55309. * Gets Wether the system has been started.
  55310. * @returns True if it has been started, otherwise false.
  55311. */
  55312. ParticleSystem.prototype.isStarted = function () {
  55313. return this._started;
  55314. };
  55315. /**
  55316. * Starts the particle system and begins to emit.
  55317. */
  55318. ParticleSystem.prototype.start = function () {
  55319. this._started = true;
  55320. this._stopped = false;
  55321. this._actualFrame = 0;
  55322. if (this.subEmitters && this.subEmitters.length != 0) {
  55323. this.activeSubSystems = new Array();
  55324. }
  55325. };
  55326. /**
  55327. * Stops the particle system.
  55328. * @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.
  55329. */
  55330. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55331. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55332. this._stopped = true;
  55333. if (stopSubEmitters) {
  55334. this._stopSubEmitters();
  55335. }
  55336. };
  55337. // animation sheet
  55338. /**
  55339. * Remove all active particles
  55340. */
  55341. ParticleSystem.prototype.reset = function () {
  55342. this._stockParticles = [];
  55343. this._particles = [];
  55344. };
  55345. /**
  55346. * @hidden (for internal use only)
  55347. */
  55348. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55349. var offset = index * this._vertexBufferSize;
  55350. this._vertexData[offset] = particle.position.x;
  55351. this._vertexData[offset + 1] = particle.position.y;
  55352. this._vertexData[offset + 2] = particle.position.z;
  55353. this._vertexData[offset + 3] = particle.color.r;
  55354. this._vertexData[offset + 4] = particle.color.g;
  55355. this._vertexData[offset + 5] = particle.color.b;
  55356. this._vertexData[offset + 6] = particle.color.a;
  55357. this._vertexData[offset + 7] = particle.angle;
  55358. this._vertexData[offset + 8] = offsetX;
  55359. this._vertexData[offset + 9] = offsetY;
  55360. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  55361. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  55362. };
  55363. /**
  55364. * @hidden (for internal use only)
  55365. */
  55366. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55367. if (offsetX === 0)
  55368. offsetX = this._epsilon;
  55369. else if (offsetX === 1)
  55370. offsetX = 1 - this._epsilon;
  55371. if (offsetY === 0)
  55372. offsetY = this._epsilon;
  55373. else if (offsetY === 1)
  55374. offsetY = 1 - this._epsilon;
  55375. var offset = index * this._vertexBufferSize;
  55376. this._vertexData[offset] = particle.position.x;
  55377. this._vertexData[offset + 1] = particle.position.y;
  55378. this._vertexData[offset + 2] = particle.position.z;
  55379. this._vertexData[offset + 3] = particle.color.r;
  55380. this._vertexData[offset + 4] = particle.color.g;
  55381. this._vertexData[offset + 5] = particle.color.b;
  55382. this._vertexData[offset + 6] = particle.color.a;
  55383. this._vertexData[offset + 7] = particle.angle;
  55384. this._vertexData[offset + 8] = offsetX;
  55385. this._vertexData[offset + 9] = offsetY;
  55386. this._vertexData[offset + 10] = particle.scale.x * particle.size;
  55387. this._vertexData[offset + 11] = particle.scale.y * particle.size;
  55388. this._vertexData[offset + 12] = particle.cellIndex;
  55389. };
  55390. ParticleSystem.prototype._stopSubEmitters = function () {
  55391. if (!this.activeSubSystems) {
  55392. return;
  55393. }
  55394. this.activeSubSystems.forEach(function (subSystem) {
  55395. subSystem.stop(true);
  55396. });
  55397. this.activeSubSystems = new Array();
  55398. };
  55399. ParticleSystem.prototype._removeFromRoot = function () {
  55400. if (!this._rootParticleSystem) {
  55401. return;
  55402. }
  55403. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55404. if (index !== -1) {
  55405. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55406. }
  55407. };
  55408. // end of sub system methods
  55409. ParticleSystem.prototype._update = function (newParticles) {
  55410. // Update current
  55411. this._alive = this._particles.length > 0;
  55412. this.updateFunction(this._particles);
  55413. // Add new ones
  55414. var worldMatrix;
  55415. if (this.emitter.position) {
  55416. var emitterMesh = this.emitter;
  55417. worldMatrix = emitterMesh.getWorldMatrix();
  55418. }
  55419. else {
  55420. var emitterPosition = this.emitter;
  55421. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55422. }
  55423. var particle;
  55424. for (var index = 0; index < newParticles; index++) {
  55425. if (this._particles.length === this._capacity) {
  55426. break;
  55427. }
  55428. particle = this._createParticle();
  55429. this._particles.push(particle);
  55430. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55431. if (this.startPositionFunction) {
  55432. this.startPositionFunction(worldMatrix, particle.position, particle);
  55433. }
  55434. else {
  55435. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55436. }
  55437. if (this.startDirectionFunction) {
  55438. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55439. }
  55440. else {
  55441. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55442. }
  55443. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55444. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55445. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55446. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55447. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55448. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55449. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55450. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55451. }
  55452. };
  55453. ParticleSystem.prototype._getEffect = function () {
  55454. if (this._customEffect) {
  55455. return this._customEffect;
  55456. }
  55457. ;
  55458. var defines = [];
  55459. if (this._scene.clipPlane) {
  55460. defines.push("#define CLIPPLANE");
  55461. }
  55462. if (this._isAnimationSheetEnabled) {
  55463. defines.push("#define ANIMATESHEET");
  55464. }
  55465. // Effect
  55466. var join = defines.join("\n");
  55467. if (this._cachedDefines !== join) {
  55468. this._cachedDefines = join;
  55469. var attributesNamesOrOptions;
  55470. var effectCreationOption;
  55471. if (this._isAnimationSheetEnabled) {
  55472. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size", "cellIndex"];
  55473. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55474. }
  55475. else {
  55476. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "size",];
  55477. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55478. }
  55479. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55480. }
  55481. return this._effect;
  55482. };
  55483. /**
  55484. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55485. */
  55486. ParticleSystem.prototype.animate = function () {
  55487. if (!this._started)
  55488. return;
  55489. var effect = this._getEffect();
  55490. // Check
  55491. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55492. return;
  55493. if (this._currentRenderId === this._scene.getRenderId()) {
  55494. return;
  55495. }
  55496. this._currentRenderId = this._scene.getRenderId();
  55497. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55498. // determine the number of particles we need to create
  55499. var newParticles;
  55500. if (this.manualEmitCount > -1) {
  55501. newParticles = this.manualEmitCount;
  55502. this._newPartsExcess = 0;
  55503. this.manualEmitCount = 0;
  55504. }
  55505. else {
  55506. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55507. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55508. }
  55509. if (this._newPartsExcess > 1.0) {
  55510. newParticles += this._newPartsExcess >> 0;
  55511. this._newPartsExcess -= this._newPartsExcess >> 0;
  55512. }
  55513. this._alive = false;
  55514. if (!this._stopped) {
  55515. this._actualFrame += this._scaledUpdateSpeed;
  55516. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55517. this.stop();
  55518. }
  55519. else {
  55520. newParticles = 0;
  55521. }
  55522. this._update(newParticles);
  55523. // Stopped?
  55524. if (this._stopped) {
  55525. if (!this._alive) {
  55526. this._started = false;
  55527. if (this.onAnimationEnd) {
  55528. this.onAnimationEnd();
  55529. }
  55530. if (this.disposeOnStop) {
  55531. this._scene._toBeDisposed.push(this);
  55532. }
  55533. }
  55534. }
  55535. // Animation sheet
  55536. if (this._isAnimationSheetEnabled) {
  55537. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55538. }
  55539. else {
  55540. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55541. }
  55542. // Update VBO
  55543. var offset = 0;
  55544. for (var index = 0; index < this._particles.length; index++) {
  55545. var particle = this._particles[index];
  55546. this._appendParticleVertexes(offset, particle);
  55547. offset += 4;
  55548. }
  55549. if (this._vertexBuffer) {
  55550. this._vertexBuffer.update(this._vertexData);
  55551. }
  55552. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55553. this.stop();
  55554. }
  55555. };
  55556. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55557. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55558. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55559. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55560. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55561. };
  55562. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55563. this._appendParticleVertex(offset++, particle, 0, 0);
  55564. this._appendParticleVertex(offset++, particle, 1, 0);
  55565. this._appendParticleVertex(offset++, particle, 1, 1);
  55566. this._appendParticleVertex(offset++, particle, 0, 1);
  55567. };
  55568. /**
  55569. * Rebuilds the particle system.
  55570. */
  55571. ParticleSystem.prototype.rebuild = function () {
  55572. this._createIndexBuffer();
  55573. if (this._vertexBuffer) {
  55574. this._vertexBuffer._rebuild();
  55575. }
  55576. };
  55577. /**
  55578. * Is this system ready to be used/rendered
  55579. * @return true if the system is ready
  55580. */
  55581. ParticleSystem.prototype.isReady = function () {
  55582. var effect = this._getEffect();
  55583. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55584. return false;
  55585. }
  55586. return true;
  55587. };
  55588. /**
  55589. * Renders the particle system in its current state.
  55590. * @returns the current number of particles
  55591. */
  55592. ParticleSystem.prototype.render = function () {
  55593. var effect = this._getEffect();
  55594. // Check
  55595. if (!this.isReady() || !this._particles.length) {
  55596. return 0;
  55597. }
  55598. var engine = this._scene.getEngine();
  55599. // Render
  55600. engine.enableEffect(effect);
  55601. engine.setState(false);
  55602. var viewMatrix = this._scene.getViewMatrix();
  55603. effect.setTexture("diffuseSampler", this.particleTexture);
  55604. effect.setMatrix("view", viewMatrix);
  55605. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55606. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55607. var baseSize = this.particleTexture.getBaseSize();
  55608. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55609. }
  55610. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55611. if (this._scene.clipPlane) {
  55612. var clipPlane = this._scene.clipPlane;
  55613. var invView = viewMatrix.clone();
  55614. invView.invert();
  55615. effect.setMatrix("invView", invView);
  55616. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55617. }
  55618. // VBOs
  55619. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55620. // Draw order
  55621. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55622. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55623. }
  55624. else {
  55625. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55626. }
  55627. if (this.forceDepthWrite) {
  55628. engine.setDepthWrite(true);
  55629. }
  55630. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55631. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55632. return this._particles.length;
  55633. };
  55634. /**
  55635. * Disposes the particle system and free the associated resources
  55636. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55637. */
  55638. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55639. if (disposeTexture === void 0) { disposeTexture = true; }
  55640. if (this._vertexBuffer) {
  55641. this._vertexBuffer.dispose();
  55642. this._vertexBuffer = null;
  55643. }
  55644. if (this._indexBuffer) {
  55645. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55646. this._indexBuffer = null;
  55647. }
  55648. if (disposeTexture && this.particleTexture) {
  55649. this.particleTexture.dispose();
  55650. this.particleTexture = null;
  55651. }
  55652. this._removeFromRoot();
  55653. // Remove from scene
  55654. var index = this._scene.particleSystems.indexOf(this);
  55655. if (index > -1) {
  55656. this._scene.particleSystems.splice(index, 1);
  55657. }
  55658. // Callback
  55659. this.onDisposeObservable.notifyObservers(this);
  55660. this.onDisposeObservable.clear();
  55661. };
  55662. /**
  55663. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55664. * @param radius The radius of the sphere to emit from
  55665. * @returns the emitter
  55666. */
  55667. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55668. if (radius === void 0) { radius = 1; }
  55669. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55670. this.particleEmitterType = particleEmitter;
  55671. return particleEmitter;
  55672. };
  55673. /**
  55674. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55675. * @param radius The radius of the sphere to emit from
  55676. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55677. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55678. * @returns the emitter
  55679. */
  55680. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55681. if (radius === void 0) { radius = 1; }
  55682. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55683. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55684. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55685. this.particleEmitterType = particleEmitter;
  55686. return particleEmitter;
  55687. };
  55688. /**
  55689. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55690. * @param radius The radius of the cone to emit from
  55691. * @param angle The base angle of the cone
  55692. * @returns the emitter
  55693. */
  55694. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55695. if (radius === void 0) { radius = 1; }
  55696. if (angle === void 0) { angle = Math.PI / 4; }
  55697. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55698. this.particleEmitterType = particleEmitter;
  55699. return particleEmitter;
  55700. };
  55701. // 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.
  55702. /**
  55703. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55704. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55705. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55706. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55707. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55708. * @returns the emitter
  55709. */
  55710. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55711. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55712. this.particleEmitterType = particleEmitter;
  55713. this.direction1 = direction1;
  55714. this.direction2 = direction2;
  55715. this.minEmitBox = minEmitBox;
  55716. this.maxEmitBox = maxEmitBox;
  55717. return particleEmitter;
  55718. };
  55719. // Clone
  55720. /**
  55721. * Clones the particle system.
  55722. * @param name The name of the cloned object
  55723. * @param newEmitter The new emitter to use
  55724. * @returns the cloned particle system
  55725. */
  55726. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55727. var custom = null;
  55728. var program = null;
  55729. if (this.customShader != null) {
  55730. program = this.customShader;
  55731. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55732. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55733. }
  55734. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55735. result.customShader = program;
  55736. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55737. if (newEmitter === undefined) {
  55738. newEmitter = this.emitter;
  55739. }
  55740. result.emitter = newEmitter;
  55741. if (this.particleTexture) {
  55742. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55743. }
  55744. if (!this.preventAutoStart) {
  55745. result.start();
  55746. }
  55747. return result;
  55748. };
  55749. /**
  55750. * Serializes the particle system to a JSON object.
  55751. * @returns the JSON object
  55752. */
  55753. ParticleSystem.prototype.serialize = function () {
  55754. var serializationObject = {};
  55755. serializationObject.name = this.name;
  55756. serializationObject.id = this.id;
  55757. // Emitter
  55758. if (this.emitter.position) {
  55759. var emitterMesh = this.emitter;
  55760. serializationObject.emitterId = emitterMesh.id;
  55761. }
  55762. else {
  55763. var emitterPosition = this.emitter;
  55764. serializationObject.emitter = emitterPosition.asArray();
  55765. }
  55766. serializationObject.capacity = this.getCapacity();
  55767. if (this.particleTexture) {
  55768. serializationObject.textureName = this.particleTexture.name;
  55769. }
  55770. // Animations
  55771. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55772. // Particle system
  55773. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55774. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55775. serializationObject.minSize = this.minSize;
  55776. serializationObject.maxSize = this.maxSize;
  55777. serializationObject.minScaleX = this.minScaleX;
  55778. serializationObject.maxScaleX = this.maxScaleX;
  55779. serializationObject.minScaleY = this.minScaleY;
  55780. serializationObject.maxScaleY = this.maxScaleY;
  55781. serializationObject.minEmitPower = this.minEmitPower;
  55782. serializationObject.maxEmitPower = this.maxEmitPower;
  55783. serializationObject.minLifeTime = this.minLifeTime;
  55784. serializationObject.maxLifeTime = this.maxLifeTime;
  55785. serializationObject.emitRate = this.emitRate;
  55786. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55787. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55788. serializationObject.gravity = this.gravity.asArray();
  55789. serializationObject.direction1 = this.direction1.asArray();
  55790. serializationObject.direction2 = this.direction2.asArray();
  55791. serializationObject.color1 = this.color1.asArray();
  55792. serializationObject.color2 = this.color2.asArray();
  55793. serializationObject.colorDead = this.colorDead.asArray();
  55794. serializationObject.updateSpeed = this.updateSpeed;
  55795. serializationObject.targetStopDuration = this.targetStopDuration;
  55796. serializationObject.textureMask = this.textureMask.asArray();
  55797. serializationObject.blendMode = this.blendMode;
  55798. serializationObject.customShader = this.customShader;
  55799. serializationObject.preventAutoStart = this.preventAutoStart;
  55800. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55801. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55802. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55803. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55804. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55805. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55806. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55807. // Emitter
  55808. if (this.particleEmitterType) {
  55809. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55810. }
  55811. return serializationObject;
  55812. };
  55813. /**
  55814. * Parses a JSON object to create a particle system.
  55815. * @param parsedParticleSystem The JSON object to parse
  55816. * @param scene The scene to create the particle system in
  55817. * @param rootUrl The root url to use to load external dependencies like texture
  55818. * @returns the Parsed particle system
  55819. */
  55820. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55821. var name = parsedParticleSystem.name;
  55822. var custom = null;
  55823. var program = null;
  55824. if (parsedParticleSystem.customShader) {
  55825. program = parsedParticleSystem.customShader;
  55826. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55827. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55828. }
  55829. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55830. particleSystem.customShader = program;
  55831. if (parsedParticleSystem.id) {
  55832. particleSystem.id = parsedParticleSystem.id;
  55833. }
  55834. // Auto start
  55835. if (parsedParticleSystem.preventAutoStart) {
  55836. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55837. }
  55838. // Texture
  55839. if (parsedParticleSystem.textureName) {
  55840. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55841. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55842. }
  55843. // Emitter
  55844. if (parsedParticleSystem.emitterId) {
  55845. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55846. }
  55847. else {
  55848. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55849. }
  55850. // Animations
  55851. if (parsedParticleSystem.animations) {
  55852. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55853. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55854. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55855. }
  55856. }
  55857. if (parsedParticleSystem.autoAnimate) {
  55858. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55859. }
  55860. // Particle system
  55861. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55862. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55863. particleSystem.minSize = parsedParticleSystem.minSize;
  55864. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55865. if (parsedParticleSystem.minScaleX) {
  55866. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  55867. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  55868. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  55869. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  55870. }
  55871. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55872. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55873. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55874. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55875. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55876. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55877. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55878. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55879. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55880. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55881. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55882. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55883. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55884. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55885. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55886. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55887. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55888. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55889. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55890. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55891. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55892. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55893. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55894. if (!particleSystem.preventAutoStart) {
  55895. particleSystem.start();
  55896. }
  55897. return particleSystem;
  55898. };
  55899. /**
  55900. * Source color is added to the destination color without alpha affecting the result.
  55901. */
  55902. ParticleSystem.BLENDMODE_ONEONE = 0;
  55903. /**
  55904. * Blend current color and particle color using particle’s alpha.
  55905. */
  55906. ParticleSystem.BLENDMODE_STANDARD = 1;
  55907. return ParticleSystem;
  55908. }());
  55909. BABYLON.ParticleSystem = ParticleSystem;
  55910. })(BABYLON || (BABYLON = {}));
  55911. //# sourceMappingURL=babylon.particleSystem.js.map
  55912. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55913. var BABYLON;
  55914. (function (BABYLON) {
  55915. /**
  55916. * Particle emitter emitting particles from the inside of a box.
  55917. * It emits the particles randomly between 2 given directions.
  55918. */
  55919. var BoxParticleEmitter = /** @class */ (function () {
  55920. /**
  55921. * Creates a new instance BoxParticleEmitter
  55922. */
  55923. function BoxParticleEmitter() {
  55924. /**
  55925. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55926. */
  55927. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55928. /**
  55929. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55930. */
  55931. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55932. /**
  55933. * 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.
  55934. */
  55935. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  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. */
  55939. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55940. }
  55941. /**
  55942. * Called by the particle System when the direction is computed for the created particle.
  55943. * @param emitPower is the power of the particle (speed)
  55944. * @param worldMatrix is the world matrix of the particle system
  55945. * @param directionToUpdate is the direction vector to update with the result
  55946. * @param particle is the particle we are computed the direction for
  55947. */
  55948. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55949. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55950. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55951. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55952. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55953. };
  55954. /**
  55955. * Called by the particle System when the position is computed for the created particle.
  55956. * @param worldMatrix is the world matrix of the particle system
  55957. * @param positionToUpdate is the position vector to update with the result
  55958. * @param particle is the particle we are computed the position for
  55959. */
  55960. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55961. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55962. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55963. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55964. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55965. };
  55966. /**
  55967. * Clones the current emitter and returns a copy of it
  55968. * @returns the new emitter
  55969. */
  55970. BoxParticleEmitter.prototype.clone = function () {
  55971. var newOne = new BoxParticleEmitter();
  55972. BABYLON.Tools.DeepCopy(this, newOne);
  55973. return newOne;
  55974. };
  55975. /**
  55976. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55977. * @param effect defines the update shader
  55978. */
  55979. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55980. effect.setVector3("direction1", this.direction1);
  55981. effect.setVector3("direction2", this.direction2);
  55982. effect.setVector3("minEmitBox", this.minEmitBox);
  55983. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55984. };
  55985. /**
  55986. * Returns a string to use to update the GPU particles update shader
  55987. * @returns a string containng the defines string
  55988. */
  55989. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55990. return "#define BOXEMITTER";
  55991. };
  55992. /**
  55993. * Returns the string "BoxEmitter"
  55994. * @returns a string containing the class name
  55995. */
  55996. BoxParticleEmitter.prototype.getClassName = function () {
  55997. return "BoxEmitter";
  55998. };
  55999. /**
  56000. * Serializes the particle system to a JSON object.
  56001. * @returns the JSON object
  56002. */
  56003. BoxParticleEmitter.prototype.serialize = function () {
  56004. var serializationObject = {};
  56005. serializationObject.type = this.getClassName();
  56006. serializationObject.direction1 = this.direction1.asArray();
  56007. serializationObject.direction2 = this.direction2.asArray();
  56008. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56009. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56010. return serializationObject;
  56011. };
  56012. /**
  56013. * Parse properties from a JSON object
  56014. * @param serializationObject defines the JSON object
  56015. */
  56016. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56017. this.direction1.copyFrom(serializationObject.direction1);
  56018. this.direction2.copyFrom(serializationObject.direction2);
  56019. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56020. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56021. };
  56022. return BoxParticleEmitter;
  56023. }());
  56024. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56025. })(BABYLON || (BABYLON = {}));
  56026. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56027. var BABYLON;
  56028. (function (BABYLON) {
  56029. /**
  56030. * Particle emitter emitting particles from the inside of a cone.
  56031. * It emits the particles alongside the cone volume from the base to the particle.
  56032. * The emission direction might be randomized.
  56033. */
  56034. var ConeParticleEmitter = /** @class */ (function () {
  56035. /**
  56036. * Creates a new instance ConeParticleEmitter
  56037. * @param radius the radius of the emission cone (1 by default)
  56038. * @param angles the cone base angle (PI by default)
  56039. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56040. */
  56041. function ConeParticleEmitter(radius, angle,
  56042. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56043. directionRandomizer) {
  56044. if (radius === void 0) { radius = 1; }
  56045. if (angle === void 0) { angle = Math.PI; }
  56046. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56047. this.directionRandomizer = directionRandomizer;
  56048. this.angle = angle;
  56049. this.radius = radius;
  56050. }
  56051. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56052. /**
  56053. * Gets or sets the radius of the emission cone
  56054. */
  56055. get: function () {
  56056. return this._radius;
  56057. },
  56058. set: function (value) {
  56059. this._radius = value;
  56060. this._buildHeight();
  56061. },
  56062. enumerable: true,
  56063. configurable: true
  56064. });
  56065. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56066. /**
  56067. * Gets or sets the angle of the emission cone
  56068. */
  56069. get: function () {
  56070. return this._angle;
  56071. },
  56072. set: function (value) {
  56073. this._angle = value;
  56074. this._buildHeight();
  56075. },
  56076. enumerable: true,
  56077. configurable: true
  56078. });
  56079. ConeParticleEmitter.prototype._buildHeight = function () {
  56080. if (this._angle !== 0) {
  56081. this._height = this._radius / Math.tan(this._angle / 2);
  56082. }
  56083. else {
  56084. this._height = 1;
  56085. }
  56086. };
  56087. /**
  56088. * Called by the particle System when the direction is computed for the created particle.
  56089. * @param emitPower is the power of the particle (speed)
  56090. * @param worldMatrix is the world matrix of the particle system
  56091. * @param directionToUpdate is the direction vector to update with the result
  56092. * @param particle is the particle we are computed the direction for
  56093. */
  56094. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56095. if (this._angle === 0) {
  56096. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56097. }
  56098. else {
  56099. // measure the direction Vector from the emitter to the particle.
  56100. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56101. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56102. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56103. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56104. direction.x += randX;
  56105. direction.y += randY;
  56106. direction.z += randZ;
  56107. direction.normalize();
  56108. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56109. }
  56110. };
  56111. /**
  56112. * Called by the particle System when the position is computed for the created particle.
  56113. * @param worldMatrix is the world matrix of the particle system
  56114. * @param positionToUpdate is the position vector to update with the result
  56115. * @param particle is the particle we are computed the position for
  56116. */
  56117. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56118. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56119. var h = BABYLON.Scalar.RandomRange(0, 1);
  56120. // Better distribution in a cone at normal angles.
  56121. h = 1 - h * h;
  56122. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56123. radius = radius * h;
  56124. var randX = radius * Math.sin(s);
  56125. var randZ = radius * Math.cos(s);
  56126. var randY = h * this._height;
  56127. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56128. };
  56129. /**
  56130. * Clones the current emitter and returns a copy of it
  56131. * @returns the new emitter
  56132. */
  56133. ConeParticleEmitter.prototype.clone = function () {
  56134. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56135. BABYLON.Tools.DeepCopy(this, newOne);
  56136. return newOne;
  56137. };
  56138. /**
  56139. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56140. * @param effect defines the update shader
  56141. */
  56142. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56143. effect.setFloat("radius", this._radius);
  56144. effect.setFloat("coneAngle", this._angle);
  56145. effect.setFloat("height", this._height);
  56146. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56147. };
  56148. /**
  56149. * Returns a string to use to update the GPU particles update shader
  56150. * @returns a string containng the defines string
  56151. */
  56152. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56153. return "#define CONEEMITTER";
  56154. };
  56155. /**
  56156. * Returns the string "BoxEmitter"
  56157. * @returns a string containing the class name
  56158. */
  56159. ConeParticleEmitter.prototype.getClassName = function () {
  56160. return "ConeEmitter";
  56161. };
  56162. /**
  56163. * Serializes the particle system to a JSON object.
  56164. * @returns the JSON object
  56165. */
  56166. ConeParticleEmitter.prototype.serialize = function () {
  56167. var serializationObject = {};
  56168. serializationObject.type = this.getClassName();
  56169. serializationObject.radius = this._radius;
  56170. serializationObject.angle = this._angle;
  56171. serializationObject.directionRandomizer = this.directionRandomizer;
  56172. return serializationObject;
  56173. };
  56174. /**
  56175. * Parse properties from a JSON object
  56176. * @param serializationObject defines the JSON object
  56177. */
  56178. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56179. this.radius = serializationObject.radius;
  56180. this.angle = serializationObject.angle;
  56181. this.directionRandomizer = serializationObject.directionRandomizer;
  56182. };
  56183. return ConeParticleEmitter;
  56184. }());
  56185. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56186. })(BABYLON || (BABYLON = {}));
  56187. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56188. var BABYLON;
  56189. (function (BABYLON) {
  56190. /**
  56191. * Particle emitter emitting particles from the inside of a sphere.
  56192. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56193. */
  56194. var SphereParticleEmitter = /** @class */ (function () {
  56195. /**
  56196. * Creates a new instance SphereParticleEmitter
  56197. * @param radius the radius of the emission sphere (1 by default)
  56198. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56199. */
  56200. function SphereParticleEmitter(
  56201. /**
  56202. * The radius of the emission sphere.
  56203. */
  56204. radius,
  56205. /**
  56206. * How much to randomize the particle direction [0-1].
  56207. */
  56208. directionRandomizer) {
  56209. if (radius === void 0) { radius = 1; }
  56210. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56211. this.radius = radius;
  56212. this.directionRandomizer = directionRandomizer;
  56213. }
  56214. /**
  56215. * Called by the particle System when the direction is computed for the created particle.
  56216. * @param emitPower is the power of the particle (speed)
  56217. * @param worldMatrix is the world matrix of the particle system
  56218. * @param directionToUpdate is the direction vector to update with the result
  56219. * @param particle is the particle we are computed the direction for
  56220. */
  56221. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56222. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56223. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56224. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56225. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56226. direction.x += randX;
  56227. direction.y += randY;
  56228. direction.z += randZ;
  56229. direction.normalize();
  56230. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56231. };
  56232. /**
  56233. * Called by the particle System when the position is computed for the created particle.
  56234. * @param worldMatrix is the world matrix of the particle system
  56235. * @param positionToUpdate is the position vector to update with the result
  56236. * @param particle is the particle we are computed the position for
  56237. */
  56238. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56239. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56240. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56241. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56242. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56243. var randY = randRadius * Math.cos(theta);
  56244. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56245. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56246. };
  56247. /**
  56248. * Clones the current emitter and returns a copy of it
  56249. * @returns the new emitter
  56250. */
  56251. SphereParticleEmitter.prototype.clone = function () {
  56252. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56253. BABYLON.Tools.DeepCopy(this, newOne);
  56254. return newOne;
  56255. };
  56256. /**
  56257. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56258. * @param effect defines the update shader
  56259. */
  56260. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56261. effect.setFloat("radius", this.radius);
  56262. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56263. };
  56264. /**
  56265. * Returns a string to use to update the GPU particles update shader
  56266. * @returns a string containng the defines string
  56267. */
  56268. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56269. return "#define SPHEREEMITTER";
  56270. };
  56271. /**
  56272. * Returns the string "SphereParticleEmitter"
  56273. * @returns a string containing the class name
  56274. */
  56275. SphereParticleEmitter.prototype.getClassName = function () {
  56276. return "SphereParticleEmitter";
  56277. };
  56278. /**
  56279. * Serializes the particle system to a JSON object.
  56280. * @returns the JSON object
  56281. */
  56282. SphereParticleEmitter.prototype.serialize = function () {
  56283. var serializationObject = {};
  56284. serializationObject.type = this.getClassName();
  56285. serializationObject.radius = this.radius;
  56286. serializationObject.directionRandomizer = this.directionRandomizer;
  56287. return serializationObject;
  56288. };
  56289. /**
  56290. * Parse properties from a JSON object
  56291. * @param serializationObject defines the JSON object
  56292. */
  56293. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56294. this.radius = serializationObject.radius;
  56295. this.directionRandomizer = serializationObject.directionRandomizer;
  56296. };
  56297. return SphereParticleEmitter;
  56298. }());
  56299. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56300. /**
  56301. * Particle emitter emitting particles from the inside of a sphere.
  56302. * It emits the particles randomly between two vectors.
  56303. */
  56304. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56305. __extends(SphereDirectedParticleEmitter, _super);
  56306. /**
  56307. * Creates a new instance SphereDirectedParticleEmitter
  56308. * @param radius the radius of the emission sphere (1 by default)
  56309. * @param direction1 the min limit of the emission direction (up vector by default)
  56310. * @param direction2 the max limit of the emission direction (up vector by default)
  56311. */
  56312. function SphereDirectedParticleEmitter(radius,
  56313. /**
  56314. * The min limit of the emission direction.
  56315. */
  56316. direction1,
  56317. /**
  56318. * The max limit of the emission direction.
  56319. */
  56320. direction2) {
  56321. if (radius === void 0) { radius = 1; }
  56322. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56323. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56324. var _this = _super.call(this, radius) || this;
  56325. _this.direction1 = direction1;
  56326. _this.direction2 = direction2;
  56327. return _this;
  56328. }
  56329. /**
  56330. * Called by the particle System when the direction is computed for the created particle.
  56331. * @param emitPower is the power of the particle (speed)
  56332. * @param worldMatrix is the world matrix of the particle system
  56333. * @param directionToUpdate is the direction vector to update with the result
  56334. * @param particle is the particle we are computed the direction for
  56335. */
  56336. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56337. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56338. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56339. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56340. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56341. };
  56342. /**
  56343. * Clones the current emitter and returns a copy of it
  56344. * @returns the new emitter
  56345. */
  56346. SphereDirectedParticleEmitter.prototype.clone = function () {
  56347. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56348. BABYLON.Tools.DeepCopy(this, newOne);
  56349. return newOne;
  56350. };
  56351. /**
  56352. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56353. * @param effect defines the update shader
  56354. */
  56355. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56356. effect.setFloat("radius", this.radius);
  56357. effect.setVector3("direction1", this.direction1);
  56358. effect.setVector3("direction2", this.direction2);
  56359. };
  56360. /**
  56361. * Returns a string to use to update the GPU particles update shader
  56362. * @returns a string containng the defines string
  56363. */
  56364. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56365. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56366. };
  56367. /**
  56368. * Returns the string "SphereDirectedParticleEmitter"
  56369. * @returns a string containing the class name
  56370. */
  56371. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56372. return "SphereDirectedParticleEmitter";
  56373. };
  56374. /**
  56375. * Serializes the particle system to a JSON object.
  56376. * @returns the JSON object
  56377. */
  56378. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56379. var serializationObject = _super.prototype.serialize.call(this);
  56380. serializationObject.direction1 = this.direction1.asArray();
  56381. serializationObject.direction2 = this.direction2.asArray();
  56382. return serializationObject;
  56383. };
  56384. /**
  56385. * Parse properties from a JSON object
  56386. * @param serializationObject defines the JSON object
  56387. */
  56388. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56389. _super.prototype.parse.call(this, serializationObject);
  56390. this.direction1.copyFrom(serializationObject.direction1);
  56391. this.direction2.copyFrom(serializationObject.direction2);
  56392. };
  56393. return SphereDirectedParticleEmitter;
  56394. }(SphereParticleEmitter));
  56395. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56396. })(BABYLON || (BABYLON = {}));
  56397. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56398. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56399. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56400. s = arguments[i];
  56401. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56402. t[p] = s[p];
  56403. }
  56404. return t;
  56405. };
  56406. var BABYLON;
  56407. (function (BABYLON) {
  56408. /**
  56409. * This represents a GPU particle system in Babylon
  56410. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56411. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56412. */
  56413. var GPUParticleSystem = /** @class */ (function () {
  56414. /**
  56415. * Instantiates a GPU particle system.
  56416. * 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.
  56417. * @param name The name of the particle system
  56418. * @param capacity The max number of particles alive at the same time
  56419. * @param scene The scene the particle system belongs to
  56420. */
  56421. function GPUParticleSystem(name, options, scene) {
  56422. /**
  56423. * The emitter represents the Mesh or position we are attaching the particle system to.
  56424. */
  56425. this.emitter = null;
  56426. /**
  56427. * The rendering group used by the Particle system to chose when to render.
  56428. */
  56429. this.renderingGroupId = 0;
  56430. /**
  56431. * The layer mask we are rendering the particles through.
  56432. */
  56433. this.layerMask = 0x0FFFFFFF;
  56434. this._targetIndex = 0;
  56435. this._currentRenderId = -1;
  56436. this._started = false;
  56437. this._stopped = false;
  56438. this._timeDelta = 0;
  56439. this._attributesStrideSize = 18;
  56440. this._actualFrame = 0;
  56441. /**
  56442. * List of animations used by the particle system.
  56443. */
  56444. this.animations = [];
  56445. /**
  56446. * An event triggered when the system is disposed.
  56447. */
  56448. this.onDisposeObservable = new BABYLON.Observable();
  56449. /**
  56450. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56451. */
  56452. this.updateSpeed = 0.01;
  56453. /**
  56454. * The amount of time the particle system is running (depends of the overall update speed).
  56455. */
  56456. this.targetStopDuration = 0;
  56457. /**
  56458. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56459. */
  56460. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56461. /**
  56462. * Minimum life time of emitting particles.
  56463. */
  56464. this.minLifeTime = 1;
  56465. /**
  56466. * Maximum life time of emitting particles.
  56467. */
  56468. this.maxLifeTime = 1;
  56469. /**
  56470. * Minimum Size of emitting particles.
  56471. */
  56472. this.minSize = 1;
  56473. /**
  56474. * Maximum Size of emitting particles.
  56475. */
  56476. this.maxSize = 1;
  56477. /**
  56478. * Minimum scale of emitting particles on X axis.
  56479. */
  56480. this.minScaleX = 1;
  56481. /**
  56482. * Maximum scale of emitting particles on X axis.
  56483. */
  56484. this.maxScaleX = 1;
  56485. /**
  56486. * Minimum scale of emitting particles on Y axis.
  56487. */
  56488. this.minScaleY = 1;
  56489. /**
  56490. * Maximum scale of emitting particles on Y axis.
  56491. */
  56492. this.maxScaleY = 1;
  56493. /**
  56494. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56495. */
  56496. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56497. /**
  56498. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56499. */
  56500. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56501. /**
  56502. * Color the particle will have at the end of its lifetime.
  56503. */
  56504. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56505. /**
  56506. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56507. */
  56508. this.emitRate = 100;
  56509. /**
  56510. * You can use gravity if you want to give an orientation to your particles.
  56511. */
  56512. this.gravity = BABYLON.Vector3.Zero();
  56513. /**
  56514. * Minimum power of emitting particles.
  56515. */
  56516. this.minEmitPower = 1;
  56517. /**
  56518. * Maximum power of emitting particles.
  56519. */
  56520. this.maxEmitPower = 1;
  56521. /**
  56522. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56523. */
  56524. this.minAngularSpeed = 0;
  56525. /**
  56526. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56527. */
  56528. this.maxAngularSpeed = 0;
  56529. /**
  56530. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56531. * to override the particles.
  56532. */
  56533. this.forceDepthWrite = false;
  56534. this.id = name;
  56535. this.name = name;
  56536. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56537. this._engine = this._scene.getEngine();
  56538. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56539. this._capacity = fullOptions.capacity;
  56540. this._activeCount = fullOptions.capacity;
  56541. this._currentActiveCount = 0;
  56542. this._scene.particleSystems.push(this);
  56543. this._updateEffectOptions = {
  56544. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  56545. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56546. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56547. "angleRange"],
  56548. uniformBuffersNames: [],
  56549. samplers: ["randomSampler"],
  56550. defines: "",
  56551. fallbacks: null,
  56552. onCompiled: null,
  56553. onError: null,
  56554. indexParameters: null,
  56555. maxSimultaneousLights: 0,
  56556. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  56557. };
  56558. // Random data
  56559. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56560. var d = [];
  56561. for (var i = 0; i < maxTextureSize; ++i) {
  56562. d.push(Math.random());
  56563. d.push(Math.random());
  56564. d.push(Math.random());
  56565. d.push(Math.random());
  56566. }
  56567. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56568. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56569. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56570. this._randomTextureSize = maxTextureSize;
  56571. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56572. }
  56573. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56574. /**
  56575. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56576. */
  56577. get: function () {
  56578. if (!BABYLON.Engine.LastCreatedEngine) {
  56579. return false;
  56580. }
  56581. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56582. },
  56583. enumerable: true,
  56584. configurable: true
  56585. });
  56586. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56587. /**
  56588. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56589. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56590. */
  56591. get: function () {
  56592. if (this.particleEmitterType.direction1) {
  56593. return this.particleEmitterType.direction1;
  56594. }
  56595. return BABYLON.Vector3.Zero();
  56596. },
  56597. set: function (value) {
  56598. if (this.particleEmitterType.direction1) {
  56599. this.particleEmitterType.direction1 = value;
  56600. }
  56601. },
  56602. enumerable: true,
  56603. configurable: true
  56604. });
  56605. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56606. /**
  56607. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56608. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56609. */
  56610. get: function () {
  56611. if (this.particleEmitterType.direction2) {
  56612. return this.particleEmitterType.direction2;
  56613. }
  56614. return BABYLON.Vector3.Zero();
  56615. },
  56616. set: function (value) {
  56617. if (this.particleEmitterType.direction2) {
  56618. this.particleEmitterType.direction2 = value;
  56619. }
  56620. },
  56621. enumerable: true,
  56622. configurable: true
  56623. });
  56624. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56625. /**
  56626. * 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.
  56627. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56628. */
  56629. get: function () {
  56630. if (this.particleEmitterType.minEmitBox) {
  56631. return this.particleEmitterType.minEmitBox;
  56632. }
  56633. return BABYLON.Vector3.Zero();
  56634. },
  56635. set: function (value) {
  56636. if (this.particleEmitterType.minEmitBox) {
  56637. this.particleEmitterType.minEmitBox = value;
  56638. }
  56639. },
  56640. enumerable: true,
  56641. configurable: true
  56642. });
  56643. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56644. /**
  56645. * 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.
  56646. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56647. */
  56648. get: function () {
  56649. if (this.particleEmitterType.maxEmitBox) {
  56650. return this.particleEmitterType.maxEmitBox;
  56651. }
  56652. return BABYLON.Vector3.Zero();
  56653. },
  56654. set: function (value) {
  56655. if (this.particleEmitterType.maxEmitBox) {
  56656. this.particleEmitterType.maxEmitBox = value;
  56657. }
  56658. },
  56659. enumerable: true,
  56660. configurable: true
  56661. });
  56662. /**
  56663. * Gets the maximum number of particles active at the same time.
  56664. * @returns The max number of active particles.
  56665. */
  56666. GPUParticleSystem.prototype.getCapacity = function () {
  56667. return this._capacity;
  56668. };
  56669. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56670. /**
  56671. * Gets or set the number of active particles
  56672. */
  56673. get: function () {
  56674. return this._activeCount;
  56675. },
  56676. set: function (value) {
  56677. this._activeCount = Math.min(value, this._capacity);
  56678. },
  56679. enumerable: true,
  56680. configurable: true
  56681. });
  56682. /**
  56683. * Is this system ready to be used/rendered
  56684. * @return true if the system is ready
  56685. */
  56686. GPUParticleSystem.prototype.isReady = function () {
  56687. if (!this._updateEffect) {
  56688. this._recreateUpdateEffect();
  56689. this._recreateRenderEffect();
  56690. return false;
  56691. }
  56692. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56693. return false;
  56694. }
  56695. return true;
  56696. };
  56697. /**
  56698. * Gets Wether the system has been started.
  56699. * @returns True if it has been started, otherwise false.
  56700. */
  56701. GPUParticleSystem.prototype.isStarted = function () {
  56702. return this._started;
  56703. };
  56704. /**
  56705. * Starts the particle system and begins to emit.
  56706. */
  56707. GPUParticleSystem.prototype.start = function () {
  56708. this._started = true;
  56709. this._stopped = false;
  56710. };
  56711. /**
  56712. * Stops the particle system.
  56713. */
  56714. GPUParticleSystem.prototype.stop = function () {
  56715. this._stopped = true;
  56716. };
  56717. /**
  56718. * Remove all active particles
  56719. */
  56720. GPUParticleSystem.prototype.reset = function () {
  56721. this._releaseBuffers();
  56722. this._releaseVAOs();
  56723. this._currentActiveCount = 0;
  56724. this._targetIndex = 0;
  56725. };
  56726. /**
  56727. * Returns the string "GPUParticleSystem"
  56728. * @returns a string containing the class name
  56729. */
  56730. GPUParticleSystem.prototype.getClassName = function () {
  56731. return "GPUParticleSystem";
  56732. };
  56733. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56734. var updateVertexBuffers = {};
  56735. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56736. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56737. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56738. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56739. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3);
  56740. updateVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4);
  56741. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 13, 3);
  56742. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2);
  56743. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56744. this._engine.bindArrayBuffer(null);
  56745. return vao;
  56746. };
  56747. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56748. var renderVertexBuffers = {};
  56749. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56750. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56751. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56752. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 3, this._attributesStrideSize, true);
  56753. renderVertexBuffers["color"] = source.createVertexBuffer("color", 9, 4, this._attributesStrideSize, true);
  56754. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 16, 2, this._attributesStrideSize, true);
  56755. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56756. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56757. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56758. this._engine.bindArrayBuffer(null);
  56759. return vao;
  56760. };
  56761. GPUParticleSystem.prototype._initialize = function (force) {
  56762. if (force === void 0) { force = false; }
  56763. if (this._buffer0 && !force) {
  56764. return;
  56765. }
  56766. var engine = this._scene.getEngine();
  56767. var data = new Array();
  56768. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56769. // position
  56770. data.push(0.0);
  56771. data.push(0.0);
  56772. data.push(0.0);
  56773. // Age and life
  56774. data.push(0.0); // create the particle as a dead one to create a new one at start
  56775. data.push(0.0);
  56776. // Seed
  56777. data.push(Math.random());
  56778. // Size
  56779. data.push(0.0);
  56780. data.push(0.0);
  56781. data.push(0.0);
  56782. // color
  56783. data.push(0.0);
  56784. data.push(0.0);
  56785. data.push(0.0);
  56786. data.push(0.0);
  56787. // direction
  56788. data.push(0.0);
  56789. data.push(0.0);
  56790. data.push(0.0);
  56791. // angle
  56792. data.push(0.0);
  56793. data.push(0.0);
  56794. }
  56795. // Sprite data
  56796. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56797. -0.5, 0.5, 0, 1,
  56798. -0.5, -0.5, 0, 0,
  56799. 0.5, -0.5, 1, 0]);
  56800. // Buffers
  56801. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56802. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56803. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56804. // Update VAO
  56805. this._updateVAO = [];
  56806. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56807. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56808. // Render VAO
  56809. this._renderVAO = [];
  56810. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56811. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56812. // Links
  56813. this._sourceBuffer = this._buffer0;
  56814. this._targetBuffer = this._buffer1;
  56815. };
  56816. /** @hidden */
  56817. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56818. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56819. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56820. return;
  56821. }
  56822. this._updateEffectOptions.defines = defines;
  56823. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56824. };
  56825. /** @hidden */
  56826. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56827. var defines = "";
  56828. if (this._scene.clipPlane) {
  56829. defines = "\n#define CLIPPLANE";
  56830. }
  56831. if (this._renderEffect && this._renderEffect.defines === defines) {
  56832. return;
  56833. }
  56834. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56835. };
  56836. /**
  56837. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56838. */
  56839. GPUParticleSystem.prototype.animate = function () {
  56840. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56841. this._actualFrame += this._timeDelta;
  56842. if (!this._stopped) {
  56843. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56844. this.stop();
  56845. }
  56846. }
  56847. };
  56848. /**
  56849. * Renders the particle system in its current state.
  56850. * @returns the current number of particles
  56851. */
  56852. GPUParticleSystem.prototype.render = function () {
  56853. if (!this._started) {
  56854. return 0;
  56855. }
  56856. this._recreateUpdateEffect();
  56857. this._recreateRenderEffect();
  56858. if (!this.isReady()) {
  56859. return 0;
  56860. }
  56861. if (this._currentRenderId === this._scene.getRenderId()) {
  56862. return 0;
  56863. }
  56864. this._currentRenderId = this._scene.getRenderId();
  56865. // Get everything ready to render
  56866. this._initialize();
  56867. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56868. // Enable update effect
  56869. this._engine.enableEffect(this._updateEffect);
  56870. this._engine.setState(false);
  56871. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56872. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56873. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56874. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56875. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56876. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56877. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56878. this._updateEffect.setDirectColor4("color1", this.color1);
  56879. this._updateEffect.setDirectColor4("color2", this.color2);
  56880. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56881. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  56882. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  56883. this._updateEffect.setVector3("gravity", this.gravity);
  56884. if (this.particleEmitterType) {
  56885. this.particleEmitterType.applyToShader(this._updateEffect);
  56886. }
  56887. var emitterWM;
  56888. if (this.emitter.position) {
  56889. var emitterMesh = this.emitter;
  56890. emitterWM = emitterMesh.getWorldMatrix();
  56891. }
  56892. else {
  56893. var emitterPosition = this.emitter;
  56894. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56895. }
  56896. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56897. // Bind source VAO
  56898. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56899. // Update
  56900. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56901. this._engine.setRasterizerState(false);
  56902. this._engine.beginTransformFeedback();
  56903. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56904. this._engine.endTransformFeedback();
  56905. this._engine.setRasterizerState(true);
  56906. this._engine.bindTransformFeedbackBuffer(null);
  56907. // Enable render effect
  56908. this._engine.enableEffect(this._renderEffect);
  56909. var viewMatrix = this._scene.getViewMatrix();
  56910. this._renderEffect.setMatrix("view", viewMatrix);
  56911. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56912. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56913. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56914. if (this._scene.clipPlane) {
  56915. var clipPlane = this._scene.clipPlane;
  56916. var invView = viewMatrix.clone();
  56917. invView.invert();
  56918. this._renderEffect.setMatrix("invView", invView);
  56919. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56920. }
  56921. // Draw order
  56922. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56923. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56924. }
  56925. else {
  56926. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56927. }
  56928. if (this.forceDepthWrite) {
  56929. this._engine.setDepthWrite(true);
  56930. }
  56931. // Bind source VAO
  56932. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56933. // Render
  56934. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56935. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56936. // Switch VAOs
  56937. this._targetIndex++;
  56938. if (this._targetIndex === 2) {
  56939. this._targetIndex = 0;
  56940. }
  56941. // Switch buffers
  56942. var tmpBuffer = this._sourceBuffer;
  56943. this._sourceBuffer = this._targetBuffer;
  56944. this._targetBuffer = tmpBuffer;
  56945. return this._currentActiveCount;
  56946. };
  56947. /**
  56948. * Rebuilds the particle system
  56949. */
  56950. GPUParticleSystem.prototype.rebuild = function () {
  56951. this._initialize(true);
  56952. };
  56953. GPUParticleSystem.prototype._releaseBuffers = function () {
  56954. if (this._buffer0) {
  56955. this._buffer0.dispose();
  56956. this._buffer0 = null;
  56957. }
  56958. if (this._buffer1) {
  56959. this._buffer1.dispose();
  56960. this._buffer1 = null;
  56961. }
  56962. if (this._spriteBuffer) {
  56963. this._spriteBuffer.dispose();
  56964. this._spriteBuffer = null;
  56965. }
  56966. };
  56967. GPUParticleSystem.prototype._releaseVAOs = function () {
  56968. if (!this._updateVAO) {
  56969. return;
  56970. }
  56971. for (var index = 0; index < this._updateVAO.length; index++) {
  56972. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56973. }
  56974. this._updateVAO = [];
  56975. for (var index = 0; index < this._renderVAO.length; index++) {
  56976. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56977. }
  56978. this._renderVAO = [];
  56979. };
  56980. /**
  56981. * Disposes the particle system and free the associated resources
  56982. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56983. */
  56984. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56985. if (disposeTexture === void 0) { disposeTexture = true; }
  56986. var index = this._scene.particleSystems.indexOf(this);
  56987. if (index > -1) {
  56988. this._scene.particleSystems.splice(index, 1);
  56989. }
  56990. this._releaseBuffers();
  56991. this._releaseVAOs();
  56992. if (this._randomTexture) {
  56993. this._randomTexture.dispose();
  56994. this._randomTexture = null;
  56995. }
  56996. if (disposeTexture && this.particleTexture) {
  56997. this.particleTexture.dispose();
  56998. this.particleTexture = null;
  56999. }
  57000. // Callback
  57001. this.onDisposeObservable.notifyObservers(this);
  57002. this.onDisposeObservable.clear();
  57003. };
  57004. /**
  57005. * Clones the particle system.
  57006. * @param name The name of the cloned object
  57007. * @param newEmitter The new emitter to use
  57008. * @returns the cloned particle system
  57009. */
  57010. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57011. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57012. BABYLON.Tools.DeepCopy(this, result);
  57013. if (newEmitter === undefined) {
  57014. newEmitter = this.emitter;
  57015. }
  57016. result.emitter = newEmitter;
  57017. if (this.particleTexture) {
  57018. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57019. }
  57020. return result;
  57021. };
  57022. /**
  57023. * Serializes the particle system to a JSON object.
  57024. * @returns the JSON object
  57025. */
  57026. GPUParticleSystem.prototype.serialize = function () {
  57027. var serializationObject = {};
  57028. serializationObject.name = this.name;
  57029. serializationObject.id = this.id;
  57030. // Emitter
  57031. if (this.emitter.position) {
  57032. var emitterMesh = this.emitter;
  57033. serializationObject.emitterId = emitterMesh.id;
  57034. }
  57035. else {
  57036. var emitterPosition = this.emitter;
  57037. serializationObject.emitter = emitterPosition.asArray();
  57038. }
  57039. serializationObject.capacity = this.getCapacity();
  57040. if (this.particleTexture) {
  57041. serializationObject.textureName = this.particleTexture.name;
  57042. }
  57043. // Animations
  57044. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57045. // Particle system
  57046. serializationObject.activeParticleCount = this.activeParticleCount;
  57047. serializationObject.randomTextureSize = this._randomTextureSize;
  57048. serializationObject.minSize = this.minSize;
  57049. serializationObject.maxSize = this.maxSize;
  57050. serializationObject.minEmitPower = this.minEmitPower;
  57051. serializationObject.maxEmitPower = this.maxEmitPower;
  57052. serializationObject.minLifeTime = this.minLifeTime;
  57053. serializationObject.maxLifeTime = this.maxLifeTime;
  57054. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57055. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57056. serializationObject.emitRate = this.emitRate;
  57057. serializationObject.gravity = this.gravity.asArray();
  57058. serializationObject.color1 = this.color1.asArray();
  57059. serializationObject.color2 = this.color2.asArray();
  57060. serializationObject.colorDead = this.colorDead.asArray();
  57061. serializationObject.updateSpeed = this.updateSpeed;
  57062. serializationObject.targetStopDuration = this.targetStopDuration;
  57063. serializationObject.blendMode = this.blendMode;
  57064. // Emitter
  57065. if (this.particleEmitterType) {
  57066. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57067. }
  57068. return serializationObject;
  57069. };
  57070. /**
  57071. * Parses a JSON object to create a GPU particle system.
  57072. * @param parsedParticleSystem The JSON object to parse
  57073. * @param scene The scene to create the particle system in
  57074. * @param rootUrl The root url to use to load external dependencies like texture
  57075. * @returns the parsed GPU particle system
  57076. */
  57077. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57078. var name = parsedParticleSystem.name;
  57079. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57080. if (parsedParticleSystem.id) {
  57081. particleSystem.id = parsedParticleSystem.id;
  57082. }
  57083. // Texture
  57084. if (parsedParticleSystem.textureName) {
  57085. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57086. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57087. }
  57088. // Emitter
  57089. if (parsedParticleSystem.emitterId) {
  57090. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57091. }
  57092. else {
  57093. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57094. }
  57095. // Animations
  57096. if (parsedParticleSystem.animations) {
  57097. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57098. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57099. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57100. }
  57101. }
  57102. // Particle system
  57103. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57104. particleSystem.minSize = parsedParticleSystem.minSize;
  57105. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57106. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57107. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57108. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57109. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57110. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57111. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57112. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57113. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57114. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57115. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57116. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57117. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57118. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57119. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57120. // Emitter
  57121. if (parsedParticleSystem.particleEmitterType) {
  57122. var emitterType = void 0;
  57123. switch (parsedParticleSystem.particleEmitterType.type) {
  57124. case "SphereEmitter":
  57125. emitterType = new BABYLON.SphereParticleEmitter();
  57126. break;
  57127. case "SphereDirectedParticleEmitter":
  57128. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57129. break;
  57130. case "ConeEmitter":
  57131. emitterType = new BABYLON.ConeParticleEmitter();
  57132. break;
  57133. case "BoxEmitter":
  57134. default:
  57135. emitterType = new BABYLON.BoxParticleEmitter();
  57136. break;
  57137. }
  57138. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57139. particleSystem.particleEmitterType = emitterType;
  57140. }
  57141. return particleSystem;
  57142. };
  57143. return GPUParticleSystem;
  57144. }());
  57145. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57146. })(BABYLON || (BABYLON = {}));
  57147. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57148. var BABYLON;
  57149. (function (BABYLON) {
  57150. /**
  57151. * Represents one particle of a solid particle system.
  57152. */
  57153. var SolidParticle = /** @class */ (function () {
  57154. /**
  57155. * Creates a Solid Particle object.
  57156. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57157. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57158. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57159. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57160. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57161. * @param shapeId (integer) is the model shape identifier in the SPS.
  57162. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57163. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57164. */
  57165. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57166. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57167. /**
  57168. * particle global index
  57169. */
  57170. this.idx = 0;
  57171. /**
  57172. * The color of the particle
  57173. */
  57174. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57175. /**
  57176. * The world space position of the particle.
  57177. */
  57178. this.position = BABYLON.Vector3.Zero();
  57179. /**
  57180. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57181. */
  57182. this.rotation = BABYLON.Vector3.Zero();
  57183. /**
  57184. * The scaling of the particle.
  57185. */
  57186. this.scaling = BABYLON.Vector3.One();
  57187. /**
  57188. * The uvs of the particle.
  57189. */
  57190. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57191. /**
  57192. * The current speed of the particle.
  57193. */
  57194. this.velocity = BABYLON.Vector3.Zero();
  57195. /**
  57196. * The pivot point in the particle local space.
  57197. */
  57198. this.pivot = BABYLON.Vector3.Zero();
  57199. /**
  57200. * Must the particle be translated from its pivot point in its local space ?
  57201. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57202. * Default : false
  57203. */
  57204. this.translateFromPivot = false;
  57205. /**
  57206. * Is the particle active or not ?
  57207. */
  57208. this.alive = true;
  57209. /**
  57210. * Is the particle visible or not ?
  57211. */
  57212. this.isVisible = true;
  57213. /**
  57214. * Index of this particle in the global "positions" array (Internal use)
  57215. */
  57216. this._pos = 0;
  57217. /**
  57218. * Index of this particle in the global "indices" array (Internal use)
  57219. */
  57220. this._ind = 0;
  57221. /**
  57222. * ModelShape id of this particle
  57223. */
  57224. this.shapeId = 0;
  57225. /**
  57226. * Index of the particle in its shape id (Internal use)
  57227. */
  57228. this.idxInShape = 0;
  57229. /**
  57230. * Still set as invisible in order to skip useless computations (Internal use)
  57231. */
  57232. this._stillInvisible = false;
  57233. /**
  57234. * Last computed particle rotation matrix
  57235. */
  57236. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57237. /**
  57238. * Parent particle Id, if any.
  57239. * Default null.
  57240. */
  57241. this.parentId = null;
  57242. /**
  57243. * Internal global position in the SPS.
  57244. */
  57245. this._globalPosition = BABYLON.Vector3.Zero();
  57246. this.idx = particleIndex;
  57247. this._pos = positionIndex;
  57248. this._ind = indiceIndex;
  57249. this._model = model;
  57250. this.shapeId = shapeId;
  57251. this.idxInShape = idxInShape;
  57252. this._sps = sps;
  57253. if (modelBoundingInfo) {
  57254. this._modelBoundingInfo = modelBoundingInfo;
  57255. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57256. }
  57257. }
  57258. Object.defineProperty(SolidParticle.prototype, "scale", {
  57259. /**
  57260. * Legacy support, changed scale to scaling
  57261. */
  57262. get: function () {
  57263. return this.scaling;
  57264. },
  57265. /**
  57266. * Legacy support, changed scale to scaling
  57267. */
  57268. set: function (scale) {
  57269. this.scaling = scale;
  57270. },
  57271. enumerable: true,
  57272. configurable: true
  57273. });
  57274. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57275. /**
  57276. * Legacy support, changed quaternion to rotationQuaternion
  57277. */
  57278. get: function () {
  57279. return this.rotationQuaternion;
  57280. },
  57281. /**
  57282. * Legacy support, changed quaternion to rotationQuaternion
  57283. */
  57284. set: function (q) {
  57285. this.rotationQuaternion = q;
  57286. },
  57287. enumerable: true,
  57288. configurable: true
  57289. });
  57290. /**
  57291. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57292. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57293. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57294. * @returns true if it intersects
  57295. */
  57296. SolidParticle.prototype.intersectsMesh = function (target) {
  57297. if (!this._boundingInfo || !target._boundingInfo) {
  57298. return false;
  57299. }
  57300. if (this._sps._bSphereOnly) {
  57301. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57302. }
  57303. return this._boundingInfo.intersects(target._boundingInfo, false);
  57304. };
  57305. return SolidParticle;
  57306. }());
  57307. BABYLON.SolidParticle = SolidParticle;
  57308. /**
  57309. * Represents the shape of the model used by one particle of a solid particle system.
  57310. * SPS internal tool, don't use it manually.
  57311. */
  57312. var ModelShape = /** @class */ (function () {
  57313. /**
  57314. * 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.
  57315. * SPS internal tool, don't use it manually.
  57316. * @hidden
  57317. */
  57318. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57319. /**
  57320. * length of the shape in the model indices array (internal use)
  57321. */
  57322. this._indicesLength = 0;
  57323. this.shapeID = id;
  57324. this._shape = shape;
  57325. this._indicesLength = indicesLength;
  57326. this._shapeUV = shapeUV;
  57327. this._positionFunction = posFunction;
  57328. this._vertexFunction = vtxFunction;
  57329. }
  57330. return ModelShape;
  57331. }());
  57332. BABYLON.ModelShape = ModelShape;
  57333. /**
  57334. * Represents a Depth Sorted Particle in the solid particle system.
  57335. */
  57336. var DepthSortedParticle = /** @class */ (function () {
  57337. function DepthSortedParticle() {
  57338. /**
  57339. * Index of the particle in the "indices" array
  57340. */
  57341. this.ind = 0;
  57342. /**
  57343. * Length of the particle shape in the "indices" array
  57344. */
  57345. this.indicesLength = 0;
  57346. /**
  57347. * Squared distance from the particle to the camera
  57348. */
  57349. this.sqDistance = 0.0;
  57350. }
  57351. return DepthSortedParticle;
  57352. }());
  57353. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57354. })(BABYLON || (BABYLON = {}));
  57355. //# sourceMappingURL=babylon.solidParticle.js.map
  57356. var BABYLON;
  57357. (function (BABYLON) {
  57358. /**
  57359. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57360. *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.
  57361. * The SPS is also a particle system. It provides some methods to manage the particles.
  57362. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57363. *
  57364. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57365. */
  57366. var SolidParticleSystem = /** @class */ (function () {
  57367. /**
  57368. * Creates a SPS (Solid Particle System) object.
  57369. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57370. * @param scene (Scene) is the scene in which the SPS is added.
  57371. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57372. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57373. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57374. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57375. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57376. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57377. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57378. */
  57379. function SolidParticleSystem(name, scene, options) {
  57380. /**
  57381. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57382. * Example : var p = SPS.particles[i];
  57383. */
  57384. this.particles = new Array();
  57385. /**
  57386. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57387. */
  57388. this.nbParticles = 0;
  57389. /**
  57390. * If the particles must ever face the camera (default false). Useful for planar particles.
  57391. */
  57392. this.billboard = false;
  57393. /**
  57394. * Recompute normals when adding a shape
  57395. */
  57396. this.recomputeNormals = true;
  57397. /**
  57398. * This a counter ofr your own usage. It's not set by any SPS functions.
  57399. */
  57400. this.counter = 0;
  57401. /**
  57402. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57403. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57404. */
  57405. this.vars = {};
  57406. /**
  57407. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57408. */
  57409. this._bSphereOnly = false;
  57410. /**
  57411. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57412. */
  57413. this._bSphereRadiusFactor = 1.0;
  57414. this._positions = new Array();
  57415. this._indices = new Array();
  57416. this._normals = new Array();
  57417. this._colors = new Array();
  57418. this._uvs = new Array();
  57419. this._index = 0; // indices index
  57420. this._updatable = true;
  57421. this._pickable = false;
  57422. this._isVisibilityBoxLocked = false;
  57423. this._alwaysVisible = false;
  57424. this._depthSort = false;
  57425. this._shapeCounter = 0;
  57426. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57427. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57428. this._computeParticleColor = true;
  57429. this._computeParticleTexture = true;
  57430. this._computeParticleRotation = true;
  57431. this._computeParticleVertex = false;
  57432. this._computeBoundingBox = false;
  57433. this._depthSortParticles = true;
  57434. this._cam_axisZ = BABYLON.Vector3.Zero();
  57435. this._cam_axisY = BABYLON.Vector3.Zero();
  57436. this._cam_axisX = BABYLON.Vector3.Zero();
  57437. this._axisZ = BABYLON.Axis.Z;
  57438. this._camDir = BABYLON.Vector3.Zero();
  57439. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57440. this._rotMatrix = new BABYLON.Matrix();
  57441. this._invertMatrix = new BABYLON.Matrix();
  57442. this._rotated = BABYLON.Vector3.Zero();
  57443. this._quaternion = new BABYLON.Quaternion();
  57444. this._vertex = BABYLON.Vector3.Zero();
  57445. this._normal = BABYLON.Vector3.Zero();
  57446. this._yaw = 0.0;
  57447. this._pitch = 0.0;
  57448. this._roll = 0.0;
  57449. this._halfroll = 0.0;
  57450. this._halfpitch = 0.0;
  57451. this._halfyaw = 0.0;
  57452. this._sinRoll = 0.0;
  57453. this._cosRoll = 0.0;
  57454. this._sinPitch = 0.0;
  57455. this._cosPitch = 0.0;
  57456. this._sinYaw = 0.0;
  57457. this._cosYaw = 0.0;
  57458. this._mustUnrotateFixedNormals = false;
  57459. this._minimum = BABYLON.Vector3.Zero();
  57460. this._maximum = BABYLON.Vector3.Zero();
  57461. this._minBbox = BABYLON.Vector3.Zero();
  57462. this._maxBbox = BABYLON.Vector3.Zero();
  57463. this._particlesIntersect = false;
  57464. this._depthSortFunction = function (p1, p2) {
  57465. return (p2.sqDistance - p1.sqDistance);
  57466. };
  57467. this._needs32Bits = false;
  57468. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57469. this._scaledPivot = BABYLON.Vector3.Zero();
  57470. this._particleHasParent = false;
  57471. this.name = name;
  57472. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57473. this._camera = scene.activeCamera;
  57474. this._pickable = options ? options.isPickable : false;
  57475. this._depthSort = options ? options.enableDepthSort : false;
  57476. this._particlesIntersect = options ? options.particleIntersection : false;
  57477. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57478. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57479. if (options && options.updatable !== undefined) {
  57480. this._updatable = options.updatable;
  57481. }
  57482. else {
  57483. this._updatable = true;
  57484. }
  57485. if (this._pickable) {
  57486. this.pickedParticles = [];
  57487. }
  57488. if (this._depthSort) {
  57489. this.depthSortedParticles = [];
  57490. }
  57491. }
  57492. /**
  57493. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57494. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57495. * @returns the created mesh
  57496. */
  57497. SolidParticleSystem.prototype.buildMesh = function () {
  57498. if (this.nbParticles === 0) {
  57499. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57500. this.addShape(triangle, 1);
  57501. triangle.dispose();
  57502. }
  57503. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57504. this._positions32 = new Float32Array(this._positions);
  57505. this._uvs32 = new Float32Array(this._uvs);
  57506. this._colors32 = new Float32Array(this._colors);
  57507. if (this.recomputeNormals) {
  57508. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57509. }
  57510. this._normals32 = new Float32Array(this._normals);
  57511. this._fixedNormal32 = new Float32Array(this._normals);
  57512. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57513. this._unrotateFixedNormals();
  57514. }
  57515. var vertexData = new BABYLON.VertexData();
  57516. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57517. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57518. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57519. if (this._uvs32.length > 0) {
  57520. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57521. }
  57522. if (this._colors32.length > 0) {
  57523. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57524. }
  57525. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57526. vertexData.applyToMesh(mesh, this._updatable);
  57527. this.mesh = mesh;
  57528. this.mesh.isPickable = this._pickable;
  57529. // free memory
  57530. if (!this._depthSort) {
  57531. this._indices = null;
  57532. }
  57533. this._positions = null;
  57534. this._normals = null;
  57535. this._uvs = null;
  57536. this._colors = null;
  57537. if (!this._updatable) {
  57538. this.particles.length = 0;
  57539. }
  57540. return mesh;
  57541. };
  57542. /**
  57543. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57544. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57545. * Thus the particles generated from `digest()` have their property `position` set yet.
  57546. * @param mesh ( Mesh ) is the mesh to be digested
  57547. * @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
  57548. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57549. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57550. * @returns the current SPS
  57551. */
  57552. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57553. var size = (options && options.facetNb) || 1;
  57554. var number = (options && options.number) || 0;
  57555. var delta = (options && options.delta) || 0;
  57556. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57557. var meshInd = mesh.getIndices();
  57558. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57559. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57560. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57561. var f = 0; // facet counter
  57562. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57563. // compute size from number
  57564. if (number) {
  57565. number = (number > totalFacets) ? totalFacets : number;
  57566. size = Math.round(totalFacets / number);
  57567. delta = 0;
  57568. }
  57569. else {
  57570. size = (size > totalFacets) ? totalFacets : size;
  57571. }
  57572. var facetPos = []; // submesh positions
  57573. var facetInd = []; // submesh indices
  57574. var facetUV = []; // submesh UV
  57575. var facetCol = []; // submesh colors
  57576. var barycenter = BABYLON.Vector3.Zero();
  57577. var sizeO = size;
  57578. while (f < totalFacets) {
  57579. size = sizeO + Math.floor((1 + delta) * Math.random());
  57580. if (f > totalFacets - size) {
  57581. size = totalFacets - f;
  57582. }
  57583. // reset temp arrays
  57584. facetPos.length = 0;
  57585. facetInd.length = 0;
  57586. facetUV.length = 0;
  57587. facetCol.length = 0;
  57588. // iterate over "size" facets
  57589. var fi = 0;
  57590. for (var j = f * 3; j < (f + size) * 3; j++) {
  57591. facetInd.push(fi);
  57592. var i = meshInd[j];
  57593. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57594. if (meshUV) {
  57595. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57596. }
  57597. if (meshCol) {
  57598. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57599. }
  57600. fi++;
  57601. }
  57602. // create a model shape for each single particle
  57603. var idx = this.nbParticles;
  57604. var shape = this._posToShape(facetPos);
  57605. var shapeUV = this._uvsToShapeUV(facetUV);
  57606. // compute the barycenter of the shape
  57607. var v;
  57608. for (v = 0; v < shape.length; v++) {
  57609. barycenter.addInPlace(shape[v]);
  57610. }
  57611. barycenter.scaleInPlace(1 / shape.length);
  57612. // shift the shape from its barycenter to the origin
  57613. for (v = 0; v < shape.length; v++) {
  57614. shape[v].subtractInPlace(barycenter);
  57615. }
  57616. var bInfo;
  57617. if (this._particlesIntersect) {
  57618. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57619. }
  57620. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57621. // add the particle in the SPS
  57622. var currentPos = this._positions.length;
  57623. var currentInd = this._indices.length;
  57624. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57625. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57626. // initialize the particle position
  57627. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57628. this._index += shape.length;
  57629. idx++;
  57630. this.nbParticles++;
  57631. this._shapeCounter++;
  57632. f += size;
  57633. }
  57634. return this;
  57635. };
  57636. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57637. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57638. var index = 0;
  57639. var idx = 0;
  57640. for (var p = 0; p < this.particles.length; p++) {
  57641. this._particle = this.particles[p];
  57642. this._shape = this._particle._model._shape;
  57643. if (this._particle.rotationQuaternion) {
  57644. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57645. }
  57646. else {
  57647. this._yaw = this._particle.rotation.y;
  57648. this._pitch = this._particle.rotation.x;
  57649. this._roll = this._particle.rotation.z;
  57650. this._quaternionRotationYPR();
  57651. }
  57652. this._quaternionToRotationMatrix();
  57653. this._rotMatrix.invertToRef(this._invertMatrix);
  57654. for (var pt = 0; pt < this._shape.length; pt++) {
  57655. idx = index + pt * 3;
  57656. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57657. this._fixedNormal32[idx] = this._normal.x;
  57658. this._fixedNormal32[idx + 1] = this._normal.y;
  57659. this._fixedNormal32[idx + 2] = this._normal.z;
  57660. }
  57661. index = idx + 3;
  57662. }
  57663. };
  57664. //reset copy
  57665. SolidParticleSystem.prototype._resetCopy = function () {
  57666. this._copy.position.x = 0;
  57667. this._copy.position.y = 0;
  57668. this._copy.position.z = 0;
  57669. this._copy.rotation.x = 0;
  57670. this._copy.rotation.y = 0;
  57671. this._copy.rotation.z = 0;
  57672. this._copy.rotationQuaternion = null;
  57673. this._copy.scaling.x = 1.0;
  57674. this._copy.scaling.y = 1.0;
  57675. this._copy.scaling.z = 1.0;
  57676. this._copy.uvs.x = 0;
  57677. this._copy.uvs.y = 0;
  57678. this._copy.uvs.z = 1.0;
  57679. this._copy.uvs.w = 1.0;
  57680. this._copy.color = null;
  57681. this._copy.translateFromPivot = false;
  57682. };
  57683. // _meshBuilder : inserts the shape model in the global SPS mesh
  57684. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57685. var i;
  57686. var u = 0;
  57687. var c = 0;
  57688. var n = 0;
  57689. this._resetCopy();
  57690. if (options && options.positionFunction) { // call to custom positionFunction
  57691. options.positionFunction(this._copy, idx, idxInShape);
  57692. this._mustUnrotateFixedNormals = true;
  57693. }
  57694. if (this._copy.rotationQuaternion) {
  57695. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57696. }
  57697. else {
  57698. this._yaw = this._copy.rotation.y;
  57699. this._pitch = this._copy.rotation.x;
  57700. this._roll = this._copy.rotation.z;
  57701. this._quaternionRotationYPR();
  57702. }
  57703. this._quaternionToRotationMatrix();
  57704. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57705. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57706. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57707. if (this._copy.translateFromPivot) {
  57708. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57709. }
  57710. else {
  57711. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57712. }
  57713. for (i = 0; i < shape.length; i++) {
  57714. this._vertex.x = shape[i].x;
  57715. this._vertex.y = shape[i].y;
  57716. this._vertex.z = shape[i].z;
  57717. if (options && options.vertexFunction) {
  57718. options.vertexFunction(this._copy, this._vertex, i);
  57719. }
  57720. this._vertex.x *= this._copy.scaling.x;
  57721. this._vertex.y *= this._copy.scaling.y;
  57722. this._vertex.z *= this._copy.scaling.z;
  57723. this._vertex.x -= this._scaledPivot.x;
  57724. this._vertex.y -= this._scaledPivot.y;
  57725. this._vertex.z -= this._scaledPivot.z;
  57726. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57727. this._rotated.addInPlace(this._pivotBackTranslation);
  57728. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57729. if (meshUV) {
  57730. 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);
  57731. u += 2;
  57732. }
  57733. if (this._copy.color) {
  57734. this._color = this._copy.color;
  57735. }
  57736. else if (meshCol && meshCol[c] !== undefined) {
  57737. this._color.r = meshCol[c];
  57738. this._color.g = meshCol[c + 1];
  57739. this._color.b = meshCol[c + 2];
  57740. this._color.a = meshCol[c + 3];
  57741. }
  57742. else {
  57743. this._color.r = 1.0;
  57744. this._color.g = 1.0;
  57745. this._color.b = 1.0;
  57746. this._color.a = 1.0;
  57747. }
  57748. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57749. c += 4;
  57750. if (!this.recomputeNormals && meshNor) {
  57751. this._normal.x = meshNor[n];
  57752. this._normal.y = meshNor[n + 1];
  57753. this._normal.z = meshNor[n + 2];
  57754. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57755. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57756. n += 3;
  57757. }
  57758. }
  57759. for (i = 0; i < meshInd.length; i++) {
  57760. var current_ind = p + meshInd[i];
  57761. indices.push(current_ind);
  57762. if (current_ind > 65535) {
  57763. this._needs32Bits = true;
  57764. }
  57765. }
  57766. if (this._pickable) {
  57767. var nbfaces = meshInd.length / 3;
  57768. for (i = 0; i < nbfaces; i++) {
  57769. this.pickedParticles.push({ idx: idx, faceId: i });
  57770. }
  57771. }
  57772. if (this._depthSort) {
  57773. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57774. }
  57775. return this._copy;
  57776. };
  57777. // returns a shape array from positions array
  57778. SolidParticleSystem.prototype._posToShape = function (positions) {
  57779. var shape = [];
  57780. for (var i = 0; i < positions.length; i += 3) {
  57781. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57782. }
  57783. return shape;
  57784. };
  57785. // returns a shapeUV array from a Vector4 uvs
  57786. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57787. var shapeUV = [];
  57788. if (uvs) {
  57789. for (var i = 0; i < uvs.length; i++)
  57790. shapeUV.push(uvs[i]);
  57791. }
  57792. return shapeUV;
  57793. };
  57794. // adds a new particle object in the particles array
  57795. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57796. if (bInfo === void 0) { bInfo = null; }
  57797. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57798. this.particles.push(sp);
  57799. return sp;
  57800. };
  57801. /**
  57802. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57803. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57804. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57805. * @param nb (positive integer) the number of particles to be created from this model
  57806. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57807. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57808. * @returns the number of shapes in the system
  57809. */
  57810. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57811. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57812. var meshInd = mesh.getIndices();
  57813. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57814. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57815. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57816. var bbInfo;
  57817. if (this._particlesIntersect) {
  57818. bbInfo = mesh.getBoundingInfo();
  57819. }
  57820. var shape = this._posToShape(meshPos);
  57821. var shapeUV = this._uvsToShapeUV(meshUV);
  57822. var posfunc = options ? options.positionFunction : null;
  57823. var vtxfunc = options ? options.vertexFunction : null;
  57824. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57825. // particles
  57826. var sp;
  57827. var currentCopy;
  57828. var idx = this.nbParticles;
  57829. for (var i = 0; i < nb; i++) {
  57830. var currentPos = this._positions.length;
  57831. var currentInd = this._indices.length;
  57832. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57833. if (this._updatable) {
  57834. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57835. sp.position.copyFrom(currentCopy.position);
  57836. sp.rotation.copyFrom(currentCopy.rotation);
  57837. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57838. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57839. }
  57840. if (currentCopy.color && sp.color) {
  57841. sp.color.copyFrom(currentCopy.color);
  57842. }
  57843. sp.scaling.copyFrom(currentCopy.scaling);
  57844. sp.uvs.copyFrom(currentCopy.uvs);
  57845. }
  57846. this._index += shape.length;
  57847. idx++;
  57848. }
  57849. this.nbParticles += nb;
  57850. this._shapeCounter++;
  57851. return this._shapeCounter - 1;
  57852. };
  57853. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57854. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57855. this._resetCopy();
  57856. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  57857. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57858. }
  57859. if (this._copy.rotationQuaternion) {
  57860. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57861. }
  57862. else {
  57863. this._yaw = this._copy.rotation.y;
  57864. this._pitch = this._copy.rotation.x;
  57865. this._roll = this._copy.rotation.z;
  57866. this._quaternionRotationYPR();
  57867. }
  57868. this._quaternionToRotationMatrix();
  57869. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57870. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57871. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57872. if (this._copy.translateFromPivot) {
  57873. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57874. }
  57875. else {
  57876. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57877. }
  57878. this._shape = particle._model._shape;
  57879. for (var pt = 0; pt < this._shape.length; pt++) {
  57880. this._vertex.x = this._shape[pt].x;
  57881. this._vertex.y = this._shape[pt].y;
  57882. this._vertex.z = this._shape[pt].z;
  57883. if (particle._model._vertexFunction) {
  57884. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57885. }
  57886. this._vertex.x *= this._copy.scaling.x;
  57887. this._vertex.y *= this._copy.scaling.y;
  57888. this._vertex.z *= this._copy.scaling.z;
  57889. this._vertex.x -= this._scaledPivot.x;
  57890. this._vertex.y -= this._scaledPivot.y;
  57891. this._vertex.z -= this._scaledPivot.z;
  57892. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57893. this._rotated.addInPlace(this._pivotBackTranslation);
  57894. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57895. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57896. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57897. }
  57898. particle.position.x = 0.0;
  57899. particle.position.y = 0.0;
  57900. particle.position.z = 0.0;
  57901. particle.rotation.x = 0.0;
  57902. particle.rotation.y = 0.0;
  57903. particle.rotation.z = 0.0;
  57904. particle.rotationQuaternion = null;
  57905. particle.scaling.x = 1.0;
  57906. particle.scaling.y = 1.0;
  57907. particle.scaling.z = 1.0;
  57908. particle.uvs.x = 0.0;
  57909. particle.uvs.y = 0.0;
  57910. particle.uvs.z = 1.0;
  57911. particle.uvs.w = 1.0;
  57912. particle.pivot.x = 0.0;
  57913. particle.pivot.y = 0.0;
  57914. particle.pivot.z = 0.0;
  57915. particle.translateFromPivot = false;
  57916. particle.parentId = null;
  57917. };
  57918. /**
  57919. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57920. * @returns the SPS.
  57921. */
  57922. SolidParticleSystem.prototype.rebuildMesh = function () {
  57923. for (var p = 0; p < this.particles.length; p++) {
  57924. this._rebuildParticle(this.particles[p]);
  57925. }
  57926. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57927. return this;
  57928. };
  57929. /**
  57930. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57931. * This method calls `updateParticle()` for each particle of the SPS.
  57932. * For an animated SPS, it is usually called within the render loop.
  57933. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57934. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57935. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57936. * @returns the SPS.
  57937. */
  57938. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57939. if (start === void 0) { start = 0; }
  57940. if (end === void 0) { end = this.nbParticles - 1; }
  57941. if (update === void 0) { update = true; }
  57942. if (!this._updatable) {
  57943. return this;
  57944. }
  57945. // custom beforeUpdate
  57946. this.beforeUpdateParticles(start, end, update);
  57947. this._cam_axisX.x = 1.0;
  57948. this._cam_axisX.y = 0.0;
  57949. this._cam_axisX.z = 0.0;
  57950. this._cam_axisY.x = 0.0;
  57951. this._cam_axisY.y = 1.0;
  57952. this._cam_axisY.z = 0.0;
  57953. this._cam_axisZ.x = 0.0;
  57954. this._cam_axisZ.y = 0.0;
  57955. this._cam_axisZ.z = 1.0;
  57956. // cases when the World Matrix is to be computed first
  57957. if (this.billboard || this._depthSort) {
  57958. this.mesh.computeWorldMatrix(true);
  57959. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57960. }
  57961. // if the particles will always face the camera
  57962. if (this.billboard) {
  57963. // compute the camera position and un-rotate it by the current mesh rotation
  57964. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57965. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57966. this._cam_axisZ.normalize();
  57967. // same for camera up vector extracted from the cam view matrix
  57968. var view = this._camera.getViewMatrix(true);
  57969. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57970. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57971. this._cam_axisY.normalize();
  57972. this._cam_axisX.normalize();
  57973. }
  57974. // if depthSort, compute the camera global position in the mesh local system
  57975. if (this._depthSort) {
  57976. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57977. }
  57978. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57979. var idx = 0; // current position index in the global array positions32
  57980. var index = 0; // position start index in the global array positions32 of the current particle
  57981. var colidx = 0; // current color index in the global array colors32
  57982. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57983. var uvidx = 0; // current uv index in the global array uvs32
  57984. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57985. var pt = 0; // current index in the particle model shape
  57986. if (this.mesh.isFacetDataEnabled) {
  57987. this._computeBoundingBox = true;
  57988. }
  57989. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57990. if (this._computeBoundingBox) {
  57991. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  57992. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57993. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57994. }
  57995. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  57996. if (this.mesh._boundingInfo) {
  57997. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57998. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57999. }
  58000. }
  58001. }
  58002. // particle loop
  58003. index = this.particles[start]._pos;
  58004. var vpos = (index / 3) | 0;
  58005. colorIndex = vpos * 4;
  58006. uvIndex = vpos * 2;
  58007. for (var p = start; p <= end; p++) {
  58008. this._particle = this.particles[p];
  58009. this._shape = this._particle._model._shape;
  58010. this._shapeUV = this._particle._model._shapeUV;
  58011. // call to custom user function to update the particle properties
  58012. this.updateParticle(this._particle);
  58013. // camera-particle distance for depth sorting
  58014. if (this._depthSort && this._depthSortParticles) {
  58015. var dsp = this.depthSortedParticles[p];
  58016. dsp.ind = this._particle._ind;
  58017. dsp.indicesLength = this._particle._model._indicesLength;
  58018. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58019. }
  58020. // skip the computations for inactive or already invisible particles
  58021. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58022. // increment indexes for the next particle
  58023. pt = this._shape.length;
  58024. index += pt * 3;
  58025. colorIndex += pt * 4;
  58026. uvIndex += pt * 2;
  58027. continue;
  58028. }
  58029. if (this._particle.isVisible) {
  58030. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58031. this._particleHasParent = (this._particle.parentId !== null);
  58032. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58033. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58034. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58035. // particle rotation matrix
  58036. if (this.billboard) {
  58037. this._particle.rotation.x = 0.0;
  58038. this._particle.rotation.y = 0.0;
  58039. }
  58040. if (this._computeParticleRotation || this.billboard) {
  58041. if (this._particle.rotationQuaternion) {
  58042. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58043. }
  58044. else {
  58045. this._yaw = this._particle.rotation.y;
  58046. this._pitch = this._particle.rotation.x;
  58047. this._roll = this._particle.rotation.z;
  58048. this._quaternionRotationYPR();
  58049. }
  58050. this._quaternionToRotationMatrix();
  58051. }
  58052. if (this._particleHasParent) {
  58053. this._parent = this.particles[this._particle.parentId];
  58054. 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];
  58055. 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];
  58056. 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];
  58057. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58058. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58059. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58060. if (this._computeParticleRotation || this.billboard) {
  58061. 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];
  58062. 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];
  58063. 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];
  58064. 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];
  58065. 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];
  58066. 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];
  58067. 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];
  58068. 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];
  58069. 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];
  58070. }
  58071. }
  58072. else {
  58073. this._particle._globalPosition.x = this._particle.position.x;
  58074. this._particle._globalPosition.y = this._particle.position.y;
  58075. this._particle._globalPosition.z = this._particle.position.z;
  58076. if (this._computeParticleRotation || this.billboard) {
  58077. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58078. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58079. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58080. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58081. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58082. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58083. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58084. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58085. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58086. }
  58087. }
  58088. if (this._particle.translateFromPivot) {
  58089. this._pivotBackTranslation.x = 0.0;
  58090. this._pivotBackTranslation.y = 0.0;
  58091. this._pivotBackTranslation.z = 0.0;
  58092. }
  58093. else {
  58094. this._pivotBackTranslation.x = this._scaledPivot.x;
  58095. this._pivotBackTranslation.y = this._scaledPivot.y;
  58096. this._pivotBackTranslation.z = this._scaledPivot.z;
  58097. }
  58098. // particle vertex loop
  58099. for (pt = 0; pt < this._shape.length; pt++) {
  58100. idx = index + pt * 3;
  58101. colidx = colorIndex + pt * 4;
  58102. uvidx = uvIndex + pt * 2;
  58103. this._vertex.x = this._shape[pt].x;
  58104. this._vertex.y = this._shape[pt].y;
  58105. this._vertex.z = this._shape[pt].z;
  58106. if (this._computeParticleVertex) {
  58107. this.updateParticleVertex(this._particle, this._vertex, pt);
  58108. }
  58109. // positions
  58110. this._vertex.x *= this._particle.scaling.x;
  58111. this._vertex.y *= this._particle.scaling.y;
  58112. this._vertex.z *= this._particle.scaling.z;
  58113. this._vertex.x -= this._scaledPivot.x;
  58114. this._vertex.y -= this._scaledPivot.y;
  58115. this._vertex.z -= this._scaledPivot.z;
  58116. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58117. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58118. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58119. this._rotated.x += this._pivotBackTranslation.x;
  58120. this._rotated.y += this._pivotBackTranslation.y;
  58121. this._rotated.z += this._pivotBackTranslation.z;
  58122. 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;
  58123. 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;
  58124. 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;
  58125. if (this._computeBoundingBox) {
  58126. if (this._positions32[idx] < this._minimum.x) {
  58127. this._minimum.x = this._positions32[idx];
  58128. }
  58129. if (this._positions32[idx] > this._maximum.x) {
  58130. this._maximum.x = this._positions32[idx];
  58131. }
  58132. if (this._positions32[idx + 1] < this._minimum.y) {
  58133. this._minimum.y = this._positions32[idx + 1];
  58134. }
  58135. if (this._positions32[idx + 1] > this._maximum.y) {
  58136. this._maximum.y = this._positions32[idx + 1];
  58137. }
  58138. if (this._positions32[idx + 2] < this._minimum.z) {
  58139. this._minimum.z = this._positions32[idx + 2];
  58140. }
  58141. if (this._positions32[idx + 2] > this._maximum.z) {
  58142. this._maximum.z = this._positions32[idx + 2];
  58143. }
  58144. }
  58145. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58146. if (!this._computeParticleVertex) {
  58147. this._normal.x = this._fixedNormal32[idx];
  58148. this._normal.y = this._fixedNormal32[idx + 1];
  58149. this._normal.z = this._fixedNormal32[idx + 2];
  58150. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58151. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58152. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58153. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58154. 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;
  58155. 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;
  58156. }
  58157. if (this._computeParticleColor && this._particle.color) {
  58158. this._colors32[colidx] = this._particle.color.r;
  58159. this._colors32[colidx + 1] = this._particle.color.g;
  58160. this._colors32[colidx + 2] = this._particle.color.b;
  58161. this._colors32[colidx + 3] = this._particle.color.a;
  58162. }
  58163. if (this._computeParticleTexture) {
  58164. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58165. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58166. }
  58167. }
  58168. }
  58169. // particle just set invisible : scaled to zero and positioned at the origin
  58170. else {
  58171. this._particle._stillInvisible = true; // mark the particle as invisible
  58172. for (pt = 0; pt < this._shape.length; pt++) {
  58173. idx = index + pt * 3;
  58174. colidx = colorIndex + pt * 4;
  58175. uvidx = uvIndex + pt * 2;
  58176. this._positions32[idx] = 0.0;
  58177. this._positions32[idx + 1] = 0.0;
  58178. this._positions32[idx + 2] = 0.0;
  58179. this._normals32[idx] = 0.0;
  58180. this._normals32[idx + 1] = 0.0;
  58181. this._normals32[idx + 2] = 0.0;
  58182. if (this._computeParticleColor && this._particle.color) {
  58183. this._colors32[colidx] = this._particle.color.r;
  58184. this._colors32[colidx + 1] = this._particle.color.g;
  58185. this._colors32[colidx + 2] = this._particle.color.b;
  58186. this._colors32[colidx + 3] = this._particle.color.a;
  58187. }
  58188. if (this._computeParticleTexture) {
  58189. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58190. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58191. }
  58192. }
  58193. }
  58194. // if the particle intersections must be computed : update the bbInfo
  58195. if (this._particlesIntersect) {
  58196. var bInfo = this._particle._boundingInfo;
  58197. var bBox = bInfo.boundingBox;
  58198. var bSphere = bInfo.boundingSphere;
  58199. if (!this._bSphereOnly) {
  58200. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58201. for (var b = 0; b < bBox.vectors.length; b++) {
  58202. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58203. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58204. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58205. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58206. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58207. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58208. 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;
  58209. 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;
  58210. 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;
  58211. }
  58212. bBox._update(this.mesh._worldMatrix);
  58213. }
  58214. // place and scale the particle bouding sphere in the SPS local system, then update it
  58215. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58216. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58217. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58218. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58219. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58220. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58221. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58222. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58223. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58224. 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));
  58225. bSphere._update(this.mesh._worldMatrix);
  58226. }
  58227. // increment indexes for the next particle
  58228. index = idx + 3;
  58229. colorIndex = colidx + 4;
  58230. uvIndex = uvidx + 2;
  58231. }
  58232. // if the VBO must be updated
  58233. if (update) {
  58234. if (this._computeParticleColor) {
  58235. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58236. }
  58237. if (this._computeParticleTexture) {
  58238. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58239. }
  58240. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58241. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58242. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58243. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58244. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58245. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58246. for (var i = 0; i < this._normals32.length; i++) {
  58247. this._fixedNormal32[i] = this._normals32[i];
  58248. }
  58249. }
  58250. if (!this.mesh.areNormalsFrozen) {
  58251. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58252. }
  58253. }
  58254. if (this._depthSort && this._depthSortParticles) {
  58255. this.depthSortedParticles.sort(this._depthSortFunction);
  58256. var dspl = this.depthSortedParticles.length;
  58257. var sorted = 0;
  58258. var lind = 0;
  58259. var sind = 0;
  58260. var sid = 0;
  58261. for (sorted = 0; sorted < dspl; sorted++) {
  58262. lind = this.depthSortedParticles[sorted].indicesLength;
  58263. sind = this.depthSortedParticles[sorted].ind;
  58264. for (var i = 0; i < lind; i++) {
  58265. this._indices32[sid] = this._indices[sind + i];
  58266. sid++;
  58267. }
  58268. }
  58269. this.mesh.updateIndices(this._indices32);
  58270. }
  58271. }
  58272. if (this._computeBoundingBox) {
  58273. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58274. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58275. }
  58276. this.afterUpdateParticles(start, end, update);
  58277. return this;
  58278. };
  58279. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58280. this._halfroll = this._roll * 0.5;
  58281. this._halfpitch = this._pitch * 0.5;
  58282. this._halfyaw = this._yaw * 0.5;
  58283. this._sinRoll = Math.sin(this._halfroll);
  58284. this._cosRoll = Math.cos(this._halfroll);
  58285. this._sinPitch = Math.sin(this._halfpitch);
  58286. this._cosPitch = Math.cos(this._halfpitch);
  58287. this._sinYaw = Math.sin(this._halfyaw);
  58288. this._cosYaw = Math.cos(this._halfyaw);
  58289. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58290. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58291. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58292. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58293. };
  58294. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58295. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58296. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58297. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58298. this._rotMatrix.m[3] = 0;
  58299. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58300. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58301. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58302. this._rotMatrix.m[7] = 0;
  58303. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58304. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58305. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58306. this._rotMatrix.m[11] = 0;
  58307. this._rotMatrix.m[12] = 0;
  58308. this._rotMatrix.m[13] = 0;
  58309. this._rotMatrix.m[14] = 0;
  58310. this._rotMatrix.m[15] = 1.0;
  58311. };
  58312. /**
  58313. * Disposes the SPS.
  58314. */
  58315. SolidParticleSystem.prototype.dispose = function () {
  58316. this.mesh.dispose();
  58317. this.vars = null;
  58318. // drop references to internal big arrays for the GC
  58319. this._positions = null;
  58320. this._indices = null;
  58321. this._normals = null;
  58322. this._uvs = null;
  58323. this._colors = null;
  58324. this._indices32 = null;
  58325. this._positions32 = null;
  58326. this._normals32 = null;
  58327. this._fixedNormal32 = null;
  58328. this._uvs32 = null;
  58329. this._colors32 = null;
  58330. this.pickedParticles = null;
  58331. };
  58332. /**
  58333. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58334. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58335. * @returns the SPS.
  58336. */
  58337. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58338. if (!this._isVisibilityBoxLocked) {
  58339. this.mesh.refreshBoundingInfo();
  58340. }
  58341. return this;
  58342. };
  58343. /**
  58344. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58345. * @param size the size (float) of the visibility box
  58346. * note : this doesn't lock the SPS mesh bounding box.
  58347. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58348. */
  58349. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58350. var vis = size / 2;
  58351. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58352. };
  58353. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58354. /**
  58355. * Gets whether the SPS as always visible or not
  58356. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58357. */
  58358. get: function () {
  58359. return this._alwaysVisible;
  58360. },
  58361. /**
  58362. * Sets the SPS as always visible or not
  58363. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58364. */
  58365. set: function (val) {
  58366. this._alwaysVisible = val;
  58367. this.mesh.alwaysSelectAsActiveMesh = val;
  58368. },
  58369. enumerable: true,
  58370. configurable: true
  58371. });
  58372. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58373. /**
  58374. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58375. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58376. */
  58377. get: function () {
  58378. return this._isVisibilityBoxLocked;
  58379. },
  58380. /**
  58381. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58382. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58383. */
  58384. set: function (val) {
  58385. this._isVisibilityBoxLocked = val;
  58386. var boundingInfo = this.mesh.getBoundingInfo();
  58387. boundingInfo.isLocked = val;
  58388. },
  58389. enumerable: true,
  58390. configurable: true
  58391. });
  58392. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58393. /**
  58394. * Gets if `setParticles()` computes the particle rotations or not.
  58395. * Default value : true. The SPS is faster when it's set to false.
  58396. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58397. */
  58398. get: function () {
  58399. return this._computeParticleRotation;
  58400. },
  58401. /**
  58402. * Tells to `setParticles()` to compute the particle rotations or not.
  58403. * Default value : true. The SPS is faster when it's set to false.
  58404. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58405. */
  58406. set: function (val) {
  58407. this._computeParticleRotation = val;
  58408. },
  58409. enumerable: true,
  58410. configurable: true
  58411. });
  58412. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58413. /**
  58414. * Gets if `setParticles()` computes the particle colors or not.
  58415. * Default value : true. The SPS is faster when it's set to false.
  58416. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58417. */
  58418. get: function () {
  58419. return this._computeParticleColor;
  58420. },
  58421. /**
  58422. * Tells to `setParticles()` to compute the particle colors or not.
  58423. * Default value : true. The SPS is faster when it's set to false.
  58424. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58425. */
  58426. set: function (val) {
  58427. this._computeParticleColor = val;
  58428. },
  58429. enumerable: true,
  58430. configurable: true
  58431. });
  58432. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58433. /**
  58434. * Gets if `setParticles()` computes the particle textures or not.
  58435. * Default value : true. The SPS is faster when it's set to false.
  58436. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58437. */
  58438. get: function () {
  58439. return this._computeParticleTexture;
  58440. },
  58441. set: function (val) {
  58442. this._computeParticleTexture = val;
  58443. },
  58444. enumerable: true,
  58445. configurable: true
  58446. });
  58447. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58448. /**
  58449. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58450. * Default value : false. The SPS is faster when it's set to false.
  58451. * Note : the particle custom vertex positions aren't stored values.
  58452. */
  58453. get: function () {
  58454. return this._computeParticleVertex;
  58455. },
  58456. /**
  58457. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58458. * Default value : false. The SPS is faster when it's set to false.
  58459. * Note : the particle custom vertex positions aren't stored values.
  58460. */
  58461. set: function (val) {
  58462. this._computeParticleVertex = val;
  58463. },
  58464. enumerable: true,
  58465. configurable: true
  58466. });
  58467. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58468. /**
  58469. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58470. */
  58471. get: function () {
  58472. return this._computeBoundingBox;
  58473. },
  58474. /**
  58475. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58476. */
  58477. set: function (val) {
  58478. this._computeBoundingBox = val;
  58479. },
  58480. enumerable: true,
  58481. configurable: true
  58482. });
  58483. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58484. /**
  58485. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58486. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58487. * Default : `true`
  58488. */
  58489. get: function () {
  58490. return this._depthSortParticles;
  58491. },
  58492. /**
  58493. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58494. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58495. * Default : `true`
  58496. */
  58497. set: function (val) {
  58498. this._depthSortParticles = val;
  58499. },
  58500. enumerable: true,
  58501. configurable: true
  58502. });
  58503. // =======================================================================
  58504. // Particle behavior logic
  58505. // these following methods may be overwritten by the user to fit his needs
  58506. /**
  58507. * This function does nothing. It may be overwritten to set all the particle first values.
  58508. * The SPS doesn't call this function, you may have to call it by your own.
  58509. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58510. */
  58511. SolidParticleSystem.prototype.initParticles = function () {
  58512. };
  58513. /**
  58514. * This function does nothing. It may be overwritten to recycle a particle.
  58515. * The SPS doesn't call this function, you may have to call it by your own.
  58516. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58517. * @param particle The particle to recycle
  58518. * @returns the recycled particle
  58519. */
  58520. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58521. return particle;
  58522. };
  58523. /**
  58524. * Updates a particle : this function should be overwritten by the user.
  58525. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58526. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58527. * @example : just set a particle position or velocity and recycle conditions
  58528. * @param particle The particle to update
  58529. * @returns the updated particle
  58530. */
  58531. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58532. return particle;
  58533. };
  58534. /**
  58535. * Updates a vertex of a particle : it can be overwritten by the user.
  58536. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58537. * @param particle the current particle
  58538. * @param vertex the current index of the current particle
  58539. * @param pt the index of the current vertex in the particle shape
  58540. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58541. * @example : just set a vertex particle position
  58542. * @returns the updated vertex
  58543. */
  58544. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58545. return vertex;
  58546. };
  58547. /**
  58548. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58549. * This does nothing and may be overwritten by the user.
  58550. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58551. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58552. * @param update the boolean update value actually passed to setParticles()
  58553. */
  58554. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58555. };
  58556. /**
  58557. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58558. * This will be passed three parameters.
  58559. * This does nothing and may be overwritten by the user.
  58560. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58561. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58562. * @param update the boolean update value actually passed to setParticles()
  58563. */
  58564. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58565. };
  58566. return SolidParticleSystem;
  58567. }());
  58568. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58569. })(BABYLON || (BABYLON = {}));
  58570. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58571. var BABYLON;
  58572. (function (BABYLON) {
  58573. var ShaderMaterial = /** @class */ (function (_super) {
  58574. __extends(ShaderMaterial, _super);
  58575. function ShaderMaterial(name, scene, shaderPath, options) {
  58576. var _this = _super.call(this, name, scene) || this;
  58577. _this._textures = {};
  58578. _this._textureArrays = {};
  58579. _this._floats = {};
  58580. _this._ints = {};
  58581. _this._floatsArrays = {};
  58582. _this._colors3 = {};
  58583. _this._colors3Arrays = {};
  58584. _this._colors4 = {};
  58585. _this._vectors2 = {};
  58586. _this._vectors3 = {};
  58587. _this._vectors4 = {};
  58588. _this._matrices = {};
  58589. _this._matrices3x3 = {};
  58590. _this._matrices2x2 = {};
  58591. _this._vectors2Arrays = {};
  58592. _this._vectors3Arrays = {};
  58593. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58594. _this._shaderPath = shaderPath;
  58595. options.needAlphaBlending = options.needAlphaBlending || false;
  58596. options.needAlphaTesting = options.needAlphaTesting || false;
  58597. options.attributes = options.attributes || ["position", "normal", "uv"];
  58598. options.uniforms = options.uniforms || ["worldViewProjection"];
  58599. options.uniformBuffers = options.uniformBuffers || [];
  58600. options.samplers = options.samplers || [];
  58601. options.defines = options.defines || [];
  58602. _this._options = options;
  58603. return _this;
  58604. }
  58605. ShaderMaterial.prototype.getClassName = function () {
  58606. return "ShaderMaterial";
  58607. };
  58608. ShaderMaterial.prototype.needAlphaBlending = function () {
  58609. return this._options.needAlphaBlending;
  58610. };
  58611. ShaderMaterial.prototype.needAlphaTesting = function () {
  58612. return this._options.needAlphaTesting;
  58613. };
  58614. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58615. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58616. this._options.uniforms.push(uniformName);
  58617. }
  58618. };
  58619. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58620. if (this._options.samplers.indexOf(name) === -1) {
  58621. this._options.samplers.push(name);
  58622. }
  58623. this._textures[name] = texture;
  58624. return this;
  58625. };
  58626. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58627. if (this._options.samplers.indexOf(name) === -1) {
  58628. this._options.samplers.push(name);
  58629. }
  58630. this._checkUniform(name);
  58631. this._textureArrays[name] = textures;
  58632. return this;
  58633. };
  58634. ShaderMaterial.prototype.setFloat = function (name, value) {
  58635. this._checkUniform(name);
  58636. this._floats[name] = value;
  58637. return this;
  58638. };
  58639. ShaderMaterial.prototype.setInt = function (name, value) {
  58640. this._checkUniform(name);
  58641. this._ints[name] = value;
  58642. return this;
  58643. };
  58644. ShaderMaterial.prototype.setFloats = function (name, value) {
  58645. this._checkUniform(name);
  58646. this._floatsArrays[name] = value;
  58647. return this;
  58648. };
  58649. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58650. this._checkUniform(name);
  58651. this._colors3[name] = value;
  58652. return this;
  58653. };
  58654. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58655. this._checkUniform(name);
  58656. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58657. color.toArray(arr, arr.length);
  58658. return arr;
  58659. }, []);
  58660. return this;
  58661. };
  58662. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58663. this._checkUniform(name);
  58664. this._colors4[name] = value;
  58665. return this;
  58666. };
  58667. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58668. this._checkUniform(name);
  58669. this._vectors2[name] = value;
  58670. return this;
  58671. };
  58672. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58673. this._checkUniform(name);
  58674. this._vectors3[name] = value;
  58675. return this;
  58676. };
  58677. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58678. this._checkUniform(name);
  58679. this._vectors4[name] = value;
  58680. return this;
  58681. };
  58682. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58683. this._checkUniform(name);
  58684. this._matrices[name] = value;
  58685. return this;
  58686. };
  58687. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58688. this._checkUniform(name);
  58689. this._matrices3x3[name] = value;
  58690. return this;
  58691. };
  58692. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58693. this._checkUniform(name);
  58694. this._matrices2x2[name] = value;
  58695. return this;
  58696. };
  58697. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58698. this._checkUniform(name);
  58699. this._vectors2Arrays[name] = value;
  58700. return this;
  58701. };
  58702. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58703. this._checkUniform(name);
  58704. this._vectors3Arrays[name] = value;
  58705. return this;
  58706. };
  58707. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58708. if (!mesh) {
  58709. return true;
  58710. }
  58711. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58712. return false;
  58713. }
  58714. return false;
  58715. };
  58716. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58717. var scene = this.getScene();
  58718. var engine = scene.getEngine();
  58719. if (!this.checkReadyOnEveryCall) {
  58720. if (this._renderId === scene.getRenderId()) {
  58721. if (this._checkCache(scene, mesh, useInstances)) {
  58722. return true;
  58723. }
  58724. }
  58725. }
  58726. // Instances
  58727. var defines = [];
  58728. var attribs = [];
  58729. var fallbacks = new BABYLON.EffectFallbacks();
  58730. if (useInstances) {
  58731. defines.push("#define INSTANCES");
  58732. }
  58733. for (var index = 0; index < this._options.defines.length; index++) {
  58734. defines.push(this._options.defines[index]);
  58735. }
  58736. for (var index = 0; index < this._options.attributes.length; index++) {
  58737. attribs.push(this._options.attributes[index]);
  58738. }
  58739. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58740. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58741. defines.push("#define VERTEXCOLOR");
  58742. }
  58743. // Bones
  58744. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58745. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58746. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58747. if (mesh.numBoneInfluencers > 4) {
  58748. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58749. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58750. }
  58751. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58752. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58753. fallbacks.addCPUSkinningFallback(0, mesh);
  58754. if (this._options.uniforms.indexOf("mBones") === -1) {
  58755. this._options.uniforms.push("mBones");
  58756. }
  58757. }
  58758. else {
  58759. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58760. }
  58761. // Textures
  58762. for (var name in this._textures) {
  58763. if (!this._textures[name].isReady()) {
  58764. return false;
  58765. }
  58766. }
  58767. // Alpha test
  58768. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58769. defines.push("#define ALPHATEST");
  58770. }
  58771. var previousEffect = this._effect;
  58772. var join = defines.join("\n");
  58773. this._effect = engine.createEffect(this._shaderPath, {
  58774. attributes: attribs,
  58775. uniformsNames: this._options.uniforms,
  58776. uniformBuffersNames: this._options.uniformBuffers,
  58777. samplers: this._options.samplers,
  58778. defines: join,
  58779. fallbacks: fallbacks,
  58780. onCompiled: this.onCompiled,
  58781. onError: this.onError
  58782. }, engine);
  58783. if (!this._effect.isReady()) {
  58784. return false;
  58785. }
  58786. if (previousEffect !== this._effect) {
  58787. scene.resetCachedMaterial();
  58788. }
  58789. this._renderId = scene.getRenderId();
  58790. return true;
  58791. };
  58792. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58793. var scene = this.getScene();
  58794. if (!this._effect) {
  58795. return;
  58796. }
  58797. if (this._options.uniforms.indexOf("world") !== -1) {
  58798. this._effect.setMatrix("world", world);
  58799. }
  58800. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58801. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58802. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58803. }
  58804. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58805. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58806. }
  58807. };
  58808. ShaderMaterial.prototype.bind = function (world, mesh) {
  58809. // Std values
  58810. this.bindOnlyWorldMatrix(world);
  58811. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58812. if (this._options.uniforms.indexOf("view") !== -1) {
  58813. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58814. }
  58815. if (this._options.uniforms.indexOf("projection") !== -1) {
  58816. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58817. }
  58818. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58819. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58820. }
  58821. // Bones
  58822. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58823. var name;
  58824. // Texture
  58825. for (name in this._textures) {
  58826. this._effect.setTexture(name, this._textures[name]);
  58827. }
  58828. // Texture arrays
  58829. for (name in this._textureArrays) {
  58830. this._effect.setTextureArray(name, this._textureArrays[name]);
  58831. }
  58832. // Int
  58833. for (name in this._ints) {
  58834. this._effect.setInt(name, this._ints[name]);
  58835. }
  58836. // Float
  58837. for (name in this._floats) {
  58838. this._effect.setFloat(name, this._floats[name]);
  58839. }
  58840. // Floats
  58841. for (name in this._floatsArrays) {
  58842. this._effect.setArray(name, this._floatsArrays[name]);
  58843. }
  58844. // Color3
  58845. for (name in this._colors3) {
  58846. this._effect.setColor3(name, this._colors3[name]);
  58847. }
  58848. for (name in this._colors3Arrays) {
  58849. this._effect.setArray3(name, this._colors3Arrays[name]);
  58850. }
  58851. // Color4
  58852. for (name in this._colors4) {
  58853. var color = this._colors4[name];
  58854. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58855. }
  58856. // Vector2
  58857. for (name in this._vectors2) {
  58858. this._effect.setVector2(name, this._vectors2[name]);
  58859. }
  58860. // Vector3
  58861. for (name in this._vectors3) {
  58862. this._effect.setVector3(name, this._vectors3[name]);
  58863. }
  58864. // Vector4
  58865. for (name in this._vectors4) {
  58866. this._effect.setVector4(name, this._vectors4[name]);
  58867. }
  58868. // Matrix
  58869. for (name in this._matrices) {
  58870. this._effect.setMatrix(name, this._matrices[name]);
  58871. }
  58872. // Matrix 3x3
  58873. for (name in this._matrices3x3) {
  58874. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58875. }
  58876. // Matrix 2x2
  58877. for (name in this._matrices2x2) {
  58878. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58879. }
  58880. // Vector2Array
  58881. for (name in this._vectors2Arrays) {
  58882. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58883. }
  58884. // Vector3Array
  58885. for (name in this._vectors3Arrays) {
  58886. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58887. }
  58888. }
  58889. this._afterBind(mesh);
  58890. };
  58891. ShaderMaterial.prototype.getActiveTextures = function () {
  58892. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58893. for (var name in this._textures) {
  58894. activeTextures.push(this._textures[name]);
  58895. }
  58896. for (var name in this._textureArrays) {
  58897. var array = this._textureArrays[name];
  58898. for (var index = 0; index < array.length; index++) {
  58899. activeTextures.push(array[index]);
  58900. }
  58901. }
  58902. return activeTextures;
  58903. };
  58904. ShaderMaterial.prototype.hasTexture = function (texture) {
  58905. if (_super.prototype.hasTexture.call(this, texture)) {
  58906. return true;
  58907. }
  58908. for (var name in this._textures) {
  58909. if (this._textures[name] === texture) {
  58910. return true;
  58911. }
  58912. }
  58913. for (var name in this._textureArrays) {
  58914. var array = this._textureArrays[name];
  58915. for (var index = 0; index < array.length; index++) {
  58916. if (array[index] === texture) {
  58917. return true;
  58918. }
  58919. }
  58920. }
  58921. return false;
  58922. };
  58923. ShaderMaterial.prototype.clone = function (name) {
  58924. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58925. return newShaderMaterial;
  58926. };
  58927. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58928. if (forceDisposeTextures) {
  58929. var name;
  58930. for (name in this._textures) {
  58931. this._textures[name].dispose();
  58932. }
  58933. for (name in this._textureArrays) {
  58934. var array = this._textureArrays[name];
  58935. for (var index = 0; index < array.length; index++) {
  58936. array[index].dispose();
  58937. }
  58938. }
  58939. }
  58940. this._textures = {};
  58941. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58942. };
  58943. ShaderMaterial.prototype.serialize = function () {
  58944. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58945. serializationObject.customType = "BABYLON.ShaderMaterial";
  58946. serializationObject.options = this._options;
  58947. serializationObject.shaderPath = this._shaderPath;
  58948. var name;
  58949. // Texture
  58950. serializationObject.textures = {};
  58951. for (name in this._textures) {
  58952. serializationObject.textures[name] = this._textures[name].serialize();
  58953. }
  58954. // Texture arrays
  58955. serializationObject.textureArrays = {};
  58956. for (name in this._textureArrays) {
  58957. serializationObject.textureArrays[name] = [];
  58958. var array = this._textureArrays[name];
  58959. for (var index = 0; index < array.length; index++) {
  58960. serializationObject.textureArrays[name].push(array[index].serialize());
  58961. }
  58962. }
  58963. // Float
  58964. serializationObject.floats = {};
  58965. for (name in this._floats) {
  58966. serializationObject.floats[name] = this._floats[name];
  58967. }
  58968. // Float s
  58969. serializationObject.FloatArrays = {};
  58970. for (name in this._floatsArrays) {
  58971. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58972. }
  58973. // Color3
  58974. serializationObject.colors3 = {};
  58975. for (name in this._colors3) {
  58976. serializationObject.colors3[name] = this._colors3[name].asArray();
  58977. }
  58978. // Color3 array
  58979. serializationObject.colors3Arrays = {};
  58980. for (name in this._colors3Arrays) {
  58981. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58982. }
  58983. // Color4
  58984. serializationObject.colors4 = {};
  58985. for (name in this._colors4) {
  58986. serializationObject.colors4[name] = this._colors4[name].asArray();
  58987. }
  58988. // Vector2
  58989. serializationObject.vectors2 = {};
  58990. for (name in this._vectors2) {
  58991. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58992. }
  58993. // Vector3
  58994. serializationObject.vectors3 = {};
  58995. for (name in this._vectors3) {
  58996. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58997. }
  58998. // Vector4
  58999. serializationObject.vectors4 = {};
  59000. for (name in this._vectors4) {
  59001. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59002. }
  59003. // Matrix
  59004. serializationObject.matrices = {};
  59005. for (name in this._matrices) {
  59006. serializationObject.matrices[name] = this._matrices[name].asArray();
  59007. }
  59008. // Matrix 3x3
  59009. serializationObject.matrices3x3 = {};
  59010. for (name in this._matrices3x3) {
  59011. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59012. }
  59013. // Matrix 2x2
  59014. serializationObject.matrices2x2 = {};
  59015. for (name in this._matrices2x2) {
  59016. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59017. }
  59018. // Vector2Array
  59019. serializationObject.vectors2Arrays = {};
  59020. for (name in this._vectors2Arrays) {
  59021. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59022. }
  59023. // Vector3Array
  59024. serializationObject.vectors3Arrays = {};
  59025. for (name in this._vectors3Arrays) {
  59026. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59027. }
  59028. return serializationObject;
  59029. };
  59030. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59031. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59032. var name;
  59033. // Texture
  59034. for (name in source.textures) {
  59035. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59036. }
  59037. // Texture arrays
  59038. for (name in source.textureArrays) {
  59039. var array = source.textureArrays[name];
  59040. var textureArray = new Array();
  59041. for (var index = 0; index < array.length; index++) {
  59042. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59043. }
  59044. material.setTextureArray(name, textureArray);
  59045. }
  59046. // Float
  59047. for (name in source.floats) {
  59048. material.setFloat(name, source.floats[name]);
  59049. }
  59050. // Float s
  59051. for (name in source.floatsArrays) {
  59052. material.setFloats(name, source.floatsArrays[name]);
  59053. }
  59054. // Color3
  59055. for (name in source.colors3) {
  59056. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59057. }
  59058. // Color3 arrays
  59059. for (name in source.colors3Arrays) {
  59060. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59061. if (i % 3 === 0) {
  59062. arr.push([num]);
  59063. }
  59064. else {
  59065. arr[arr.length - 1].push(num);
  59066. }
  59067. return arr;
  59068. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59069. material.setColor3Array(name, colors);
  59070. }
  59071. // Color4
  59072. for (name in source.colors4) {
  59073. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59074. }
  59075. // Vector2
  59076. for (name in source.vectors2) {
  59077. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59078. }
  59079. // Vector3
  59080. for (name in source.vectors3) {
  59081. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59082. }
  59083. // Vector4
  59084. for (name in source.vectors4) {
  59085. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59086. }
  59087. // Matrix
  59088. for (name in source.matrices) {
  59089. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59090. }
  59091. // Matrix 3x3
  59092. for (name in source.matrices3x3) {
  59093. material.setMatrix3x3(name, source.matrices3x3[name]);
  59094. }
  59095. // Matrix 2x2
  59096. for (name in source.matrices2x2) {
  59097. material.setMatrix2x2(name, source.matrices2x2[name]);
  59098. }
  59099. // Vector2Array
  59100. for (name in source.vectors2Arrays) {
  59101. material.setArray2(name, source.vectors2Arrays[name]);
  59102. }
  59103. // Vector3Array
  59104. for (name in source.vectors3Arrays) {
  59105. material.setArray3(name, source.vectors3Arrays[name]);
  59106. }
  59107. return material;
  59108. };
  59109. return ShaderMaterial;
  59110. }(BABYLON.Material));
  59111. BABYLON.ShaderMaterial = ShaderMaterial;
  59112. })(BABYLON || (BABYLON = {}));
  59113. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59114. var BABYLON;
  59115. (function (BABYLON) {
  59116. var GroundMesh = /** @class */ (function (_super) {
  59117. __extends(GroundMesh, _super);
  59118. function GroundMesh(name, scene) {
  59119. var _this = _super.call(this, name, scene) || this;
  59120. _this.generateOctree = false;
  59121. return _this;
  59122. }
  59123. GroundMesh.prototype.getClassName = function () {
  59124. return "GroundMesh";
  59125. };
  59126. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59127. get: function () {
  59128. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59129. },
  59130. enumerable: true,
  59131. configurable: true
  59132. });
  59133. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59134. get: function () {
  59135. return this._subdivisionsX;
  59136. },
  59137. enumerable: true,
  59138. configurable: true
  59139. });
  59140. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59141. get: function () {
  59142. return this._subdivisionsY;
  59143. },
  59144. enumerable: true,
  59145. configurable: true
  59146. });
  59147. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59148. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59149. this._subdivisionsX = chunksCount;
  59150. this._subdivisionsY = chunksCount;
  59151. this.subdivide(chunksCount);
  59152. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59153. };
  59154. /**
  59155. * Returns a height (y) value in the Worl system :
  59156. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59157. * Returns the ground y position if (x, z) are outside the ground surface.
  59158. */
  59159. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59160. var world = this.getWorldMatrix();
  59161. var invMat = BABYLON.Tmp.Matrix[5];
  59162. world.invertToRef(invMat);
  59163. var tmpVect = BABYLON.Tmp.Vector3[8];
  59164. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59165. x = tmpVect.x;
  59166. z = tmpVect.z;
  59167. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59168. return this.position.y;
  59169. }
  59170. if (!this._heightQuads || this._heightQuads.length == 0) {
  59171. this._initHeightQuads();
  59172. this._computeHeightQuads();
  59173. }
  59174. var facet = this._getFacetAt(x, z);
  59175. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59176. // return y in the World system
  59177. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59178. return tmpVect.y;
  59179. };
  59180. /**
  59181. * Returns a normalized vector (Vector3) orthogonal to the ground
  59182. * at the ground coordinates (x, z) expressed in the World system.
  59183. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59184. */
  59185. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59186. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59187. this.getNormalAtCoordinatesToRef(x, z, normal);
  59188. return normal;
  59189. };
  59190. /**
  59191. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59192. * at the ground coordinates (x, z) expressed in the World system.
  59193. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59194. * Returns the GroundMesh.
  59195. */
  59196. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59197. var world = this.getWorldMatrix();
  59198. var tmpMat = BABYLON.Tmp.Matrix[5];
  59199. world.invertToRef(tmpMat);
  59200. var tmpVect = BABYLON.Tmp.Vector3[8];
  59201. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59202. x = tmpVect.x;
  59203. z = tmpVect.z;
  59204. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59205. return this;
  59206. }
  59207. if (!this._heightQuads || this._heightQuads.length == 0) {
  59208. this._initHeightQuads();
  59209. this._computeHeightQuads();
  59210. }
  59211. var facet = this._getFacetAt(x, z);
  59212. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59213. return this;
  59214. };
  59215. /**
  59216. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59217. * if the ground has been updated.
  59218. * This can be used in the render loop.
  59219. * Returns the GroundMesh.
  59220. */
  59221. GroundMesh.prototype.updateCoordinateHeights = function () {
  59222. if (!this._heightQuads || this._heightQuads.length == 0) {
  59223. this._initHeightQuads();
  59224. }
  59225. this._computeHeightQuads();
  59226. return this;
  59227. };
  59228. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59229. GroundMesh.prototype._getFacetAt = function (x, z) {
  59230. // retrieve col and row from x, z coordinates in the ground local system
  59231. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59232. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59233. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59234. var facet;
  59235. if (z < quad.slope.x * x + quad.slope.y) {
  59236. facet = quad.facet1;
  59237. }
  59238. else {
  59239. facet = quad.facet2;
  59240. }
  59241. return facet;
  59242. };
  59243. // Creates and populates the heightMap array with "facet" elements :
  59244. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59245. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59246. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59247. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59248. // Returns the GroundMesh.
  59249. GroundMesh.prototype._initHeightQuads = function () {
  59250. var subdivisionsX = this._subdivisionsX;
  59251. var subdivisionsY = this._subdivisionsY;
  59252. this._heightQuads = new Array();
  59253. for (var row = 0; row < subdivisionsY; row++) {
  59254. for (var col = 0; col < subdivisionsX; col++) {
  59255. 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) };
  59256. this._heightQuads[row * subdivisionsX + col] = quad;
  59257. }
  59258. }
  59259. return this;
  59260. };
  59261. // Compute each quad element values and update the the heightMap array :
  59262. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59263. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59264. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59265. // Returns the GroundMesh.
  59266. GroundMesh.prototype._computeHeightQuads = function () {
  59267. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59268. if (!positions) {
  59269. return this;
  59270. }
  59271. var v1 = BABYLON.Tmp.Vector3[3];
  59272. var v2 = BABYLON.Tmp.Vector3[2];
  59273. var v3 = BABYLON.Tmp.Vector3[1];
  59274. var v4 = BABYLON.Tmp.Vector3[0];
  59275. var v1v2 = BABYLON.Tmp.Vector3[4];
  59276. var v1v3 = BABYLON.Tmp.Vector3[5];
  59277. var v1v4 = BABYLON.Tmp.Vector3[6];
  59278. var norm1 = BABYLON.Tmp.Vector3[7];
  59279. var norm2 = BABYLON.Tmp.Vector3[8];
  59280. var i = 0;
  59281. var j = 0;
  59282. var k = 0;
  59283. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59284. var h = 0;
  59285. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59286. var d2 = 0;
  59287. var subdivisionsX = this._subdivisionsX;
  59288. var subdivisionsY = this._subdivisionsY;
  59289. for (var row = 0; row < subdivisionsY; row++) {
  59290. for (var col = 0; col < subdivisionsX; col++) {
  59291. i = col * 3;
  59292. j = row * (subdivisionsX + 1) * 3;
  59293. k = (row + 1) * (subdivisionsX + 1) * 3;
  59294. v1.x = positions[j + i];
  59295. v1.y = positions[j + i + 1];
  59296. v1.z = positions[j + i + 2];
  59297. v2.x = positions[j + i + 3];
  59298. v2.y = positions[j + i + 4];
  59299. v2.z = positions[j + i + 5];
  59300. v3.x = positions[k + i];
  59301. v3.y = positions[k + i + 1];
  59302. v3.z = positions[k + i + 2];
  59303. v4.x = positions[k + i + 3];
  59304. v4.y = positions[k + i + 4];
  59305. v4.z = positions[k + i + 5];
  59306. // 2D slope V1V4
  59307. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59308. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59309. // facet equations :
  59310. // we compute each facet normal vector
  59311. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59312. // we compute the value d by applying the equation to v1 which belongs to the plane
  59313. // then we store the facet equation in a Vector4
  59314. v2.subtractToRef(v1, v1v2);
  59315. v3.subtractToRef(v1, v1v3);
  59316. v4.subtractToRef(v1, v1v4);
  59317. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59318. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59319. norm1.normalize();
  59320. norm2.normalize();
  59321. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59322. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59323. var quad = this._heightQuads[row * subdivisionsX + col];
  59324. quad.slope.copyFromFloats(cd, h);
  59325. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59326. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59327. }
  59328. }
  59329. return this;
  59330. };
  59331. GroundMesh.prototype.serialize = function (serializationObject) {
  59332. _super.prototype.serialize.call(this, serializationObject);
  59333. serializationObject.subdivisionsX = this._subdivisionsX;
  59334. serializationObject.subdivisionsY = this._subdivisionsY;
  59335. serializationObject.minX = this._minX;
  59336. serializationObject.maxX = this._maxX;
  59337. serializationObject.minZ = this._minZ;
  59338. serializationObject.maxZ = this._maxZ;
  59339. serializationObject.width = this._width;
  59340. serializationObject.height = this._height;
  59341. };
  59342. GroundMesh.Parse = function (parsedMesh, scene) {
  59343. var result = new GroundMesh(parsedMesh.name, scene);
  59344. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59345. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59346. result._minX = parsedMesh.minX;
  59347. result._maxX = parsedMesh.maxX;
  59348. result._minZ = parsedMesh.minZ;
  59349. result._maxZ = parsedMesh.maxZ;
  59350. result._width = parsedMesh.width;
  59351. result._height = parsedMesh.height;
  59352. return result;
  59353. };
  59354. return GroundMesh;
  59355. }(BABYLON.Mesh));
  59356. BABYLON.GroundMesh = GroundMesh;
  59357. })(BABYLON || (BABYLON = {}));
  59358. //# sourceMappingURL=babylon.groundMesh.js.map
  59359. var BABYLON;
  59360. (function (BABYLON) {
  59361. /**
  59362. * Creates an instance based on a source mesh.
  59363. */
  59364. var InstancedMesh = /** @class */ (function (_super) {
  59365. __extends(InstancedMesh, _super);
  59366. function InstancedMesh(name, source) {
  59367. var _this = _super.call(this, name, source.getScene()) || this;
  59368. source.instances.push(_this);
  59369. _this._sourceMesh = source;
  59370. _this.position.copyFrom(source.position);
  59371. _this.rotation.copyFrom(source.rotation);
  59372. _this.scaling.copyFrom(source.scaling);
  59373. if (source.rotationQuaternion) {
  59374. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59375. }
  59376. _this.infiniteDistance = source.infiniteDistance;
  59377. _this.setPivotMatrix(source.getPivotMatrix());
  59378. _this.refreshBoundingInfo();
  59379. _this._syncSubMeshes();
  59380. return _this;
  59381. }
  59382. /**
  59383. * Returns the string "InstancedMesh".
  59384. */
  59385. InstancedMesh.prototype.getClassName = function () {
  59386. return "InstancedMesh";
  59387. };
  59388. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59389. // Methods
  59390. get: function () {
  59391. return this._sourceMesh.receiveShadows;
  59392. },
  59393. enumerable: true,
  59394. configurable: true
  59395. });
  59396. Object.defineProperty(InstancedMesh.prototype, "material", {
  59397. get: function () {
  59398. return this._sourceMesh.material;
  59399. },
  59400. enumerable: true,
  59401. configurable: true
  59402. });
  59403. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59404. get: function () {
  59405. return this._sourceMesh.visibility;
  59406. },
  59407. enumerable: true,
  59408. configurable: true
  59409. });
  59410. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59411. get: function () {
  59412. return this._sourceMesh.skeleton;
  59413. },
  59414. enumerable: true,
  59415. configurable: true
  59416. });
  59417. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59418. get: function () {
  59419. return this._sourceMesh.renderingGroupId;
  59420. },
  59421. set: function (value) {
  59422. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59423. return;
  59424. }
  59425. //no-op with warning
  59426. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59427. },
  59428. enumerable: true,
  59429. configurable: true
  59430. });
  59431. /**
  59432. * Returns the total number of vertices (integer).
  59433. */
  59434. InstancedMesh.prototype.getTotalVertices = function () {
  59435. return this._sourceMesh.getTotalVertices();
  59436. };
  59437. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59438. get: function () {
  59439. return this._sourceMesh;
  59440. },
  59441. enumerable: true,
  59442. configurable: true
  59443. });
  59444. /**
  59445. * Is this node ready to be used/rendered
  59446. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59447. * @return {boolean} is it ready
  59448. */
  59449. InstancedMesh.prototype.isReady = function (completeCheck) {
  59450. if (completeCheck === void 0) { completeCheck = false; }
  59451. return this._sourceMesh.isReady(completeCheck, true);
  59452. };
  59453. /**
  59454. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59455. */
  59456. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59457. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59458. };
  59459. /**
  59460. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59461. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59462. * The `data` are either a numeric array either a Float32Array.
  59463. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59464. * 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).
  59465. * Note that a new underlying VertexBuffer object is created each call.
  59466. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59467. *
  59468. * Possible `kind` values :
  59469. * - BABYLON.VertexBuffer.PositionKind
  59470. * - BABYLON.VertexBuffer.UVKind
  59471. * - BABYLON.VertexBuffer.UV2Kind
  59472. * - BABYLON.VertexBuffer.UV3Kind
  59473. * - BABYLON.VertexBuffer.UV4Kind
  59474. * - BABYLON.VertexBuffer.UV5Kind
  59475. * - BABYLON.VertexBuffer.UV6Kind
  59476. * - BABYLON.VertexBuffer.ColorKind
  59477. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59478. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59479. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59480. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59481. *
  59482. * Returns the Mesh.
  59483. */
  59484. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59485. if (this.sourceMesh) {
  59486. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59487. }
  59488. return this.sourceMesh;
  59489. };
  59490. /**
  59491. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59492. * If the mesh has no geometry, it is simply returned as it is.
  59493. * The `data` are either a numeric array either a Float32Array.
  59494. * No new underlying VertexBuffer object is created.
  59495. * 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.
  59496. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59497. *
  59498. * Possible `kind` values :
  59499. * - BABYLON.VertexBuffer.PositionKind
  59500. * - BABYLON.VertexBuffer.UVKind
  59501. * - BABYLON.VertexBuffer.UV2Kind
  59502. * - BABYLON.VertexBuffer.UV3Kind
  59503. * - BABYLON.VertexBuffer.UV4Kind
  59504. * - BABYLON.VertexBuffer.UV5Kind
  59505. * - BABYLON.VertexBuffer.UV6Kind
  59506. * - BABYLON.VertexBuffer.ColorKind
  59507. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59508. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59509. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59510. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59511. *
  59512. * Returns the Mesh.
  59513. */
  59514. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59515. if (this.sourceMesh) {
  59516. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59517. }
  59518. return this.sourceMesh;
  59519. };
  59520. /**
  59521. * Sets the mesh indices.
  59522. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59523. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59524. * This method creates a new index buffer each call.
  59525. * Returns the Mesh.
  59526. */
  59527. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59528. if (totalVertices === void 0) { totalVertices = null; }
  59529. if (this.sourceMesh) {
  59530. this.sourceMesh.setIndices(indices, totalVertices);
  59531. }
  59532. return this.sourceMesh;
  59533. };
  59534. /**
  59535. * Boolean : True if the mesh owns the requested kind of data.
  59536. */
  59537. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59538. return this._sourceMesh.isVerticesDataPresent(kind);
  59539. };
  59540. /**
  59541. * Returns an array of indices (IndicesArray).
  59542. */
  59543. InstancedMesh.prototype.getIndices = function () {
  59544. return this._sourceMesh.getIndices();
  59545. };
  59546. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59547. get: function () {
  59548. return this._sourceMesh._positions;
  59549. },
  59550. enumerable: true,
  59551. configurable: true
  59552. });
  59553. /**
  59554. * Sets a new updated BoundingInfo to the mesh.
  59555. * Returns the mesh.
  59556. */
  59557. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59558. var meshBB = this._sourceMesh.getBoundingInfo();
  59559. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59560. this._updateBoundingInfo();
  59561. return this;
  59562. };
  59563. InstancedMesh.prototype._preActivate = function () {
  59564. if (this._currentLOD) {
  59565. this._currentLOD._preActivate();
  59566. }
  59567. return this;
  59568. };
  59569. InstancedMesh.prototype._activate = function (renderId) {
  59570. if (this._currentLOD) {
  59571. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59572. }
  59573. return this;
  59574. };
  59575. /**
  59576. * Returns the current associated LOD AbstractMesh.
  59577. */
  59578. InstancedMesh.prototype.getLOD = function (camera) {
  59579. if (!camera) {
  59580. return this;
  59581. }
  59582. var boundingInfo = this.getBoundingInfo();
  59583. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59584. if (this._currentLOD === this.sourceMesh) {
  59585. return this;
  59586. }
  59587. return this._currentLOD;
  59588. };
  59589. InstancedMesh.prototype._syncSubMeshes = function () {
  59590. this.releaseSubMeshes();
  59591. if (this._sourceMesh.subMeshes) {
  59592. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59593. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59594. }
  59595. }
  59596. return this;
  59597. };
  59598. InstancedMesh.prototype._generatePointsArray = function () {
  59599. return this._sourceMesh._generatePointsArray();
  59600. };
  59601. /**
  59602. * Creates a new InstancedMesh from the current mesh.
  59603. * - name (string) : the cloned mesh name
  59604. * - newParent (optional Node) : the optional Node to parent the clone to.
  59605. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59606. *
  59607. * Returns the clone.
  59608. */
  59609. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59610. var result = this._sourceMesh.createInstance(name);
  59611. // Deep copy
  59612. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59613. // Bounding info
  59614. this.refreshBoundingInfo();
  59615. // Parent
  59616. if (newParent) {
  59617. result.parent = newParent;
  59618. }
  59619. if (!doNotCloneChildren) {
  59620. // Children
  59621. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59622. var mesh = this.getScene().meshes[index];
  59623. if (mesh.parent === this) {
  59624. mesh.clone(mesh.name, result);
  59625. }
  59626. }
  59627. }
  59628. result.computeWorldMatrix(true);
  59629. return result;
  59630. };
  59631. /**
  59632. * Disposes the InstancedMesh.
  59633. * Returns nothing.
  59634. */
  59635. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59636. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59637. // Remove from mesh
  59638. var index = this._sourceMesh.instances.indexOf(this);
  59639. this._sourceMesh.instances.splice(index, 1);
  59640. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59641. };
  59642. return InstancedMesh;
  59643. }(BABYLON.AbstractMesh));
  59644. BABYLON.InstancedMesh = InstancedMesh;
  59645. })(BABYLON || (BABYLON = {}));
  59646. //# sourceMappingURL=babylon.instancedMesh.js.map
  59647. var BABYLON;
  59648. (function (BABYLON) {
  59649. var LinesMesh = /** @class */ (function (_super) {
  59650. __extends(LinesMesh, _super);
  59651. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59652. if (scene === void 0) { scene = null; }
  59653. if (parent === void 0) { parent = null; }
  59654. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59655. _this.useVertexColor = useVertexColor;
  59656. _this.useVertexAlpha = useVertexAlpha;
  59657. _this.color = new BABYLON.Color3(1, 1, 1);
  59658. _this.alpha = 1;
  59659. if (source) {
  59660. _this.color = source.color.clone();
  59661. _this.alpha = source.alpha;
  59662. _this.useVertexColor = source.useVertexColor;
  59663. _this.useVertexAlpha = source.useVertexAlpha;
  59664. }
  59665. _this._intersectionThreshold = 0.1;
  59666. var defines = [];
  59667. var options = {
  59668. attributes: [BABYLON.VertexBuffer.PositionKind],
  59669. uniforms: ["world", "viewProjection"],
  59670. needAlphaBlending: true,
  59671. defines: defines
  59672. };
  59673. if (useVertexAlpha === false) {
  59674. options.needAlphaBlending = false;
  59675. }
  59676. if (!useVertexColor) {
  59677. options.uniforms.push("color");
  59678. }
  59679. else {
  59680. options.defines.push("#define VERTEXCOLOR");
  59681. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59682. }
  59683. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59684. return _this;
  59685. }
  59686. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59687. /**
  59688. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59689. * This margin is expressed in world space coordinates, so its value may vary.
  59690. * Default value is 0.1
  59691. * @returns the intersection Threshold value.
  59692. */
  59693. get: function () {
  59694. return this._intersectionThreshold;
  59695. },
  59696. /**
  59697. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59698. * This margin is expressed in world space coordinates, so its value may vary.
  59699. * @param value the new threshold to apply
  59700. */
  59701. set: function (value) {
  59702. if (this._intersectionThreshold === value) {
  59703. return;
  59704. }
  59705. this._intersectionThreshold = value;
  59706. if (this.geometry) {
  59707. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59708. }
  59709. },
  59710. enumerable: true,
  59711. configurable: true
  59712. });
  59713. /**
  59714. * Returns the string "LineMesh"
  59715. */
  59716. LinesMesh.prototype.getClassName = function () {
  59717. return "LinesMesh";
  59718. };
  59719. Object.defineProperty(LinesMesh.prototype, "material", {
  59720. get: function () {
  59721. return this._colorShader;
  59722. },
  59723. set: function (value) {
  59724. // Do nothing
  59725. },
  59726. enumerable: true,
  59727. configurable: true
  59728. });
  59729. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59730. get: function () {
  59731. return false;
  59732. },
  59733. enumerable: true,
  59734. configurable: true
  59735. });
  59736. LinesMesh.prototype.createInstance = function (name) {
  59737. throw new Error("LinesMeshes do not support createInstance.");
  59738. };
  59739. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59740. if (!this._geometry) {
  59741. return this;
  59742. }
  59743. // VBOs
  59744. this._geometry._bind(this._colorShader.getEffect());
  59745. // Color
  59746. if (!this.useVertexColor) {
  59747. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59748. }
  59749. return this;
  59750. };
  59751. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59752. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59753. return this;
  59754. }
  59755. var engine = this.getScene().getEngine();
  59756. // Draw order
  59757. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59758. return this;
  59759. };
  59760. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59761. this._colorShader.dispose();
  59762. _super.prototype.dispose.call(this, doNotRecurse);
  59763. };
  59764. /**
  59765. * Returns a new LineMesh object cloned from the current one.
  59766. */
  59767. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59768. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59769. };
  59770. return LinesMesh;
  59771. }(BABYLON.Mesh));
  59772. BABYLON.LinesMesh = LinesMesh;
  59773. })(BABYLON || (BABYLON = {}));
  59774. //# sourceMappingURL=babylon.linesMesh.js.map
  59775. var BABYLON;
  59776. (function (BABYLON) {
  59777. /**
  59778. * Class containing static functions to help procedurally build meshes
  59779. */
  59780. var MeshBuilder = /** @class */ (function () {
  59781. function MeshBuilder() {
  59782. }
  59783. MeshBuilder.updateSideOrientation = function (orientation) {
  59784. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59785. return BABYLON.Mesh.DOUBLESIDE;
  59786. }
  59787. if (orientation === undefined || orientation === null) {
  59788. return BABYLON.Mesh.FRONTSIDE;
  59789. }
  59790. return orientation;
  59791. };
  59792. /**
  59793. * Creates a box mesh
  59794. * * The parameter `size` sets the size (float) of each box side (default 1)
  59795. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59796. * * 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)
  59797. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59798. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59799. * * 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
  59800. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59801. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59802. * @param name defines the name of the mesh
  59803. * @param options defines the options used to create the mesh
  59804. * @param scene defines the hosting scene
  59805. * @returns the box mesh
  59806. */
  59807. MeshBuilder.CreateBox = function (name, options, scene) {
  59808. if (scene === void 0) { scene = null; }
  59809. var box = new BABYLON.Mesh(name, scene);
  59810. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59811. box._originalBuilderSideOrientation = options.sideOrientation;
  59812. var vertexData = BABYLON.VertexData.CreateBox(options);
  59813. vertexData.applyToMesh(box, options.updatable);
  59814. return box;
  59815. };
  59816. /**
  59817. * Creates a sphere mesh
  59818. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59819. * * 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`)
  59820. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59821. * * 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
  59822. * * 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)
  59823. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59824. * * 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
  59825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59826. * @param name defines the name of the mesh
  59827. * @param options defines the options used to create the mesh
  59828. * @param scene defines the hosting scene
  59829. * @returns the sphere mesh
  59830. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59831. */
  59832. MeshBuilder.CreateSphere = function (name, options, scene) {
  59833. var sphere = new BABYLON.Mesh(name, scene);
  59834. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59835. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59836. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59837. vertexData.applyToMesh(sphere, options.updatable);
  59838. return sphere;
  59839. };
  59840. /**
  59841. * Creates a plane polygonal mesh. By default, this is a disc
  59842. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59843. * * 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
  59844. * * 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
  59845. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59846. * * 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
  59847. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59848. * @param name defines the name of the mesh
  59849. * @param options defines the options used to create the mesh
  59850. * @param scene defines the hosting scene
  59851. * @returns the plane polygonal mesh
  59852. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  59853. */
  59854. MeshBuilder.CreateDisc = function (name, options, scene) {
  59855. if (scene === void 0) { scene = null; }
  59856. var disc = new BABYLON.Mesh(name, scene);
  59857. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59858. disc._originalBuilderSideOrientation = options.sideOrientation;
  59859. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59860. vertexData.applyToMesh(disc, options.updatable);
  59861. return disc;
  59862. };
  59863. /**
  59864. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59865. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59866. * * 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`)
  59867. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59868. * * 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
  59869. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59870. * * 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
  59871. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59872. * @param name defines the name of the mesh
  59873. * @param options defines the options used to create the mesh
  59874. * @param scene defines the hosting scene
  59875. * @returns the icosahedron mesh
  59876. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  59877. */
  59878. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59879. var sphere = new BABYLON.Mesh(name, scene);
  59880. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59881. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59882. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59883. vertexData.applyToMesh(sphere, options.updatable);
  59884. return sphere;
  59885. };
  59886. ;
  59887. /**
  59888. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59889. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59890. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59891. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59892. * * 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
  59893. * * 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
  59894. * * 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
  59895. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59896. * * 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
  59897. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59898. * * 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
  59899. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59900. * * 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
  59901. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59902. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59903. * @param name defines the name of the mesh
  59904. * @param options defines the options used to create the mesh
  59905. * @param scene defines the hosting scene
  59906. * @returns the ribbon mesh
  59907. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59908. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59909. */
  59910. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59911. if (scene === void 0) { scene = null; }
  59912. var pathArray = options.pathArray;
  59913. var closeArray = options.closeArray;
  59914. var closePath = options.closePath;
  59915. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59916. var instance = options.instance;
  59917. var updatable = options.updatable;
  59918. if (instance) { // existing ribbon instance update
  59919. // positionFunction : ribbon case
  59920. // only pathArray and sideOrientation parameters are taken into account for positions update
  59921. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59922. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59923. var positionFunction = function (positions) {
  59924. var minlg = pathArray[0].length;
  59925. var i = 0;
  59926. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59927. for (var si = 1; si <= ns; si++) {
  59928. for (var p = 0; p < pathArray.length; p++) {
  59929. var path = pathArray[p];
  59930. var l = path.length;
  59931. minlg = (minlg < l) ? minlg : l;
  59932. var j = 0;
  59933. while (j < minlg) {
  59934. positions[i] = path[j].x;
  59935. positions[i + 1] = path[j].y;
  59936. positions[i + 2] = path[j].z;
  59937. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59938. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59939. }
  59940. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59941. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59942. }
  59943. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59944. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59945. }
  59946. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59947. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59948. }
  59949. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59950. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59951. }
  59952. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59953. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59954. }
  59955. j++;
  59956. i += 3;
  59957. }
  59958. if (instance._closePath) {
  59959. positions[i] = path[0].x;
  59960. positions[i + 1] = path[0].y;
  59961. positions[i + 2] = path[0].z;
  59962. i += 3;
  59963. }
  59964. }
  59965. }
  59966. };
  59967. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59968. positionFunction(positions);
  59969. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59970. instance._boundingInfo.update(instance._worldMatrix);
  59971. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59972. if (options.colors) {
  59973. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59974. for (var c = 0; c < options.colors.length; c++) {
  59975. colors[c * 4] = options.colors[c].r;
  59976. colors[c * 4 + 1] = options.colors[c].g;
  59977. colors[c * 4 + 2] = options.colors[c].b;
  59978. colors[c * 4 + 3] = options.colors[c].a;
  59979. }
  59980. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59981. }
  59982. if (options.uvs) {
  59983. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59984. for (var i = 0; i < options.uvs.length; i++) {
  59985. uvs[i * 2] = options.uvs[i].x;
  59986. uvs[i * 2 + 1] = options.uvs[i].y;
  59987. }
  59988. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59989. }
  59990. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59991. var indices = instance.getIndices();
  59992. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59993. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59994. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59995. if (instance._closePath) {
  59996. var indexFirst = 0;
  59997. var indexLast = 0;
  59998. for (var p = 0; p < pathArray.length; p++) {
  59999. indexFirst = instance._idx[p] * 3;
  60000. if (p + 1 < pathArray.length) {
  60001. indexLast = (instance._idx[p + 1] - 1) * 3;
  60002. }
  60003. else {
  60004. indexLast = normals.length - 3;
  60005. }
  60006. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60007. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60008. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60009. normals[indexLast] = normals[indexFirst];
  60010. normals[indexLast + 1] = normals[indexFirst + 1];
  60011. normals[indexLast + 2] = normals[indexFirst + 2];
  60012. }
  60013. }
  60014. if (!(instance.areNormalsFrozen)) {
  60015. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60016. }
  60017. }
  60018. return instance;
  60019. }
  60020. else { // new ribbon creation
  60021. var ribbon = new BABYLON.Mesh(name, scene);
  60022. ribbon._originalBuilderSideOrientation = sideOrientation;
  60023. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60024. if (closePath) {
  60025. ribbon._idx = vertexData._idx;
  60026. }
  60027. ribbon._closePath = closePath;
  60028. ribbon._closeArray = closeArray;
  60029. vertexData.applyToMesh(ribbon, updatable);
  60030. return ribbon;
  60031. }
  60032. };
  60033. /**
  60034. * Creates a cylinder or a cone mesh
  60035. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60036. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60037. * * 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.
  60038. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60039. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60040. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60041. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60042. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60043. * * 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).
  60044. * * 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
  60045. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60046. * * 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
  60047. * * 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.
  60048. * * If `enclose` is false, a ring surface is one element.
  60049. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60050. * * 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
  60051. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60052. * * 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
  60053. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60054. * @param name defines the name of the mesh
  60055. * @param options defines the options used to create the mesh
  60056. * @param scene defines the hosting scene
  60057. * @returns the cylinder mesh
  60058. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60059. */
  60060. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60061. var cylinder = new BABYLON.Mesh(name, scene);
  60062. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60063. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60064. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60065. vertexData.applyToMesh(cylinder, options.updatable);
  60066. return cylinder;
  60067. };
  60068. /**
  60069. * Creates a torus mesh
  60070. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60071. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60072. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60073. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60074. * * 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
  60075. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60076. * @param name defines the name of the mesh
  60077. * @param options defines the options used to create the mesh
  60078. * @param scene defines the hosting scene
  60079. * @returns the torus mesh
  60080. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60081. */
  60082. MeshBuilder.CreateTorus = function (name, options, scene) {
  60083. var torus = new BABYLON.Mesh(name, scene);
  60084. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60085. torus._originalBuilderSideOrientation = options.sideOrientation;
  60086. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60087. vertexData.applyToMesh(torus, options.updatable);
  60088. return torus;
  60089. };
  60090. /**
  60091. * Creates a torus knot mesh
  60092. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60093. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60094. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60095. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60096. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60097. * * 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
  60098. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60099. * @param name defines the name of the mesh
  60100. * @param options defines the options used to create the mesh
  60101. * @param scene defines the hosting scene
  60102. * @returns the torus knot mesh
  60103. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60104. */
  60105. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60106. var torusKnot = new BABYLON.Mesh(name, scene);
  60107. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60108. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60109. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60110. vertexData.applyToMesh(torusKnot, options.updatable);
  60111. return torusKnot;
  60112. };
  60113. /**
  60114. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60115. * * 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
  60116. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60117. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60118. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60119. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60120. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60121. * * 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
  60122. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60123. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60124. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60125. * @param name defines the name of the new line system
  60126. * @param options defines the options used to create the line system
  60127. * @param scene defines the hosting scene
  60128. * @returns a new line system mesh
  60129. */
  60130. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60131. var instance = options.instance;
  60132. var lines = options.lines;
  60133. var colors = options.colors;
  60134. if (instance) { // lines update
  60135. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60136. var vertexColor;
  60137. var lineColors;
  60138. if (colors) {
  60139. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60140. }
  60141. var i = 0;
  60142. var c = 0;
  60143. for (var l = 0; l < lines.length; l++) {
  60144. var points = lines[l];
  60145. for (var p = 0; p < points.length; p++) {
  60146. positions[i] = points[p].x;
  60147. positions[i + 1] = points[p].y;
  60148. positions[i + 2] = points[p].z;
  60149. if (colors && vertexColor) {
  60150. lineColors = colors[l];
  60151. vertexColor[c] = lineColors[p].r;
  60152. vertexColor[c + 1] = lineColors[p].g;
  60153. vertexColor[c + 2] = lineColors[p].b;
  60154. vertexColor[c + 3] = lineColors[p].a;
  60155. c += 4;
  60156. }
  60157. i += 3;
  60158. }
  60159. }
  60160. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60161. if (colors && vertexColor) {
  60162. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60163. }
  60164. return instance;
  60165. }
  60166. // line system creation
  60167. var useVertexColor = (colors) ? true : false;
  60168. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60169. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60170. vertexData.applyToMesh(lineSystem, options.updatable);
  60171. return lineSystem;
  60172. };
  60173. /**
  60174. * Creates a line mesh
  60175. * 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
  60176. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60177. * * The parameter `points` is an array successive Vector3
  60178. * * 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
  60179. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60180. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60181. * * When updating an instance, remember that only point positions can change, not the number of points
  60182. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60183. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60184. * @param name defines the name of the new line system
  60185. * @param options defines the options used to create the line system
  60186. * @param scene defines the hosting scene
  60187. * @returns a new line mesh
  60188. */
  60189. MeshBuilder.CreateLines = function (name, options, scene) {
  60190. if (scene === void 0) { scene = null; }
  60191. var colors = (options.colors) ? [options.colors] : null;
  60192. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60193. return lines;
  60194. };
  60195. /**
  60196. * Creates a dashed line mesh
  60197. * * 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
  60198. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60199. * * The parameter `points` is an array successive Vector3
  60200. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60201. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60202. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60203. * * 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
  60204. * * When updating an instance, remember that only point positions can change, not the number of points
  60205. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60206. * @param name defines the name of the mesh
  60207. * @param options defines the options used to create the mesh
  60208. * @param scene defines the hosting scene
  60209. * @returns the dashed line mesh
  60210. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60211. */
  60212. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60213. if (scene === void 0) { scene = null; }
  60214. var points = options.points;
  60215. var instance = options.instance;
  60216. var gapSize = options.gapSize || 1;
  60217. var dashSize = options.dashSize || 3;
  60218. if (instance) { // dashed lines update
  60219. var positionFunction = function (positions) {
  60220. var curvect = BABYLON.Vector3.Zero();
  60221. var nbSeg = positions.length / 6;
  60222. var lg = 0;
  60223. var nb = 0;
  60224. var shft = 0;
  60225. var dashshft = 0;
  60226. var curshft = 0;
  60227. var p = 0;
  60228. var i = 0;
  60229. var j = 0;
  60230. for (i = 0; i < points.length - 1; i++) {
  60231. points[i + 1].subtractToRef(points[i], curvect);
  60232. lg += curvect.length();
  60233. }
  60234. shft = lg / nbSeg;
  60235. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60236. for (i = 0; i < points.length - 1; i++) {
  60237. points[i + 1].subtractToRef(points[i], curvect);
  60238. nb = Math.floor(curvect.length() / shft);
  60239. curvect.normalize();
  60240. j = 0;
  60241. while (j < nb && p < positions.length) {
  60242. curshft = shft * j;
  60243. positions[p] = points[i].x + curshft * curvect.x;
  60244. positions[p + 1] = points[i].y + curshft * curvect.y;
  60245. positions[p + 2] = points[i].z + curshft * curvect.z;
  60246. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60247. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60248. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60249. p += 6;
  60250. j++;
  60251. }
  60252. }
  60253. while (p < positions.length) {
  60254. positions[p] = points[i].x;
  60255. positions[p + 1] = points[i].y;
  60256. positions[p + 2] = points[i].z;
  60257. p += 3;
  60258. }
  60259. };
  60260. instance.updateMeshPositions(positionFunction, false);
  60261. return instance;
  60262. }
  60263. // dashed lines creation
  60264. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60265. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60266. vertexData.applyToMesh(dashedLines, options.updatable);
  60267. dashedLines.dashSize = dashSize;
  60268. dashedLines.gapSize = gapSize;
  60269. return dashedLines;
  60270. };
  60271. /**
  60272. * 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.
  60273. * * 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.
  60274. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60275. * * 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.
  60276. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60277. * * 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
  60278. * * 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
  60279. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60280. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60281. * * 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
  60282. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60283. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60284. * @param name defines the name of the mesh
  60285. * @param options defines the options used to create the mesh
  60286. * @param scene defines the hosting scene
  60287. * @returns the extruded shape mesh
  60288. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60289. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60290. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60291. */
  60292. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60293. if (scene === void 0) { scene = null; }
  60294. var path = options.path;
  60295. var shape = options.shape;
  60296. var scale = options.scale || 1;
  60297. var rotation = options.rotation || 0;
  60298. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60299. var updatable = options.updatable;
  60300. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60301. var instance = options.instance || null;
  60302. var invertUV = options.invertUV || false;
  60303. 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);
  60304. };
  60305. /**
  60306. * Creates an custom extruded shape mesh.
  60307. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60308. * * 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.
  60309. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60310. * * 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
  60311. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60312. * * 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
  60313. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60314. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60315. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60316. * * 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
  60317. * * 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
  60318. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60319. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60320. * * 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
  60321. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60322. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60323. * @param name defines the name of the mesh
  60324. * @param options defines the options used to create the mesh
  60325. * @param scene defines the hosting scene
  60326. * @returns the custom extruded shape mesh
  60327. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60328. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60329. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60330. */
  60331. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60332. var path = options.path;
  60333. var shape = options.shape;
  60334. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60335. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60336. var ribbonCloseArray = options.ribbonCloseArray || false;
  60337. var ribbonClosePath = options.ribbonClosePath || false;
  60338. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60339. var updatable = options.updatable;
  60340. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60341. var instance = options.instance;
  60342. var invertUV = options.invertUV || false;
  60343. 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);
  60344. };
  60345. /**
  60346. * Creates lathe mesh.
  60347. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60348. * * 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
  60349. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60350. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60351. * * 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
  60352. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60353. * * 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
  60354. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60355. * * 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
  60356. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60357. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60358. * @param name defines the name of the mesh
  60359. * @param options defines the options used to create the mesh
  60360. * @param scene defines the hosting scene
  60361. * @returns the lathe mesh
  60362. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60363. */
  60364. MeshBuilder.CreateLathe = function (name, options, scene) {
  60365. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60366. var closed = (options.closed === undefined) ? true : options.closed;
  60367. var shape = options.shape;
  60368. var radius = options.radius || 1;
  60369. var tessellation = options.tessellation || 64;
  60370. var updatable = options.updatable;
  60371. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60372. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60373. var pi2 = Math.PI * 2;
  60374. var paths = new Array();
  60375. var invertUV = options.invertUV || false;
  60376. var i = 0;
  60377. var p = 0;
  60378. var step = pi2 / tessellation * arc;
  60379. var rotated;
  60380. var path = new Array();
  60381. for (i = 0; i <= tessellation; i++) {
  60382. var path = [];
  60383. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60384. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60385. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60386. }
  60387. for (p = 0; p < shape.length; p++) {
  60388. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60389. path.push(rotated);
  60390. }
  60391. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60392. 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));
  60393. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60394. }
  60395. paths.push(path);
  60396. }
  60397. // lathe ribbon
  60398. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60399. return lathe;
  60400. };
  60401. /**
  60402. * Creates a plane mesh
  60403. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60404. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60405. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60406. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60407. * * 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
  60408. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60409. * @param name defines the name of the mesh
  60410. * @param options defines the options used to create the mesh
  60411. * @param scene defines the hosting scene
  60412. * @returns the plane mesh
  60413. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60414. */
  60415. MeshBuilder.CreatePlane = function (name, options, scene) {
  60416. var plane = new BABYLON.Mesh(name, scene);
  60417. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60418. plane._originalBuilderSideOrientation = options.sideOrientation;
  60419. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60420. vertexData.applyToMesh(plane, options.updatable);
  60421. if (options.sourcePlane) {
  60422. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60423. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60424. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60425. plane.rotate(vectorProduct, product);
  60426. }
  60427. return plane;
  60428. };
  60429. /**
  60430. * Creates a ground mesh
  60431. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60432. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60433. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60434. * @param name defines the name of the mesh
  60435. * @param options defines the options used to create the mesh
  60436. * @param scene defines the hosting scene
  60437. * @returns the ground mesh
  60438. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60439. */
  60440. MeshBuilder.CreateGround = function (name, options, scene) {
  60441. var ground = new BABYLON.GroundMesh(name, scene);
  60442. ground._setReady(false);
  60443. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60444. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60445. ground._width = options.width || 1;
  60446. ground._height = options.height || 1;
  60447. ground._maxX = ground._width / 2;
  60448. ground._maxZ = ground._height / 2;
  60449. ground._minX = -ground._maxX;
  60450. ground._minZ = -ground._maxZ;
  60451. var vertexData = BABYLON.VertexData.CreateGround(options);
  60452. vertexData.applyToMesh(ground, options.updatable);
  60453. ground._setReady(true);
  60454. return ground;
  60455. };
  60456. /**
  60457. * Creates a tiled ground mesh
  60458. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60459. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60460. * * 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
  60461. * * 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
  60462. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60463. * @param name defines the name of the mesh
  60464. * @param options defines the options used to create the mesh
  60465. * @param scene defines the hosting scene
  60466. * @returns the tiled ground mesh
  60467. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60468. */
  60469. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60470. var tiledGround = new BABYLON.Mesh(name, scene);
  60471. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60472. vertexData.applyToMesh(tiledGround, options.updatable);
  60473. return tiledGround;
  60474. };
  60475. /**
  60476. * Creates a ground mesh from a height map
  60477. * * The parameter `url` sets the URL of the height map image resource.
  60478. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60479. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60480. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60481. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60482. * * 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.
  60483. * * 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).
  60484. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60485. * @param name defines the name of the mesh
  60486. * @param url defines the url to the height map
  60487. * @param options defines the options used to create the mesh
  60488. * @param scene defines the hosting scene
  60489. * @returns the ground mesh
  60490. * @see http://doc.babylonjs.com/babylon101/height_map
  60491. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60492. */
  60493. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60494. var width = options.width || 10.0;
  60495. var height = options.height || 10.0;
  60496. var subdivisions = options.subdivisions || 1 | 0;
  60497. var minHeight = options.minHeight || 0.0;
  60498. var maxHeight = options.maxHeight || 1.0;
  60499. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60500. var updatable = options.updatable;
  60501. var onReady = options.onReady;
  60502. var ground = new BABYLON.GroundMesh(name, scene);
  60503. ground._subdivisionsX = subdivisions;
  60504. ground._subdivisionsY = subdivisions;
  60505. ground._width = width;
  60506. ground._height = height;
  60507. ground._maxX = ground._width / 2.0;
  60508. ground._maxZ = ground._height / 2.0;
  60509. ground._minX = -ground._maxX;
  60510. ground._minZ = -ground._maxZ;
  60511. ground._setReady(false);
  60512. var onload = function (img) {
  60513. // Getting height map data
  60514. var canvas = document.createElement("canvas");
  60515. var context = canvas.getContext("2d");
  60516. if (!context) {
  60517. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60518. }
  60519. if (scene.isDisposed) {
  60520. return;
  60521. }
  60522. var bufferWidth = img.width;
  60523. var bufferHeight = img.height;
  60524. canvas.width = bufferWidth;
  60525. canvas.height = bufferHeight;
  60526. context.drawImage(img, 0, 0);
  60527. // Create VertexData from map data
  60528. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60529. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60530. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60531. width: width, height: height,
  60532. subdivisions: subdivisions,
  60533. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60534. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60535. });
  60536. vertexData.applyToMesh(ground, updatable);
  60537. //execute ready callback, if set
  60538. if (onReady) {
  60539. onReady(ground);
  60540. }
  60541. ground._setReady(true);
  60542. };
  60543. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60544. return ground;
  60545. };
  60546. /**
  60547. * Creates a polygon mesh
  60548. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60549. * * 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
  60550. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60551. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60552. * * 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)
  60553. * * Remember you can only change the shape positions, not their number when updating a polygon
  60554. * @param name defines the name of the mesh
  60555. * @param options defines the options used to create the mesh
  60556. * @param scene defines the hosting scene
  60557. * @returns the polygon mesh
  60558. */
  60559. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60560. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60561. var shape = options.shape;
  60562. var holes = options.holes || [];
  60563. var depth = options.depth || 0;
  60564. var contours = [];
  60565. var hole = [];
  60566. for (var i = 0; i < shape.length; i++) {
  60567. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60568. }
  60569. var epsilon = 0.00000001;
  60570. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60571. contours.pop();
  60572. }
  60573. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60574. for (var hNb = 0; hNb < holes.length; hNb++) {
  60575. hole = [];
  60576. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60577. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60578. }
  60579. polygonTriangulation.addHole(hole);
  60580. }
  60581. var polygon = polygonTriangulation.build(options.updatable, depth);
  60582. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60583. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60584. vertexData.applyToMesh(polygon, options.updatable);
  60585. return polygon;
  60586. };
  60587. ;
  60588. /**
  60589. * Creates an extruded polygon mesh, with depth in the Y direction.
  60590. * * 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)
  60591. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60592. * @param name defines the name of the mesh
  60593. * @param options defines the options used to create the mesh
  60594. * @param scene defines the hosting scene
  60595. * @returns the polygon mesh
  60596. */
  60597. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60598. return MeshBuilder.CreatePolygon(name, options, scene);
  60599. };
  60600. ;
  60601. /**
  60602. * Creates a tube mesh.
  60603. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60604. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60605. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60606. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60607. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60608. * * 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)
  60609. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60610. * * 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
  60611. * * 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
  60612. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60613. * * 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
  60614. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60615. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60616. * @param name defines the name of the mesh
  60617. * @param options defines the options used to create the mesh
  60618. * @param scene defines the hosting scene
  60619. * @returns the tube mesh
  60620. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60621. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60622. */
  60623. MeshBuilder.CreateTube = function (name, options, scene) {
  60624. var path = options.path;
  60625. var instance = options.instance;
  60626. var radius = 1.0;
  60627. if (instance) {
  60628. radius = instance.radius;
  60629. }
  60630. if (options.radius !== undefined) {
  60631. radius = options.radius;
  60632. }
  60633. ;
  60634. var tessellation = options.tessellation || 64 | 0;
  60635. var radiusFunction = options.radiusFunction || null;
  60636. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60637. var invertUV = options.invertUV || false;
  60638. var updatable = options.updatable;
  60639. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60640. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60641. // tube geometry
  60642. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60643. var tangents = path3D.getTangents();
  60644. var normals = path3D.getNormals();
  60645. var distances = path3D.getDistances();
  60646. var pi2 = Math.PI * 2;
  60647. var step = pi2 / tessellation * arc;
  60648. var returnRadius = function () { return radius; };
  60649. var radiusFunctionFinal = radiusFunction || returnRadius;
  60650. var circlePath;
  60651. var rad;
  60652. var normal;
  60653. var rotated;
  60654. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60655. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60656. for (var i = 0; i < path.length; i++) {
  60657. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60658. circlePath = Array(); // current circle array
  60659. normal = normals[i]; // current normal
  60660. for (var t = 0; t < tessellation; t++) {
  60661. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60662. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60663. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60664. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60665. circlePath[t] = rotated;
  60666. }
  60667. circlePaths[index] = circlePath;
  60668. index++;
  60669. }
  60670. // cap
  60671. var capPath = function (nbPoints, pathIndex) {
  60672. var pointCap = Array();
  60673. for (var i = 0; i < nbPoints; i++) {
  60674. pointCap.push(path[pathIndex]);
  60675. }
  60676. return pointCap;
  60677. };
  60678. switch (cap) {
  60679. case BABYLON.Mesh.NO_CAP:
  60680. break;
  60681. case BABYLON.Mesh.CAP_START:
  60682. circlePaths[0] = capPath(tessellation, 0);
  60683. circlePaths[1] = circlePaths[2].slice(0);
  60684. break;
  60685. case BABYLON.Mesh.CAP_END:
  60686. circlePaths[index] = circlePaths[index - 1].slice(0);
  60687. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60688. break;
  60689. case BABYLON.Mesh.CAP_ALL:
  60690. circlePaths[0] = capPath(tessellation, 0);
  60691. circlePaths[1] = circlePaths[2].slice(0);
  60692. circlePaths[index] = circlePaths[index - 1].slice(0);
  60693. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60694. break;
  60695. default:
  60696. break;
  60697. }
  60698. return circlePaths;
  60699. };
  60700. var path3D;
  60701. var pathArray;
  60702. if (instance) { // tube update
  60703. var arc = options.arc || instance.arc;
  60704. path3D = (instance.path3D).update(path);
  60705. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60706. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60707. instance.path3D = path3D;
  60708. instance.pathArray = pathArray;
  60709. instance.arc = arc;
  60710. instance.radius = radius;
  60711. return instance;
  60712. }
  60713. // tube creation
  60714. path3D = new BABYLON.Path3D(path);
  60715. var newPathArray = new Array();
  60716. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60717. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60718. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60719. tube.pathArray = pathArray;
  60720. tube.path3D = path3D;
  60721. tube.tessellation = tessellation;
  60722. tube.cap = cap;
  60723. tube.arc = options.arc;
  60724. tube.radius = radius;
  60725. return tube;
  60726. };
  60727. /**
  60728. * Creates a polyhedron mesh
  60729. * * 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
  60730. * * The parameter `size` (positive float, default 1) sets the polygon size
  60731. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60732. * * 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`
  60733. * * 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
  60734. * * 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)`)
  60735. * * 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
  60736. * * 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
  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 polyhedron mesh
  60744. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  60745. */
  60746. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60747. var polyhedron = new BABYLON.Mesh(name, scene);
  60748. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60749. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60750. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60751. vertexData.applyToMesh(polyhedron, options.updatable);
  60752. return polyhedron;
  60753. };
  60754. /**
  60755. * Creates a decal mesh.
  60756. * 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
  60757. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60758. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60759. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60760. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60761. * @param name defines the name of the mesh
  60762. * @param sourceMesh defines the mesh where the decal must be applied
  60763. * @param options defines the options used to create the mesh
  60764. * @param scene defines the hosting scene
  60765. * @returns the decal mesh
  60766. * @see http://doc.babylonjs.com/how_to/decals
  60767. */
  60768. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60769. var indices = sourceMesh.getIndices();
  60770. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60771. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60772. var position = options.position || BABYLON.Vector3.Zero();
  60773. var normal = options.normal || BABYLON.Vector3.Up();
  60774. var size = options.size || BABYLON.Vector3.One();
  60775. var angle = options.angle || 0;
  60776. // Getting correct rotation
  60777. if (!normal) {
  60778. var target = new BABYLON.Vector3(0, 0, 1);
  60779. var camera = sourceMesh.getScene().activeCamera;
  60780. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60781. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60782. }
  60783. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60784. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60785. var pitch = Math.atan2(normal.y, len);
  60786. // Matrix
  60787. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60788. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60789. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60790. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60791. var vertexData = new BABYLON.VertexData();
  60792. vertexData.indices = [];
  60793. vertexData.positions = [];
  60794. vertexData.normals = [];
  60795. vertexData.uvs = [];
  60796. var currentVertexDataIndex = 0;
  60797. var extractDecalVector3 = function (indexId) {
  60798. var result = new BABYLON.PositionNormalVertex();
  60799. if (!indices || !positions || !normals) {
  60800. return result;
  60801. }
  60802. var vertexId = indices[indexId];
  60803. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60804. // Send vector to decal local world
  60805. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60806. // Get normal
  60807. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60808. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60809. return result;
  60810. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60811. var clip = function (vertices, axis) {
  60812. if (vertices.length === 0) {
  60813. return vertices;
  60814. }
  60815. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60816. var clipVertices = function (v0, v1) {
  60817. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60818. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60819. };
  60820. var result = new Array();
  60821. for (var index = 0; index < vertices.length; index += 3) {
  60822. var v1Out;
  60823. var v2Out;
  60824. var v3Out;
  60825. var total = 0;
  60826. var nV1 = null;
  60827. var nV2 = null;
  60828. var nV3 = null;
  60829. var nV4 = null;
  60830. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60831. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60832. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60833. v1Out = d1 > 0;
  60834. v2Out = d2 > 0;
  60835. v3Out = d3 > 0;
  60836. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60837. switch (total) {
  60838. case 0:
  60839. result.push(vertices[index]);
  60840. result.push(vertices[index + 1]);
  60841. result.push(vertices[index + 2]);
  60842. break;
  60843. case 1:
  60844. if (v1Out) {
  60845. nV1 = vertices[index + 1];
  60846. nV2 = vertices[index + 2];
  60847. nV3 = clipVertices(vertices[index], nV1);
  60848. nV4 = clipVertices(vertices[index], nV2);
  60849. }
  60850. if (v2Out) {
  60851. nV1 = vertices[index];
  60852. nV2 = vertices[index + 2];
  60853. nV3 = clipVertices(vertices[index + 1], nV1);
  60854. nV4 = clipVertices(vertices[index + 1], nV2);
  60855. result.push(nV3);
  60856. result.push(nV2.clone());
  60857. result.push(nV1.clone());
  60858. result.push(nV2.clone());
  60859. result.push(nV3.clone());
  60860. result.push(nV4);
  60861. break;
  60862. }
  60863. if (v3Out) {
  60864. nV1 = vertices[index];
  60865. nV2 = vertices[index + 1];
  60866. nV3 = clipVertices(vertices[index + 2], nV1);
  60867. nV4 = clipVertices(vertices[index + 2], nV2);
  60868. }
  60869. if (nV1 && nV2 && nV3 && nV4) {
  60870. result.push(nV1.clone());
  60871. result.push(nV2.clone());
  60872. result.push(nV3);
  60873. result.push(nV4);
  60874. result.push(nV3.clone());
  60875. result.push(nV2.clone());
  60876. }
  60877. break;
  60878. case 2:
  60879. if (!v1Out) {
  60880. nV1 = vertices[index].clone();
  60881. nV2 = clipVertices(nV1, vertices[index + 1]);
  60882. nV3 = clipVertices(nV1, vertices[index + 2]);
  60883. result.push(nV1);
  60884. result.push(nV2);
  60885. result.push(nV3);
  60886. }
  60887. if (!v2Out) {
  60888. nV1 = vertices[index + 1].clone();
  60889. nV2 = clipVertices(nV1, vertices[index + 2]);
  60890. nV3 = clipVertices(nV1, vertices[index]);
  60891. result.push(nV1);
  60892. result.push(nV2);
  60893. result.push(nV3);
  60894. }
  60895. if (!v3Out) {
  60896. nV1 = vertices[index + 2].clone();
  60897. nV2 = clipVertices(nV1, vertices[index]);
  60898. nV3 = clipVertices(nV1, vertices[index + 1]);
  60899. result.push(nV1);
  60900. result.push(nV2);
  60901. result.push(nV3);
  60902. }
  60903. break;
  60904. case 3:
  60905. break;
  60906. }
  60907. }
  60908. return result;
  60909. };
  60910. for (var index = 0; index < indices.length; index += 3) {
  60911. var faceVertices = new Array();
  60912. faceVertices.push(extractDecalVector3(index));
  60913. faceVertices.push(extractDecalVector3(index + 1));
  60914. faceVertices.push(extractDecalVector3(index + 2));
  60915. // Clip
  60916. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60917. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60918. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60919. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60920. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60921. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60922. if (faceVertices.length === 0) {
  60923. continue;
  60924. }
  60925. // Add UVs and get back to world
  60926. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60927. var vertex = faceVertices[vIndex];
  60928. //TODO check for Int32Array | Uint32Array | Uint16Array
  60929. vertexData.indices.push(currentVertexDataIndex);
  60930. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60931. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60932. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60933. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60934. currentVertexDataIndex++;
  60935. }
  60936. }
  60937. // Return mesh
  60938. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60939. vertexData.applyToMesh(decal);
  60940. decal.position = position.clone();
  60941. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60942. return decal;
  60943. };
  60944. // Privates
  60945. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60946. // extrusion geometry
  60947. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60948. var tangents = path3D.getTangents();
  60949. var normals = path3D.getNormals();
  60950. var binormals = path3D.getBinormals();
  60951. var distances = path3D.getDistances();
  60952. var angle = 0;
  60953. var returnScale = function () { return scale !== null ? scale : 1; };
  60954. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60955. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60956. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60957. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60958. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60959. for (var i = 0; i < curve.length; i++) {
  60960. var shapePath = new Array();
  60961. var angleStep = rotate(i, distances[i]);
  60962. var scaleRatio = scl(i, distances[i]);
  60963. for (var p = 0; p < shape.length; p++) {
  60964. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60965. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60966. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60967. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60968. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60969. shapePath[p] = rotated;
  60970. }
  60971. shapePaths[index] = shapePath;
  60972. angle += angleStep;
  60973. index++;
  60974. }
  60975. // cap
  60976. var capPath = function (shapePath) {
  60977. var pointCap = Array();
  60978. var barycenter = BABYLON.Vector3.Zero();
  60979. var i;
  60980. for (i = 0; i < shapePath.length; i++) {
  60981. barycenter.addInPlace(shapePath[i]);
  60982. }
  60983. barycenter.scaleInPlace(1.0 / shapePath.length);
  60984. for (i = 0; i < shapePath.length; i++) {
  60985. pointCap.push(barycenter);
  60986. }
  60987. return pointCap;
  60988. };
  60989. switch (cap) {
  60990. case BABYLON.Mesh.NO_CAP:
  60991. break;
  60992. case BABYLON.Mesh.CAP_START:
  60993. shapePaths[0] = capPath(shapePaths[2]);
  60994. shapePaths[1] = shapePaths[2];
  60995. break;
  60996. case BABYLON.Mesh.CAP_END:
  60997. shapePaths[index] = shapePaths[index - 1];
  60998. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60999. break;
  61000. case BABYLON.Mesh.CAP_ALL:
  61001. shapePaths[0] = capPath(shapePaths[2]);
  61002. shapePaths[1] = shapePaths[2];
  61003. shapePaths[index] = shapePaths[index - 1];
  61004. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61005. break;
  61006. default:
  61007. break;
  61008. }
  61009. return shapePaths;
  61010. };
  61011. var path3D;
  61012. var pathArray;
  61013. if (instance) { // instance update
  61014. path3D = (instance.path3D).update(curve);
  61015. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61016. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61017. return instance;
  61018. }
  61019. // extruded shape creation
  61020. path3D = new BABYLON.Path3D(curve);
  61021. var newShapePaths = new Array();
  61022. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61023. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61024. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61025. extrudedGeneric.pathArray = pathArray;
  61026. extrudedGeneric.path3D = path3D;
  61027. extrudedGeneric.cap = cap;
  61028. return extrudedGeneric;
  61029. };
  61030. return MeshBuilder;
  61031. }());
  61032. BABYLON.MeshBuilder = MeshBuilder;
  61033. })(BABYLON || (BABYLON = {}));
  61034. //# sourceMappingURL=babylon.meshBuilder.js.map
  61035. var BABYLON;
  61036. (function (BABYLON) {
  61037. /**
  61038. * Draco compression (https://google.github.io/draco/)
  61039. *
  61040. * This class wraps the Draco module.
  61041. *
  61042. * **Encoder**
  61043. *
  61044. * The encoder is not currently implemented.
  61045. *
  61046. * **Decoder**
  61047. *
  61048. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61049. *
  61050. * To update the configuration, use the following code:
  61051. * ```javascript
  61052. * BABYLON.DracoCompression.Configuration = {
  61053. * decoder: {
  61054. * wasmUrl: "<url to the WebAssembly library>",
  61055. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61056. * fallbackUrl: "<url to the fallback JavaScript library>",
  61057. * }
  61058. * };
  61059. * ```
  61060. *
  61061. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  61062. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61063. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61064. *
  61065. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61066. * ```javascript
  61067. * var dracoCompression = new BABYLON.DracoCompression();
  61068. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61069. * [BABYLON.VertexBuffer.PositionKind]: 0
  61070. * });
  61071. * ```
  61072. *
  61073. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61074. */
  61075. var DracoCompression = /** @class */ (function () {
  61076. /**
  61077. * Constructor
  61078. */
  61079. function DracoCompression() {
  61080. }
  61081. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61082. /**
  61083. * Returns true if the decoder is available.
  61084. */
  61085. get: function () {
  61086. if (typeof DracoDecoderModule !== "undefined") {
  61087. return true;
  61088. }
  61089. var decoder = DracoCompression.Configuration.decoder;
  61090. if (decoder) {
  61091. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61092. return true;
  61093. }
  61094. if (decoder.fallbackUrl) {
  61095. return true;
  61096. }
  61097. }
  61098. return false;
  61099. },
  61100. enumerable: true,
  61101. configurable: true
  61102. });
  61103. /**
  61104. * Stop all async operations and release resources.
  61105. */
  61106. DracoCompression.prototype.dispose = function () {
  61107. };
  61108. /**
  61109. * Decode Draco compressed mesh data to vertex data.
  61110. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61111. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61112. * @returns A promise that resolves with the decoded vertex data
  61113. */
  61114. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61115. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61116. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61117. var module = wrappedModule.module;
  61118. var vertexData = new BABYLON.VertexData();
  61119. var buffer = new module.DecoderBuffer();
  61120. buffer.Init(dataView, dataView.byteLength);
  61121. var decoder = new module.Decoder();
  61122. var geometry;
  61123. var status;
  61124. try {
  61125. var type = decoder.GetEncodedGeometryType(buffer);
  61126. switch (type) {
  61127. case module.TRIANGULAR_MESH:
  61128. geometry = new module.Mesh();
  61129. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61130. break;
  61131. case module.POINT_CLOUD:
  61132. geometry = new module.PointCloud();
  61133. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61134. break;
  61135. default:
  61136. throw new Error("Invalid geometry type " + type);
  61137. }
  61138. if (!status.ok() || !geometry.ptr) {
  61139. throw new Error(status.error_msg());
  61140. }
  61141. var numPoints = geometry.num_points();
  61142. if (type === module.TRIANGULAR_MESH) {
  61143. var numFaces = geometry.num_faces();
  61144. var faceIndices = new module.DracoInt32Array();
  61145. try {
  61146. var indices = new Uint32Array(numFaces * 3);
  61147. for (var i = 0; i < numFaces; i++) {
  61148. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61149. var offset = i * 3;
  61150. indices[offset + 0] = faceIndices.GetValue(0);
  61151. indices[offset + 1] = faceIndices.GetValue(1);
  61152. indices[offset + 2] = faceIndices.GetValue(2);
  61153. }
  61154. vertexData.indices = indices;
  61155. }
  61156. finally {
  61157. module.destroy(faceIndices);
  61158. }
  61159. }
  61160. for (var kind in attributes) {
  61161. var uniqueId = attributes[kind];
  61162. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61163. var dracoData = new module.DracoFloat32Array();
  61164. try {
  61165. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61166. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61167. for (var i = 0; i < babylonData.length; i++) {
  61168. babylonData[i] = dracoData.GetValue(i);
  61169. }
  61170. vertexData.set(babylonData, kind);
  61171. }
  61172. finally {
  61173. module.destroy(dracoData);
  61174. }
  61175. }
  61176. }
  61177. finally {
  61178. if (geometry) {
  61179. module.destroy(geometry);
  61180. }
  61181. module.destroy(decoder);
  61182. module.destroy(buffer);
  61183. }
  61184. return vertexData;
  61185. });
  61186. };
  61187. DracoCompression._GetDecoderModule = function () {
  61188. if (!DracoCompression._DecoderModulePromise) {
  61189. var promise = null;
  61190. var config_1 = {};
  61191. if (typeof DracoDecoderModule !== "undefined") {
  61192. promise = Promise.resolve();
  61193. }
  61194. else {
  61195. var decoder = DracoCompression.Configuration.decoder;
  61196. if (decoder) {
  61197. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61198. promise = Promise.all([
  61199. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61200. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61201. config_1.wasmBinary = data;
  61202. })
  61203. ]);
  61204. }
  61205. else if (decoder.fallbackUrl) {
  61206. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61207. }
  61208. }
  61209. }
  61210. if (!promise) {
  61211. throw new Error("Draco decoder module is not available");
  61212. }
  61213. DracoCompression._DecoderModulePromise = promise.then(function () {
  61214. return new Promise(function (resolve) {
  61215. config_1.onModuleLoaded = function (decoderModule) {
  61216. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61217. resolve({ module: decoderModule });
  61218. };
  61219. DracoDecoderModule(config_1);
  61220. });
  61221. });
  61222. }
  61223. return DracoCompression._DecoderModulePromise;
  61224. };
  61225. DracoCompression._LoadScriptAsync = function (url) {
  61226. return new Promise(function (resolve, reject) {
  61227. BABYLON.Tools.LoadScript(url, function () {
  61228. resolve();
  61229. }, function (message) {
  61230. reject(new Error(message));
  61231. });
  61232. });
  61233. };
  61234. DracoCompression._LoadFileAsync = function (url) {
  61235. return new Promise(function (resolve, reject) {
  61236. BABYLON.Tools.LoadFile(url, function (data) {
  61237. resolve(data);
  61238. }, undefined, undefined, true, function (request, exception) {
  61239. reject(exception);
  61240. });
  61241. });
  61242. };
  61243. /**
  61244. * The configuration. Defaults to the following urls:
  61245. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61246. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61247. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61248. */
  61249. DracoCompression.Configuration = {
  61250. decoder: {
  61251. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61252. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61253. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61254. }
  61255. };
  61256. return DracoCompression;
  61257. }());
  61258. BABYLON.DracoCompression = DracoCompression;
  61259. })(BABYLON || (BABYLON = {}));
  61260. //# sourceMappingURL=babylon.dracoCompression.js.map
  61261. var BABYLON;
  61262. (function (BABYLON) {
  61263. var AudioEngine = /** @class */ (function () {
  61264. function AudioEngine() {
  61265. this._audioContext = null;
  61266. this._audioContextInitialized = false;
  61267. this.canUseWebAudio = false;
  61268. this.WarnedWebAudioUnsupported = false;
  61269. this.unlocked = false;
  61270. this.isMP3supported = false;
  61271. this.isOGGsupported = false;
  61272. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61273. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61274. this.canUseWebAudio = true;
  61275. }
  61276. var audioElem = document.createElement('audio');
  61277. try {
  61278. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61279. this.isMP3supported = true;
  61280. }
  61281. }
  61282. catch (e) {
  61283. // protect error during capability check.
  61284. }
  61285. try {
  61286. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61287. this.isOGGsupported = true;
  61288. }
  61289. }
  61290. catch (e) {
  61291. // protect error during capability check.
  61292. }
  61293. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61294. this._unlockiOSaudio();
  61295. }
  61296. else {
  61297. this.unlocked = true;
  61298. }
  61299. }
  61300. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61301. get: function () {
  61302. if (!this._audioContextInitialized) {
  61303. this._initializeAudioContext();
  61304. }
  61305. return this._audioContext;
  61306. },
  61307. enumerable: true,
  61308. configurable: true
  61309. });
  61310. AudioEngine.prototype._unlockiOSaudio = function () {
  61311. var _this = this;
  61312. var unlockaudio = function () {
  61313. if (!_this.audioContext) {
  61314. return;
  61315. }
  61316. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61317. var source = _this.audioContext.createBufferSource();
  61318. source.buffer = buffer;
  61319. source.connect(_this.audioContext.destination);
  61320. source.start(0);
  61321. setTimeout(function () {
  61322. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61323. _this.unlocked = true;
  61324. window.removeEventListener('touchend', unlockaudio, false);
  61325. if (_this.onAudioUnlocked) {
  61326. _this.onAudioUnlocked();
  61327. }
  61328. }
  61329. }, 0);
  61330. };
  61331. window.addEventListener('touchend', unlockaudio, false);
  61332. };
  61333. AudioEngine.prototype._initializeAudioContext = function () {
  61334. try {
  61335. if (this.canUseWebAudio) {
  61336. this._audioContext = new AudioContext();
  61337. // create a global volume gain node
  61338. this.masterGain = this._audioContext.createGain();
  61339. this.masterGain.gain.value = 1;
  61340. this.masterGain.connect(this._audioContext.destination);
  61341. this._audioContextInitialized = true;
  61342. }
  61343. }
  61344. catch (e) {
  61345. this.canUseWebAudio = false;
  61346. BABYLON.Tools.Error("Web Audio: " + e.message);
  61347. }
  61348. };
  61349. AudioEngine.prototype.dispose = function () {
  61350. if (this.canUseWebAudio && this._audioContextInitialized) {
  61351. if (this._connectedAnalyser && this._audioContext) {
  61352. this._connectedAnalyser.stopDebugCanvas();
  61353. this._connectedAnalyser.dispose();
  61354. this.masterGain.disconnect();
  61355. this.masterGain.connect(this._audioContext.destination);
  61356. this._connectedAnalyser = null;
  61357. }
  61358. this.masterGain.gain.value = 1;
  61359. }
  61360. this.WarnedWebAudioUnsupported = false;
  61361. };
  61362. AudioEngine.prototype.getGlobalVolume = function () {
  61363. if (this.canUseWebAudio && this._audioContextInitialized) {
  61364. return this.masterGain.gain.value;
  61365. }
  61366. else {
  61367. return -1;
  61368. }
  61369. };
  61370. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61371. if (this.canUseWebAudio && this._audioContextInitialized) {
  61372. this.masterGain.gain.value = newVolume;
  61373. }
  61374. };
  61375. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61376. if (this._connectedAnalyser) {
  61377. this._connectedAnalyser.stopDebugCanvas();
  61378. }
  61379. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61380. this._connectedAnalyser = analyser;
  61381. this.masterGain.disconnect();
  61382. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61383. }
  61384. };
  61385. return AudioEngine;
  61386. }());
  61387. BABYLON.AudioEngine = AudioEngine;
  61388. })(BABYLON || (BABYLON = {}));
  61389. //# sourceMappingURL=babylon.audioEngine.js.map
  61390. var BABYLON;
  61391. (function (BABYLON) {
  61392. var Sound = /** @class */ (function () {
  61393. /**
  61394. * Create a sound and attach it to a scene
  61395. * @param name Name of your sound
  61396. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61397. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61398. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61399. */
  61400. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61401. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61402. var _this = this;
  61403. this.autoplay = false;
  61404. this.loop = false;
  61405. this.useCustomAttenuation = false;
  61406. this.spatialSound = false;
  61407. this.refDistance = 1;
  61408. this.rolloffFactor = 1;
  61409. this.maxDistance = 100;
  61410. this.distanceModel = "linear";
  61411. this._panningModel = "equalpower";
  61412. this._playbackRate = 1;
  61413. this._streaming = false;
  61414. this._startTime = 0;
  61415. this._startOffset = 0;
  61416. this._position = BABYLON.Vector3.Zero();
  61417. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61418. this._volume = 1;
  61419. this._isReadyToPlay = false;
  61420. this.isPlaying = false;
  61421. this.isPaused = false;
  61422. this._isDirectional = false;
  61423. // Used if you'd like to create a directional sound.
  61424. // If not set, the sound will be omnidirectional
  61425. this._coneInnerAngle = 360;
  61426. this._coneOuterAngle = 360;
  61427. this._coneOuterGain = 0;
  61428. this._isOutputConnected = false;
  61429. this._urlType = "Unknown";
  61430. this.name = name;
  61431. this._scene = scene;
  61432. this._readyToPlayCallback = readyToPlayCallback;
  61433. // Default custom attenuation function is a linear attenuation
  61434. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61435. if (currentDistance < maxDistance) {
  61436. return currentVolume * (1 - currentDistance / maxDistance);
  61437. }
  61438. else {
  61439. return 0;
  61440. }
  61441. };
  61442. if (options) {
  61443. this.autoplay = options.autoplay || false;
  61444. this.loop = options.loop || false;
  61445. // if volume === 0, we need another way to check this option
  61446. if (options.volume !== undefined) {
  61447. this._volume = options.volume;
  61448. }
  61449. this.spatialSound = options.spatialSound || false;
  61450. this.maxDistance = options.maxDistance || 100;
  61451. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61452. this.rolloffFactor = options.rolloffFactor || 1;
  61453. this.refDistance = options.refDistance || 1;
  61454. this.distanceModel = options.distanceModel || "linear";
  61455. this._playbackRate = options.playbackRate || 1;
  61456. this._streaming = options.streaming || false;
  61457. }
  61458. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61459. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61460. this._soundGain.gain.value = this._volume;
  61461. this._inputAudioNode = this._soundGain;
  61462. this._ouputAudioNode = this._soundGain;
  61463. if (this.spatialSound) {
  61464. this._createSpatialParameters();
  61465. }
  61466. this._scene.mainSoundTrack.AddSound(this);
  61467. var validParameter = true;
  61468. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61469. if (urlOrArrayBuffer) {
  61470. try {
  61471. if (typeof (urlOrArrayBuffer) === "string")
  61472. this._urlType = "String";
  61473. if (Array.isArray(urlOrArrayBuffer))
  61474. this._urlType = "Array";
  61475. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61476. this._urlType = "ArrayBuffer";
  61477. var urls = [];
  61478. var codecSupportedFound = false;
  61479. switch (this._urlType) {
  61480. case "ArrayBuffer":
  61481. if (urlOrArrayBuffer.byteLength > 0) {
  61482. codecSupportedFound = true;
  61483. this._soundLoaded(urlOrArrayBuffer);
  61484. }
  61485. break;
  61486. case "String":
  61487. urls.push(urlOrArrayBuffer);
  61488. case "Array":
  61489. if (urls.length === 0)
  61490. urls = urlOrArrayBuffer;
  61491. // If we found a supported format, we load it immediately and stop the loop
  61492. for (var i = 0; i < urls.length; i++) {
  61493. var url = urls[i];
  61494. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61495. codecSupportedFound = true;
  61496. }
  61497. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61498. codecSupportedFound = true;
  61499. }
  61500. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61501. codecSupportedFound = true;
  61502. }
  61503. if (url.indexOf("blob:") !== -1) {
  61504. codecSupportedFound = true;
  61505. }
  61506. if (codecSupportedFound) {
  61507. // Loading sound using XHR2
  61508. if (!this._streaming) {
  61509. this._scene._loadFile(url, function (data) {
  61510. _this._soundLoaded(data);
  61511. }, undefined, true, true, function (exception) {
  61512. if (exception) {
  61513. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61514. }
  61515. BABYLON.Tools.Error("Sound creation aborted.");
  61516. _this._scene.mainSoundTrack.RemoveSound(_this);
  61517. });
  61518. }
  61519. // Streaming sound using HTML5 Audio tag
  61520. else {
  61521. this._htmlAudioElement = new Audio(url);
  61522. this._htmlAudioElement.controls = false;
  61523. this._htmlAudioElement.loop = this.loop;
  61524. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61525. this._htmlAudioElement.preload = "auto";
  61526. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61527. _this._isReadyToPlay = true;
  61528. if (_this.autoplay) {
  61529. _this.play();
  61530. }
  61531. if (_this._readyToPlayCallback) {
  61532. _this._readyToPlayCallback();
  61533. }
  61534. });
  61535. document.body.appendChild(this._htmlAudioElement);
  61536. }
  61537. break;
  61538. }
  61539. }
  61540. break;
  61541. default:
  61542. validParameter = false;
  61543. break;
  61544. }
  61545. if (!validParameter) {
  61546. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61547. }
  61548. else {
  61549. if (!codecSupportedFound) {
  61550. this._isReadyToPlay = true;
  61551. // Simulating a ready to play event to avoid breaking code path
  61552. if (this._readyToPlayCallback) {
  61553. window.setTimeout(function () {
  61554. if (_this._readyToPlayCallback) {
  61555. _this._readyToPlayCallback();
  61556. }
  61557. }, 1000);
  61558. }
  61559. }
  61560. }
  61561. }
  61562. catch (ex) {
  61563. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61564. this._scene.mainSoundTrack.RemoveSound(this);
  61565. }
  61566. }
  61567. }
  61568. else {
  61569. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61570. this._scene.mainSoundTrack.AddSound(this);
  61571. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61572. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61573. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61574. }
  61575. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61576. if (this._readyToPlayCallback) {
  61577. window.setTimeout(function () {
  61578. if (_this._readyToPlayCallback) {
  61579. _this._readyToPlayCallback();
  61580. }
  61581. }, 1000);
  61582. }
  61583. }
  61584. }
  61585. Sound.prototype.dispose = function () {
  61586. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61587. if (this.isPlaying) {
  61588. this.stop();
  61589. }
  61590. this._isReadyToPlay = false;
  61591. if (this.soundTrackId === -1) {
  61592. this._scene.mainSoundTrack.RemoveSound(this);
  61593. }
  61594. else {
  61595. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61596. }
  61597. if (this._soundGain) {
  61598. this._soundGain.disconnect();
  61599. this._soundGain = null;
  61600. }
  61601. if (this._soundPanner) {
  61602. this._soundPanner.disconnect();
  61603. this._soundPanner = null;
  61604. }
  61605. if (this._soundSource) {
  61606. this._soundSource.disconnect();
  61607. this._soundSource = null;
  61608. }
  61609. this._audioBuffer = null;
  61610. if (this._htmlAudioElement) {
  61611. this._htmlAudioElement.pause();
  61612. this._htmlAudioElement.src = "";
  61613. document.body.removeChild(this._htmlAudioElement);
  61614. }
  61615. if (this._connectedMesh && this._registerFunc) {
  61616. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61617. this._connectedMesh = null;
  61618. }
  61619. }
  61620. };
  61621. Sound.prototype.isReady = function () {
  61622. return this._isReadyToPlay;
  61623. };
  61624. Sound.prototype._soundLoaded = function (audioData) {
  61625. var _this = this;
  61626. if (!BABYLON.Engine.audioEngine.audioContext) {
  61627. return;
  61628. }
  61629. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61630. _this._audioBuffer = buffer;
  61631. _this._isReadyToPlay = true;
  61632. if (_this.autoplay) {
  61633. _this.play();
  61634. }
  61635. if (_this._readyToPlayCallback) {
  61636. _this._readyToPlayCallback();
  61637. }
  61638. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61639. };
  61640. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61641. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61642. this._audioBuffer = audioBuffer;
  61643. this._isReadyToPlay = true;
  61644. }
  61645. };
  61646. Sound.prototype.updateOptions = function (options) {
  61647. if (options) {
  61648. this.loop = options.loop || this.loop;
  61649. this.maxDistance = options.maxDistance || this.maxDistance;
  61650. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61651. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61652. this.refDistance = options.refDistance || this.refDistance;
  61653. this.distanceModel = options.distanceModel || this.distanceModel;
  61654. this._playbackRate = options.playbackRate || this._playbackRate;
  61655. this._updateSpatialParameters();
  61656. if (this.isPlaying) {
  61657. if (this._streaming) {
  61658. this._htmlAudioElement.playbackRate = this._playbackRate;
  61659. }
  61660. else {
  61661. if (this._soundSource) {
  61662. this._soundSource.playbackRate.value = this._playbackRate;
  61663. }
  61664. }
  61665. }
  61666. }
  61667. };
  61668. Sound.prototype._createSpatialParameters = function () {
  61669. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61670. if (this._scene.headphone) {
  61671. this._panningModel = "HRTF";
  61672. }
  61673. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61674. this._updateSpatialParameters();
  61675. this._soundPanner.connect(this._ouputAudioNode);
  61676. this._inputAudioNode = this._soundPanner;
  61677. }
  61678. };
  61679. Sound.prototype._updateSpatialParameters = function () {
  61680. if (this.spatialSound && this._soundPanner) {
  61681. if (this.useCustomAttenuation) {
  61682. // Tricks to disable in a way embedded Web Audio attenuation
  61683. this._soundPanner.distanceModel = "linear";
  61684. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61685. this._soundPanner.refDistance = 1;
  61686. this._soundPanner.rolloffFactor = 1;
  61687. this._soundPanner.panningModel = this._panningModel;
  61688. }
  61689. else {
  61690. this._soundPanner.distanceModel = this.distanceModel;
  61691. this._soundPanner.maxDistance = this.maxDistance;
  61692. this._soundPanner.refDistance = this.refDistance;
  61693. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61694. this._soundPanner.panningModel = this._panningModel;
  61695. }
  61696. }
  61697. };
  61698. Sound.prototype.switchPanningModelToHRTF = function () {
  61699. this._panningModel = "HRTF";
  61700. this._switchPanningModel();
  61701. };
  61702. Sound.prototype.switchPanningModelToEqualPower = function () {
  61703. this._panningModel = "equalpower";
  61704. this._switchPanningModel();
  61705. };
  61706. Sound.prototype._switchPanningModel = function () {
  61707. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61708. this._soundPanner.panningModel = this._panningModel;
  61709. }
  61710. };
  61711. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61712. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61713. if (this._isOutputConnected) {
  61714. this._ouputAudioNode.disconnect();
  61715. }
  61716. this._ouputAudioNode.connect(soundTrackAudioNode);
  61717. this._isOutputConnected = true;
  61718. }
  61719. };
  61720. /**
  61721. * Transform this sound into a directional source
  61722. * @param coneInnerAngle Size of the inner cone in degree
  61723. * @param coneOuterAngle Size of the outer cone in degree
  61724. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61725. */
  61726. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61727. if (coneOuterAngle < coneInnerAngle) {
  61728. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61729. return;
  61730. }
  61731. this._coneInnerAngle = coneInnerAngle;
  61732. this._coneOuterAngle = coneOuterAngle;
  61733. this._coneOuterGain = coneOuterGain;
  61734. this._isDirectional = true;
  61735. if (this.isPlaying && this.loop) {
  61736. this.stop();
  61737. this.play();
  61738. }
  61739. };
  61740. Sound.prototype.setPosition = function (newPosition) {
  61741. this._position = newPosition;
  61742. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61743. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61744. }
  61745. };
  61746. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61747. this._localDirection = newLocalDirection;
  61748. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61749. this._updateDirection();
  61750. }
  61751. };
  61752. Sound.prototype._updateDirection = function () {
  61753. if (!this._connectedMesh || !this._soundPanner) {
  61754. return;
  61755. }
  61756. var mat = this._connectedMesh.getWorldMatrix();
  61757. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61758. direction.normalize();
  61759. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61760. };
  61761. Sound.prototype.updateDistanceFromListener = function () {
  61762. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61763. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61764. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61765. }
  61766. };
  61767. Sound.prototype.setAttenuationFunction = function (callback) {
  61768. this._customAttenuationFunction = callback;
  61769. };
  61770. /**
  61771. * Play the sound
  61772. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61773. * @param offset (optional) Start the sound setting it at a specific time
  61774. */
  61775. Sound.prototype.play = function (time, offset) {
  61776. var _this = this;
  61777. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61778. try {
  61779. if (this._startOffset < 0) {
  61780. time = -this._startOffset;
  61781. this._startOffset = 0;
  61782. }
  61783. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61784. if (!this._soundSource || !this._streamingSource) {
  61785. if (this.spatialSound && this._soundPanner) {
  61786. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61787. if (this._isDirectional) {
  61788. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61789. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61790. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61791. if (this._connectedMesh) {
  61792. this._updateDirection();
  61793. }
  61794. else {
  61795. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61796. }
  61797. }
  61798. }
  61799. }
  61800. if (this._streaming) {
  61801. if (!this._streamingSource) {
  61802. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61803. this._htmlAudioElement.onended = function () { _this._onended(); };
  61804. this._htmlAudioElement.playbackRate = this._playbackRate;
  61805. }
  61806. this._streamingSource.disconnect();
  61807. this._streamingSource.connect(this._inputAudioNode);
  61808. this._htmlAudioElement.play();
  61809. }
  61810. else {
  61811. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61812. this._soundSource.buffer = this._audioBuffer;
  61813. this._soundSource.connect(this._inputAudioNode);
  61814. this._soundSource.loop = this.loop;
  61815. this._soundSource.playbackRate.value = this._playbackRate;
  61816. this._soundSource.onended = function () { _this._onended(); };
  61817. if (this._soundSource.buffer) {
  61818. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61819. }
  61820. }
  61821. this._startTime = startTime;
  61822. this.isPlaying = true;
  61823. this.isPaused = false;
  61824. }
  61825. catch (ex) {
  61826. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61827. }
  61828. }
  61829. };
  61830. Sound.prototype._onended = function () {
  61831. this.isPlaying = false;
  61832. if (this.onended) {
  61833. this.onended();
  61834. }
  61835. };
  61836. /**
  61837. * Stop the sound
  61838. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61839. */
  61840. Sound.prototype.stop = function (time) {
  61841. if (this.isPlaying) {
  61842. if (this._streaming) {
  61843. this._htmlAudioElement.pause();
  61844. // Test needed for Firefox or it will generate an Invalid State Error
  61845. if (this._htmlAudioElement.currentTime > 0) {
  61846. this._htmlAudioElement.currentTime = 0;
  61847. }
  61848. }
  61849. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61850. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61851. this._soundSource.stop(stopTime);
  61852. this._soundSource.onended = function () { };
  61853. if (!this.isPaused) {
  61854. this._startOffset = 0;
  61855. }
  61856. }
  61857. this.isPlaying = false;
  61858. }
  61859. };
  61860. Sound.prototype.pause = function () {
  61861. if (this.isPlaying) {
  61862. this.isPaused = true;
  61863. if (this._streaming) {
  61864. this._htmlAudioElement.pause();
  61865. }
  61866. else if (BABYLON.Engine.audioEngine.audioContext) {
  61867. this.stop(0);
  61868. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61869. }
  61870. }
  61871. };
  61872. Sound.prototype.setVolume = function (newVolume, time) {
  61873. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61874. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61875. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61876. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61877. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61878. }
  61879. else {
  61880. this._soundGain.gain.value = newVolume;
  61881. }
  61882. }
  61883. this._volume = newVolume;
  61884. };
  61885. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61886. this._playbackRate = newPlaybackRate;
  61887. if (this.isPlaying) {
  61888. if (this._streaming) {
  61889. this._htmlAudioElement.playbackRate = this._playbackRate;
  61890. }
  61891. else if (this._soundSource) {
  61892. this._soundSource.playbackRate.value = this._playbackRate;
  61893. }
  61894. }
  61895. };
  61896. Sound.prototype.getVolume = function () {
  61897. return this._volume;
  61898. };
  61899. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61900. var _this = this;
  61901. if (this._connectedMesh && this._registerFunc) {
  61902. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61903. this._registerFunc = null;
  61904. }
  61905. this._connectedMesh = meshToConnectTo;
  61906. if (!this.spatialSound) {
  61907. this.spatialSound = true;
  61908. this._createSpatialParameters();
  61909. if (this.isPlaying && this.loop) {
  61910. this.stop();
  61911. this.play();
  61912. }
  61913. }
  61914. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61915. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61916. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61917. };
  61918. Sound.prototype.detachFromMesh = function () {
  61919. if (this._connectedMesh && this._registerFunc) {
  61920. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61921. this._registerFunc = null;
  61922. this._connectedMesh = null;
  61923. }
  61924. };
  61925. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61926. if (!node.getBoundingInfo) {
  61927. return;
  61928. }
  61929. var mesh = node;
  61930. var boundingInfo = mesh.getBoundingInfo();
  61931. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61932. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61933. this._updateDirection();
  61934. }
  61935. };
  61936. Sound.prototype.clone = function () {
  61937. var _this = this;
  61938. if (!this._streaming) {
  61939. var setBufferAndRun = function () {
  61940. if (_this._isReadyToPlay) {
  61941. clonedSound._audioBuffer = _this.getAudioBuffer();
  61942. clonedSound._isReadyToPlay = true;
  61943. if (clonedSound.autoplay) {
  61944. clonedSound.play();
  61945. }
  61946. }
  61947. else {
  61948. window.setTimeout(setBufferAndRun, 300);
  61949. }
  61950. };
  61951. var currentOptions = {
  61952. autoplay: this.autoplay, loop: this.loop,
  61953. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61954. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61955. refDistance: this.refDistance, distanceModel: this.distanceModel
  61956. };
  61957. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61958. if (this.useCustomAttenuation) {
  61959. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61960. }
  61961. clonedSound.setPosition(this._position);
  61962. clonedSound.setPlaybackRate(this._playbackRate);
  61963. setBufferAndRun();
  61964. return clonedSound;
  61965. }
  61966. // Can't clone a streaming sound
  61967. else {
  61968. return null;
  61969. }
  61970. };
  61971. Sound.prototype.getAudioBuffer = function () {
  61972. return this._audioBuffer;
  61973. };
  61974. Sound.prototype.serialize = function () {
  61975. var serializationObject = {
  61976. name: this.name,
  61977. url: this.name,
  61978. autoplay: this.autoplay,
  61979. loop: this.loop,
  61980. volume: this._volume,
  61981. spatialSound: this.spatialSound,
  61982. maxDistance: this.maxDistance,
  61983. rolloffFactor: this.rolloffFactor,
  61984. refDistance: this.refDistance,
  61985. distanceModel: this.distanceModel,
  61986. playbackRate: this._playbackRate,
  61987. panningModel: this._panningModel,
  61988. soundTrackId: this.soundTrackId
  61989. };
  61990. if (this.spatialSound) {
  61991. if (this._connectedMesh)
  61992. serializationObject.connectedMeshId = this._connectedMesh.id;
  61993. serializationObject.position = this._position.asArray();
  61994. serializationObject.refDistance = this.refDistance;
  61995. serializationObject.distanceModel = this.distanceModel;
  61996. serializationObject.isDirectional = this._isDirectional;
  61997. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61998. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61999. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62000. serializationObject.coneOuterGain = this._coneOuterGain;
  62001. }
  62002. return serializationObject;
  62003. };
  62004. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62005. var soundName = parsedSound.name;
  62006. var soundUrl;
  62007. if (parsedSound.url) {
  62008. soundUrl = rootUrl + parsedSound.url;
  62009. }
  62010. else {
  62011. soundUrl = rootUrl + soundName;
  62012. }
  62013. var options = {
  62014. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62015. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62016. rolloffFactor: parsedSound.rolloffFactor,
  62017. refDistance: parsedSound.refDistance,
  62018. distanceModel: parsedSound.distanceModel,
  62019. playbackRate: parsedSound.playbackRate
  62020. };
  62021. var newSound;
  62022. if (!sourceSound) {
  62023. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62024. scene._addPendingData(newSound);
  62025. }
  62026. else {
  62027. var setBufferAndRun = function () {
  62028. if (sourceSound._isReadyToPlay) {
  62029. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62030. newSound._isReadyToPlay = true;
  62031. if (newSound.autoplay) {
  62032. newSound.play();
  62033. }
  62034. }
  62035. else {
  62036. window.setTimeout(setBufferAndRun, 300);
  62037. }
  62038. };
  62039. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62040. setBufferAndRun();
  62041. }
  62042. if (parsedSound.position) {
  62043. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62044. newSound.setPosition(soundPosition);
  62045. }
  62046. if (parsedSound.isDirectional) {
  62047. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62048. if (parsedSound.localDirectionToMesh) {
  62049. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62050. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62051. }
  62052. }
  62053. if (parsedSound.connectedMeshId) {
  62054. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62055. if (connectedMesh) {
  62056. newSound.attachToMesh(connectedMesh);
  62057. }
  62058. }
  62059. return newSound;
  62060. };
  62061. return Sound;
  62062. }());
  62063. BABYLON.Sound = Sound;
  62064. })(BABYLON || (BABYLON = {}));
  62065. //# sourceMappingURL=babylon.sound.js.map
  62066. var BABYLON;
  62067. (function (BABYLON) {
  62068. var SoundTrack = /** @class */ (function () {
  62069. function SoundTrack(scene, options) {
  62070. this.id = -1;
  62071. this._isMainTrack = false;
  62072. this._isInitialized = false;
  62073. this._scene = scene;
  62074. this.soundCollection = new Array();
  62075. this._options = options;
  62076. if (!this._isMainTrack) {
  62077. this._scene.soundTracks.push(this);
  62078. this.id = this._scene.soundTracks.length - 1;
  62079. }
  62080. }
  62081. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62082. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62083. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62084. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62085. if (this._options) {
  62086. if (this._options.volume) {
  62087. this._outputAudioNode.gain.value = this._options.volume;
  62088. }
  62089. if (this._options.mainTrack) {
  62090. this._isMainTrack = this._options.mainTrack;
  62091. }
  62092. }
  62093. this._isInitialized = true;
  62094. }
  62095. };
  62096. SoundTrack.prototype.dispose = function () {
  62097. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62098. if (this._connectedAnalyser) {
  62099. this._connectedAnalyser.stopDebugCanvas();
  62100. }
  62101. while (this.soundCollection.length) {
  62102. this.soundCollection[0].dispose();
  62103. }
  62104. if (this._outputAudioNode) {
  62105. this._outputAudioNode.disconnect();
  62106. }
  62107. this._outputAudioNode = null;
  62108. }
  62109. };
  62110. SoundTrack.prototype.AddSound = function (sound) {
  62111. if (!this._isInitialized) {
  62112. this._initializeSoundTrackAudioGraph();
  62113. }
  62114. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62115. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62116. }
  62117. if (sound.soundTrackId) {
  62118. if (sound.soundTrackId === -1) {
  62119. this._scene.mainSoundTrack.RemoveSound(sound);
  62120. }
  62121. else {
  62122. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62123. }
  62124. }
  62125. this.soundCollection.push(sound);
  62126. sound.soundTrackId = this.id;
  62127. };
  62128. SoundTrack.prototype.RemoveSound = function (sound) {
  62129. var index = this.soundCollection.indexOf(sound);
  62130. if (index !== -1) {
  62131. this.soundCollection.splice(index, 1);
  62132. }
  62133. };
  62134. SoundTrack.prototype.setVolume = function (newVolume) {
  62135. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62136. this._outputAudioNode.gain.value = newVolume;
  62137. }
  62138. };
  62139. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62140. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62141. for (var i = 0; i < this.soundCollection.length; i++) {
  62142. this.soundCollection[i].switchPanningModelToHRTF();
  62143. }
  62144. }
  62145. };
  62146. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62147. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62148. for (var i = 0; i < this.soundCollection.length; i++) {
  62149. this.soundCollection[i].switchPanningModelToEqualPower();
  62150. }
  62151. }
  62152. };
  62153. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62154. if (this._connectedAnalyser) {
  62155. this._connectedAnalyser.stopDebugCanvas();
  62156. }
  62157. this._connectedAnalyser = analyser;
  62158. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62159. this._outputAudioNode.disconnect();
  62160. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62161. }
  62162. };
  62163. return SoundTrack;
  62164. }());
  62165. BABYLON.SoundTrack = SoundTrack;
  62166. })(BABYLON || (BABYLON = {}));
  62167. //# sourceMappingURL=babylon.soundtrack.js.map
  62168. var BABYLON;
  62169. (function (BABYLON) {
  62170. /**
  62171. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62172. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62173. */
  62174. var Analyser = /** @class */ (function () {
  62175. /**
  62176. * Creates a new analyser
  62177. * @param scene defines hosting scene
  62178. */
  62179. function Analyser(scene) {
  62180. /**
  62181. * Gets or sets the smoothing
  62182. * @ignorenaming
  62183. */
  62184. this.SMOOTHING = 0.75;
  62185. /**
  62186. * Gets or sets the FFT table size
  62187. * @ignorenaming
  62188. */
  62189. this.FFT_SIZE = 512;
  62190. /**
  62191. * Gets or sets the bar graph amplitude
  62192. * @ignorenaming
  62193. */
  62194. this.BARGRAPHAMPLITUDE = 256;
  62195. /**
  62196. * Gets or sets the position of the debug canvas
  62197. * @ignorenaming
  62198. */
  62199. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62200. /**
  62201. * Gets or sets the debug canvas size
  62202. * @ignorenaming
  62203. */
  62204. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62205. this._scene = scene;
  62206. this._audioEngine = BABYLON.Engine.audioEngine;
  62207. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62208. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62209. this._webAudioAnalyser.minDecibels = -140;
  62210. this._webAudioAnalyser.maxDecibels = 0;
  62211. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62212. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62213. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62214. }
  62215. }
  62216. /**
  62217. * Get the number of data values you will have to play with for the visualization
  62218. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62219. * @returns a number
  62220. */
  62221. Analyser.prototype.getFrequencyBinCount = function () {
  62222. if (this._audioEngine.canUseWebAudio) {
  62223. return this._webAudioAnalyser.frequencyBinCount;
  62224. }
  62225. else {
  62226. return 0;
  62227. }
  62228. };
  62229. /**
  62230. * Gets the current frequency data as a byte array
  62231. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62232. * @returns a Uint8Array
  62233. */
  62234. Analyser.prototype.getByteFrequencyData = function () {
  62235. if (this._audioEngine.canUseWebAudio) {
  62236. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62237. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62238. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62239. }
  62240. return this._byteFreqs;
  62241. };
  62242. /**
  62243. * Gets the current waveform as a byte array
  62244. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62245. * @returns a Uint8Array
  62246. */
  62247. Analyser.prototype.getByteTimeDomainData = function () {
  62248. if (this._audioEngine.canUseWebAudio) {
  62249. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62250. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62251. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62252. }
  62253. return this._byteTime;
  62254. };
  62255. /**
  62256. * Gets the current frequency data as a float array
  62257. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62258. * @returns a Float32Array
  62259. */
  62260. Analyser.prototype.getFloatFrequencyData = function () {
  62261. if (this._audioEngine.canUseWebAudio) {
  62262. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62263. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62264. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62265. }
  62266. return this._floatFreqs;
  62267. };
  62268. /**
  62269. * Renders the debug canvas
  62270. */
  62271. Analyser.prototype.drawDebugCanvas = function () {
  62272. var _this = this;
  62273. if (this._audioEngine.canUseWebAudio) {
  62274. if (!this._debugCanvas) {
  62275. this._debugCanvas = document.createElement("canvas");
  62276. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62277. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62278. this._debugCanvas.style.position = "absolute";
  62279. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62280. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62281. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62282. document.body.appendChild(this._debugCanvas);
  62283. this._registerFunc = function () {
  62284. _this.drawDebugCanvas();
  62285. };
  62286. this._scene.registerBeforeRender(this._registerFunc);
  62287. }
  62288. if (this._registerFunc && this._debugCanvasContext) {
  62289. var workingArray = this.getByteFrequencyData();
  62290. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62291. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62292. // Draw the frequency domain chart.
  62293. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62294. var value = workingArray[i];
  62295. var percent = value / this.BARGRAPHAMPLITUDE;
  62296. var height = this.DEBUGCANVASSIZE.height * percent;
  62297. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62298. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62299. var hue = i / this.getFrequencyBinCount() * 360;
  62300. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62301. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62302. }
  62303. }
  62304. }
  62305. };
  62306. /**
  62307. * Stops rendering the debug canvas and removes it
  62308. */
  62309. Analyser.prototype.stopDebugCanvas = function () {
  62310. if (this._debugCanvas) {
  62311. if (this._registerFunc) {
  62312. this._scene.unregisterBeforeRender(this._registerFunc);
  62313. this._registerFunc = null;
  62314. }
  62315. document.body.removeChild(this._debugCanvas);
  62316. this._debugCanvas = null;
  62317. this._debugCanvasContext = null;
  62318. }
  62319. };
  62320. /**
  62321. * Connects two audio nodes
  62322. * @param inputAudioNode defines first node to connect
  62323. * @param outputAudioNode defines second node to connect
  62324. */
  62325. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62326. if (this._audioEngine.canUseWebAudio) {
  62327. inputAudioNode.connect(this._webAudioAnalyser);
  62328. this._webAudioAnalyser.connect(outputAudioNode);
  62329. }
  62330. };
  62331. /**
  62332. * Releases all associated resources
  62333. */
  62334. Analyser.prototype.dispose = function () {
  62335. if (this._audioEngine.canUseWebAudio) {
  62336. this._webAudioAnalyser.disconnect();
  62337. }
  62338. };
  62339. return Analyser;
  62340. }());
  62341. BABYLON.Analyser = Analyser;
  62342. })(BABYLON || (BABYLON = {}));
  62343. //# sourceMappingURL=babylon.analyser.js.map
  62344. var BABYLON;
  62345. (function (BABYLON) {
  62346. var CubeTexture = /** @class */ (function (_super) {
  62347. __extends(CubeTexture, _super);
  62348. /**
  62349. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62350. * as prefiltered data.
  62351. * @param rootUrl defines the url of the texture or the root name of the six images
  62352. * @param scene defines the scene the texture is attached to
  62353. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62354. * @param noMipmap defines if mipmaps should be created or not
  62355. * @param files defines the six files to load for the different faces
  62356. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62357. * @param onError defines a callback triggered in case of error during load
  62358. * @param format defines the internal format to use for the texture once loaded
  62359. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62360. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62361. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62362. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62363. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62364. * @return the cube texture
  62365. */
  62366. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62367. if (extensions === void 0) { extensions = null; }
  62368. if (noMipmap === void 0) { noMipmap = false; }
  62369. if (files === void 0) { files = null; }
  62370. if (onLoad === void 0) { onLoad = null; }
  62371. if (onError === void 0) { onError = null; }
  62372. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62373. if (prefiltered === void 0) { prefiltered = false; }
  62374. if (forcedExtension === void 0) { forcedExtension = null; }
  62375. if (createPolynomials === void 0) { createPolynomials = false; }
  62376. if (lodScale === void 0) { lodScale = 0.8; }
  62377. if (lodOffset === void 0) { lodOffset = 0; }
  62378. var _this = _super.call(this, scene) || this;
  62379. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62380. /**
  62381. * Gets or sets the center of the bounding box associated with the cube texture
  62382. * It must define where the camera used to render the texture was set
  62383. */
  62384. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62385. _this._rotationY = 0;
  62386. /** @hidden */
  62387. _this._prefiltered = false;
  62388. _this.name = rootUrl;
  62389. _this.url = rootUrl;
  62390. _this._noMipmap = noMipmap;
  62391. _this.hasAlpha = false;
  62392. _this._format = format;
  62393. _this.isCube = true;
  62394. _this._textureMatrix = BABYLON.Matrix.Identity();
  62395. _this._createPolynomials = createPolynomials;
  62396. if (!rootUrl && !files) {
  62397. return _this;
  62398. }
  62399. var lastDot = rootUrl.lastIndexOf(".");
  62400. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62401. var isDDS = (extension === ".dds");
  62402. var isEnv = (extension === ".env");
  62403. if (isEnv) {
  62404. _this.gammaSpace = false;
  62405. _this._prefiltered = false;
  62406. }
  62407. else {
  62408. _this._prefiltered = prefiltered;
  62409. if (prefiltered) {
  62410. _this.gammaSpace = false;
  62411. }
  62412. }
  62413. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62414. if (!files) {
  62415. if (!isEnv && !isDDS && !extensions) {
  62416. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62417. }
  62418. files = [];
  62419. if (extensions) {
  62420. for (var index = 0; index < extensions.length; index++) {
  62421. files.push(rootUrl + extensions[index]);
  62422. }
  62423. }
  62424. }
  62425. _this._files = files;
  62426. if (!_this._texture) {
  62427. if (!scene.useDelayedTextureLoading) {
  62428. if (prefiltered) {
  62429. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  62430. }
  62431. else {
  62432. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  62433. }
  62434. }
  62435. else {
  62436. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62437. }
  62438. }
  62439. else if (onLoad) {
  62440. if (_this._texture.isReady) {
  62441. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62442. }
  62443. else {
  62444. _this._texture.onLoadedObservable.add(onLoad);
  62445. }
  62446. }
  62447. return _this;
  62448. }
  62449. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62450. get: function () {
  62451. return this._boundingBoxSize;
  62452. },
  62453. /**
  62454. * Gets or sets the size of the bounding box associated with the cube texture
  62455. * When defined, the cubemap will switch to local mode
  62456. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62457. * @example https://www.babylonjs-playground.com/#RNASML
  62458. */
  62459. set: function (value) {
  62460. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62461. return;
  62462. }
  62463. this._boundingBoxSize = value;
  62464. var scene = this.getScene();
  62465. if (scene) {
  62466. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62467. }
  62468. },
  62469. enumerable: true,
  62470. configurable: true
  62471. });
  62472. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62473. /**
  62474. * Gets texture matrix rotation angle around Y axis radians.
  62475. */
  62476. get: function () {
  62477. return this._rotationY;
  62478. },
  62479. /**
  62480. * Sets texture matrix rotation angle around Y axis in radians.
  62481. */
  62482. set: function (value) {
  62483. this._rotationY = value;
  62484. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62485. },
  62486. enumerable: true,
  62487. configurable: true
  62488. });
  62489. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62490. var rootUrlKey = "";
  62491. files.forEach(function (url) { return rootUrlKey += url; });
  62492. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62493. };
  62494. /**
  62495. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  62496. * @param url defines the url of the prefiltered texture
  62497. * @param scene defines the scene the texture is attached to
  62498. * @param forcedExtension defines the extension of the file if different from the url
  62499. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62500. * @return the prefiltered texture
  62501. */
  62502. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  62503. if (forcedExtension === void 0) { forcedExtension = null; }
  62504. if (createPolynomials === void 0) { createPolynomials = true; }
  62505. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  62506. };
  62507. // Methods
  62508. CubeTexture.prototype.delayLoad = function () {
  62509. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62510. return;
  62511. }
  62512. var scene = this.getScene();
  62513. if (!scene) {
  62514. return;
  62515. }
  62516. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62517. this._texture = this._getFromCache(this.url, this._noMipmap);
  62518. if (!this._texture) {
  62519. if (this._prefiltered) {
  62520. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  62521. }
  62522. else {
  62523. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62524. }
  62525. }
  62526. };
  62527. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62528. return this._textureMatrix;
  62529. };
  62530. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62531. this._textureMatrix = value;
  62532. };
  62533. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62534. var texture = BABYLON.SerializationHelper.Parse(function () {
  62535. var prefiltered = false;
  62536. if (parsedTexture.prefiltered) {
  62537. prefiltered = parsedTexture.prefiltered;
  62538. }
  62539. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  62540. }, parsedTexture, scene);
  62541. // Local Cubemaps
  62542. if (parsedTexture.boundingBoxPosition) {
  62543. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62544. }
  62545. if (parsedTexture.boundingBoxSize) {
  62546. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62547. }
  62548. // Animations
  62549. if (parsedTexture.animations) {
  62550. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62551. var parsedAnimation = parsedTexture.animations[animationIndex];
  62552. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62553. }
  62554. }
  62555. return texture;
  62556. };
  62557. CubeTexture.prototype.clone = function () {
  62558. var _this = this;
  62559. return BABYLON.SerializationHelper.Clone(function () {
  62560. var scene = _this.getScene();
  62561. if (!scene) {
  62562. return _this;
  62563. }
  62564. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62565. }, this);
  62566. };
  62567. __decorate([
  62568. BABYLON.serialize("rotationY")
  62569. ], CubeTexture.prototype, "_rotationY", void 0);
  62570. return CubeTexture;
  62571. }(BABYLON.BaseTexture));
  62572. BABYLON.CubeTexture = CubeTexture;
  62573. })(BABYLON || (BABYLON = {}));
  62574. //# sourceMappingURL=babylon.cubeTexture.js.map
  62575. var BABYLON;
  62576. (function (BABYLON) {
  62577. var RenderTargetTexture = /** @class */ (function (_super) {
  62578. __extends(RenderTargetTexture, _super);
  62579. /**
  62580. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62581. * or used a shadow, depth texture...
  62582. * @param name The friendly name of the texture
  62583. * @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)
  62584. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62585. * @param generateMipMaps True if mip maps need to be generated after render.
  62586. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62587. * @param type The type of the buffer in the RTT (int, half float, float...)
  62588. * @param isCube True if a cube texture needs to be created
  62589. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62590. * @param generateDepthBuffer True to generate a depth buffer
  62591. * @param generateStencilBuffer True to generate a stencil buffer
  62592. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62593. */
  62594. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62595. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62596. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62597. if (isCube === void 0) { isCube = false; }
  62598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62599. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62600. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62601. if (isMulti === void 0) { isMulti = false; }
  62602. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62603. _this.isCube = isCube;
  62604. /**
  62605. * Use this list to define the list of mesh you want to render.
  62606. */
  62607. _this.renderList = new Array();
  62608. _this.renderParticles = true;
  62609. _this.renderSprites = false;
  62610. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62611. _this.ignoreCameraViewport = false;
  62612. // Events
  62613. /**
  62614. * An event triggered when the texture is unbind.
  62615. */
  62616. _this.onBeforeBindObservable = new BABYLON.Observable();
  62617. /**
  62618. * An event triggered when the texture is unbind.
  62619. */
  62620. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62621. /**
  62622. * An event triggered before rendering the texture
  62623. */
  62624. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62625. /**
  62626. * An event triggered after rendering the texture
  62627. */
  62628. _this.onAfterRenderObservable = new BABYLON.Observable();
  62629. /**
  62630. * An event triggered after the texture clear
  62631. */
  62632. _this.onClearObservable = new BABYLON.Observable();
  62633. _this._currentRefreshId = -1;
  62634. _this._refreshRate = 1;
  62635. _this._samples = 1;
  62636. /**
  62637. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62638. * It must define where the camera used to render the texture is set
  62639. */
  62640. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62641. scene = _this.getScene();
  62642. if (!scene) {
  62643. return _this;
  62644. }
  62645. _this._engine = scene.getEngine();
  62646. _this.name = name;
  62647. _this.isRenderTarget = true;
  62648. _this._initialSizeParameter = size;
  62649. _this._processSizeParameter(size);
  62650. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62651. });
  62652. _this._generateMipMaps = generateMipMaps ? true : false;
  62653. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62654. // Rendering groups
  62655. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62656. if (isMulti) {
  62657. return _this;
  62658. }
  62659. _this._renderTargetOptions = {
  62660. generateMipMaps: generateMipMaps,
  62661. type: type,
  62662. samplingMode: samplingMode,
  62663. generateDepthBuffer: generateDepthBuffer,
  62664. generateStencilBuffer: generateStencilBuffer
  62665. };
  62666. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62667. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62668. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62669. }
  62670. if (isCube) {
  62671. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62672. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62673. _this._textureMatrix = BABYLON.Matrix.Identity();
  62674. }
  62675. else {
  62676. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62677. }
  62678. return _this;
  62679. }
  62680. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62681. get: function () {
  62682. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62683. },
  62684. enumerable: true,
  62685. configurable: true
  62686. });
  62687. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62688. get: function () {
  62689. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62690. },
  62691. enumerable: true,
  62692. configurable: true
  62693. });
  62694. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62695. get: function () {
  62696. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62697. },
  62698. enumerable: true,
  62699. configurable: true
  62700. });
  62701. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62702. set: function (callback) {
  62703. if (this._onAfterUnbindObserver) {
  62704. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62705. }
  62706. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62707. },
  62708. enumerable: true,
  62709. configurable: true
  62710. });
  62711. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62712. set: function (callback) {
  62713. if (this._onBeforeRenderObserver) {
  62714. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62715. }
  62716. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62717. },
  62718. enumerable: true,
  62719. configurable: true
  62720. });
  62721. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62722. set: function (callback) {
  62723. if (this._onAfterRenderObserver) {
  62724. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62725. }
  62726. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62727. },
  62728. enumerable: true,
  62729. configurable: true
  62730. });
  62731. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62732. set: function (callback) {
  62733. if (this._onClearObserver) {
  62734. this.onClearObservable.remove(this._onClearObserver);
  62735. }
  62736. this._onClearObserver = this.onClearObservable.add(callback);
  62737. },
  62738. enumerable: true,
  62739. configurable: true
  62740. });
  62741. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62742. get: function () {
  62743. return this._renderTargetOptions;
  62744. },
  62745. enumerable: true,
  62746. configurable: true
  62747. });
  62748. RenderTargetTexture.prototype._onRatioRescale = function () {
  62749. if (this._sizeRatio) {
  62750. this.resize(this._initialSizeParameter);
  62751. }
  62752. };
  62753. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62754. get: function () {
  62755. return this._boundingBoxSize;
  62756. },
  62757. /**
  62758. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62759. * When defined, the cubemap will switch to local mode
  62760. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62761. * @example https://www.babylonjs-playground.com/#RNASML
  62762. */
  62763. set: function (value) {
  62764. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62765. return;
  62766. }
  62767. this._boundingBoxSize = value;
  62768. var scene = this.getScene();
  62769. if (scene) {
  62770. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62771. }
  62772. },
  62773. enumerable: true,
  62774. configurable: true
  62775. });
  62776. /**
  62777. * Creates a depth stencil texture.
  62778. * This is only available in WebGL 2 or with the depth texture extension available.
  62779. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62780. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62781. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62782. */
  62783. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62784. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62785. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62786. if (generateStencil === void 0) { generateStencil = false; }
  62787. if (!this.getScene()) {
  62788. return;
  62789. }
  62790. var engine = this.getScene().getEngine();
  62791. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62792. bilinearFiltering: bilinearFiltering,
  62793. comparisonFunction: comparisonFunction,
  62794. generateStencil: generateStencil,
  62795. isCube: this.isCube
  62796. });
  62797. engine.setFrameBufferDepthStencilTexture(this);
  62798. };
  62799. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62800. if (size.ratio) {
  62801. this._sizeRatio = size.ratio;
  62802. this._size = {
  62803. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62804. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62805. };
  62806. }
  62807. else {
  62808. this._size = size;
  62809. }
  62810. };
  62811. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62812. get: function () {
  62813. return this._samples;
  62814. },
  62815. set: function (value) {
  62816. if (this._samples === value) {
  62817. return;
  62818. }
  62819. var scene = this.getScene();
  62820. if (!scene) {
  62821. return;
  62822. }
  62823. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62824. },
  62825. enumerable: true,
  62826. configurable: true
  62827. });
  62828. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62829. this._currentRefreshId = -1;
  62830. };
  62831. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62832. get: function () {
  62833. return this._refreshRate;
  62834. },
  62835. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62836. set: function (value) {
  62837. this._refreshRate = value;
  62838. this.resetRefreshCounter();
  62839. },
  62840. enumerable: true,
  62841. configurable: true
  62842. });
  62843. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62844. if (!this._postProcessManager) {
  62845. var scene = this.getScene();
  62846. if (!scene) {
  62847. return;
  62848. }
  62849. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62850. this._postProcesses = new Array();
  62851. }
  62852. this._postProcesses.push(postProcess);
  62853. this._postProcesses[0].autoClear = false;
  62854. };
  62855. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62856. if (!this._postProcesses) {
  62857. return;
  62858. }
  62859. if (dispose) {
  62860. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62861. var postProcess = _a[_i];
  62862. postProcess.dispose();
  62863. }
  62864. }
  62865. this._postProcesses = [];
  62866. };
  62867. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62868. if (!this._postProcesses) {
  62869. return;
  62870. }
  62871. var index = this._postProcesses.indexOf(postProcess);
  62872. if (index === -1) {
  62873. return;
  62874. }
  62875. this._postProcesses.splice(index, 1);
  62876. if (this._postProcesses.length > 0) {
  62877. this._postProcesses[0].autoClear = false;
  62878. }
  62879. };
  62880. RenderTargetTexture.prototype._shouldRender = function () {
  62881. if (this._currentRefreshId === -1) { // At least render once
  62882. this._currentRefreshId = 1;
  62883. return true;
  62884. }
  62885. if (this.refreshRate === this._currentRefreshId) {
  62886. this._currentRefreshId = 1;
  62887. return true;
  62888. }
  62889. this._currentRefreshId++;
  62890. return false;
  62891. };
  62892. RenderTargetTexture.prototype.getRenderSize = function () {
  62893. if (this._size.width) {
  62894. return this._size.width;
  62895. }
  62896. return this._size;
  62897. };
  62898. RenderTargetTexture.prototype.getRenderWidth = function () {
  62899. if (this._size.width) {
  62900. return this._size.width;
  62901. }
  62902. return this._size;
  62903. };
  62904. RenderTargetTexture.prototype.getRenderHeight = function () {
  62905. if (this._size.width) {
  62906. return this._size.height;
  62907. }
  62908. return this._size;
  62909. };
  62910. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62911. get: function () {
  62912. return true;
  62913. },
  62914. enumerable: true,
  62915. configurable: true
  62916. });
  62917. RenderTargetTexture.prototype.scale = function (ratio) {
  62918. var newSize = this.getRenderSize() * ratio;
  62919. this.resize(newSize);
  62920. };
  62921. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62922. if (this.isCube) {
  62923. return this._textureMatrix;
  62924. }
  62925. return _super.prototype.getReflectionTextureMatrix.call(this);
  62926. };
  62927. RenderTargetTexture.prototype.resize = function (size) {
  62928. this.releaseInternalTexture();
  62929. var scene = this.getScene();
  62930. if (!scene) {
  62931. return;
  62932. }
  62933. this._processSizeParameter(size);
  62934. if (this.isCube) {
  62935. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62936. }
  62937. else {
  62938. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62939. }
  62940. };
  62941. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62942. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62943. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62944. var scene = this.getScene();
  62945. if (!scene) {
  62946. return;
  62947. }
  62948. var engine = scene.getEngine();
  62949. if (this.useCameraPostProcesses !== undefined) {
  62950. useCameraPostProcess = this.useCameraPostProcesses;
  62951. }
  62952. if (this._waitingRenderList) {
  62953. this.renderList = [];
  62954. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62955. var id = this._waitingRenderList[index];
  62956. var mesh_1 = scene.getMeshByID(id);
  62957. if (mesh_1) {
  62958. this.renderList.push(mesh_1);
  62959. }
  62960. }
  62961. delete this._waitingRenderList;
  62962. }
  62963. // Is predicate defined?
  62964. if (this.renderListPredicate) {
  62965. if (this.renderList) {
  62966. this.renderList.splice(0); // Clear previous renderList
  62967. }
  62968. else {
  62969. this.renderList = [];
  62970. }
  62971. var scene = this.getScene();
  62972. if (!scene) {
  62973. return;
  62974. }
  62975. var sceneMeshes = scene.meshes;
  62976. for (var index = 0; index < sceneMeshes.length; index++) {
  62977. var mesh = sceneMeshes[index];
  62978. if (this.renderListPredicate(mesh)) {
  62979. this.renderList.push(mesh);
  62980. }
  62981. }
  62982. }
  62983. this.onBeforeBindObservable.notifyObservers(this);
  62984. // Set custom projection.
  62985. // Needs to be before binding to prevent changing the aspect ratio.
  62986. var camera;
  62987. if (this.activeCamera) {
  62988. camera = this.activeCamera;
  62989. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62990. if (this.activeCamera !== scene.activeCamera) {
  62991. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62992. }
  62993. }
  62994. else {
  62995. camera = scene.activeCamera;
  62996. if (camera) {
  62997. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62998. }
  62999. }
  63000. // Prepare renderingManager
  63001. this._renderingManager.reset();
  63002. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63003. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63004. var sceneRenderId = scene.getRenderId();
  63005. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63006. var mesh = currentRenderList[meshIndex];
  63007. if (mesh) {
  63008. if (!mesh.isReady(this.refreshRate === 0)) {
  63009. this.resetRefreshCounter();
  63010. continue;
  63011. }
  63012. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63013. var isMasked = void 0;
  63014. if (!this.renderList && camera) {
  63015. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63016. }
  63017. else {
  63018. isMasked = false;
  63019. }
  63020. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63021. mesh._activate(sceneRenderId);
  63022. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63023. var subMesh = mesh.subMeshes[subIndex];
  63024. scene._activeIndices.addCount(subMesh.indexCount, false);
  63025. this._renderingManager.dispatch(subMesh, mesh);
  63026. }
  63027. }
  63028. }
  63029. }
  63030. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63031. var particleSystem = scene.particleSystems[particleIndex];
  63032. var emitter = particleSystem.emitter;
  63033. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63034. continue;
  63035. }
  63036. if (currentRenderList.indexOf(emitter) >= 0) {
  63037. this._renderingManager.dispatchParticles(particleSystem);
  63038. }
  63039. }
  63040. if (this.isCube) {
  63041. for (var face = 0; face < 6; face++) {
  63042. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63043. scene.incrementRenderId();
  63044. scene.resetCachedMaterial();
  63045. }
  63046. }
  63047. else {
  63048. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63049. }
  63050. this.onAfterUnbindObservable.notifyObservers(this);
  63051. if (scene.activeCamera) {
  63052. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63053. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63054. }
  63055. engine.setViewport(scene.activeCamera.viewport);
  63056. }
  63057. scene.resetCachedMaterial();
  63058. };
  63059. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63060. var minimum = 128;
  63061. var x = renderDimension * scale;
  63062. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63063. // Ensure we don't exceed the render dimension (while staying POT)
  63064. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63065. };
  63066. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63067. var _this = this;
  63068. if (!this._texture) {
  63069. return;
  63070. }
  63071. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63072. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63073. });
  63074. };
  63075. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63076. var scene = this.getScene();
  63077. if (!scene) {
  63078. return;
  63079. }
  63080. var engine = scene.getEngine();
  63081. if (!this._texture) {
  63082. return;
  63083. }
  63084. // Bind
  63085. if (this._postProcessManager) {
  63086. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63087. }
  63088. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63089. if (this._texture) {
  63090. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63091. }
  63092. }
  63093. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63094. // Clear
  63095. if (this.onClearObservable.hasObservers()) {
  63096. this.onClearObservable.notifyObservers(engine);
  63097. }
  63098. else {
  63099. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63100. }
  63101. if (!this._doNotChangeAspectRatio) {
  63102. scene.updateTransformMatrix(true);
  63103. }
  63104. // Render
  63105. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63106. if (this._postProcessManager) {
  63107. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63108. }
  63109. else if (useCameraPostProcess) {
  63110. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63111. }
  63112. if (!this._doNotChangeAspectRatio) {
  63113. scene.updateTransformMatrix(true);
  63114. }
  63115. // Dump ?
  63116. if (dumpForDebug) {
  63117. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63118. }
  63119. // Unbind
  63120. if (!this.isCube || faceIndex === 5) {
  63121. if (this.isCube) {
  63122. if (faceIndex === 5) {
  63123. engine.generateMipMapsForCubemap(this._texture);
  63124. }
  63125. }
  63126. this.unbindFrameBuffer(engine, faceIndex);
  63127. }
  63128. else {
  63129. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63130. }
  63131. };
  63132. /**
  63133. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63134. * This allowed control for front to back rendering or reversly depending of the special needs.
  63135. *
  63136. * @param renderingGroupId The rendering group id corresponding to its index
  63137. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63138. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63139. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63140. */
  63141. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63142. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63143. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63144. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63145. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63146. };
  63147. /**
  63148. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63149. *
  63150. * @param renderingGroupId The rendering group id corresponding to its index
  63151. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63152. */
  63153. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63154. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63155. };
  63156. RenderTargetTexture.prototype.clone = function () {
  63157. var textureSize = this.getSize();
  63158. 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);
  63159. // Base texture
  63160. newTexture.hasAlpha = this.hasAlpha;
  63161. newTexture.level = this.level;
  63162. // RenderTarget Texture
  63163. newTexture.coordinatesMode = this.coordinatesMode;
  63164. if (this.renderList) {
  63165. newTexture.renderList = this.renderList.slice(0);
  63166. }
  63167. return newTexture;
  63168. };
  63169. RenderTargetTexture.prototype.serialize = function () {
  63170. if (!this.name) {
  63171. return null;
  63172. }
  63173. var serializationObject = _super.prototype.serialize.call(this);
  63174. serializationObject.renderTargetSize = this.getRenderSize();
  63175. serializationObject.renderList = [];
  63176. if (this.renderList) {
  63177. for (var index = 0; index < this.renderList.length; index++) {
  63178. serializationObject.renderList.push(this.renderList[index].id);
  63179. }
  63180. }
  63181. return serializationObject;
  63182. };
  63183. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63184. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63185. var objBuffer = this.getInternalTexture();
  63186. var scene = this.getScene();
  63187. if (objBuffer && scene) {
  63188. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63189. }
  63190. };
  63191. RenderTargetTexture.prototype.dispose = function () {
  63192. if (this._postProcessManager) {
  63193. this._postProcessManager.dispose();
  63194. this._postProcessManager = null;
  63195. }
  63196. this.clearPostProcesses(true);
  63197. if (this._resizeObserver) {
  63198. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63199. this._resizeObserver = null;
  63200. }
  63201. this.renderList = null;
  63202. // Remove from custom render targets
  63203. var scene = this.getScene();
  63204. if (!scene) {
  63205. return;
  63206. }
  63207. var index = scene.customRenderTargets.indexOf(this);
  63208. if (index >= 0) {
  63209. scene.customRenderTargets.splice(index, 1);
  63210. }
  63211. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63212. var camera = _a[_i];
  63213. index = camera.customRenderTargets.indexOf(this);
  63214. if (index >= 0) {
  63215. camera.customRenderTargets.splice(index, 1);
  63216. }
  63217. }
  63218. _super.prototype.dispose.call(this);
  63219. };
  63220. RenderTargetTexture.prototype._rebuild = function () {
  63221. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63222. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63223. }
  63224. if (this._postProcessManager) {
  63225. this._postProcessManager._rebuild();
  63226. }
  63227. };
  63228. /**
  63229. * Clear the info related to rendering groups preventing retention point in material dispose.
  63230. */
  63231. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63232. if (this._renderingManager) {
  63233. this._renderingManager.freeRenderingGroups();
  63234. }
  63235. };
  63236. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63237. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63238. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63239. return RenderTargetTexture;
  63240. }(BABYLON.Texture));
  63241. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63242. })(BABYLON || (BABYLON = {}));
  63243. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63244. var BABYLON;
  63245. (function (BABYLON) {
  63246. ;
  63247. var MultiRenderTarget = /** @class */ (function (_super) {
  63248. __extends(MultiRenderTarget, _super);
  63249. function MultiRenderTarget(name, size, count, scene, options) {
  63250. var _this = this;
  63251. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63252. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63253. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63254. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63255. _this._engine = scene.getEngine();
  63256. if (!_this.isSupported) {
  63257. _this.dispose();
  63258. return;
  63259. }
  63260. var types = [];
  63261. var samplingModes = [];
  63262. for (var i = 0; i < count; i++) {
  63263. if (options && options.types && options.types[i] !== undefined) {
  63264. types.push(options.types[i]);
  63265. }
  63266. else {
  63267. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63268. }
  63269. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63270. samplingModes.push(options.samplingModes[i]);
  63271. }
  63272. else {
  63273. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63274. }
  63275. }
  63276. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63277. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63278. _this._size = size;
  63279. _this._multiRenderTargetOptions = {
  63280. samplingModes: samplingModes,
  63281. generateMipMaps: generateMipMaps,
  63282. generateDepthBuffer: generateDepthBuffer,
  63283. generateStencilBuffer: generateStencilBuffer,
  63284. generateDepthTexture: generateDepthTexture,
  63285. types: types,
  63286. textureCount: count
  63287. };
  63288. _this._createInternalTextures();
  63289. _this._createTextures();
  63290. return _this;
  63291. }
  63292. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63293. get: function () {
  63294. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63295. },
  63296. enumerable: true,
  63297. configurable: true
  63298. });
  63299. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63300. get: function () {
  63301. return this._textures;
  63302. },
  63303. enumerable: true,
  63304. configurable: true
  63305. });
  63306. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63307. get: function () {
  63308. return this._textures[this._textures.length - 1];
  63309. },
  63310. enumerable: true,
  63311. configurable: true
  63312. });
  63313. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63314. set: function (wrap) {
  63315. if (this._textures) {
  63316. for (var i = 0; i < this._textures.length; i++) {
  63317. this._textures[i].wrapU = wrap;
  63318. }
  63319. }
  63320. },
  63321. enumerable: true,
  63322. configurable: true
  63323. });
  63324. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63325. set: function (wrap) {
  63326. if (this._textures) {
  63327. for (var i = 0; i < this._textures.length; i++) {
  63328. this._textures[i].wrapV = wrap;
  63329. }
  63330. }
  63331. },
  63332. enumerable: true,
  63333. configurable: true
  63334. });
  63335. MultiRenderTarget.prototype._rebuild = function () {
  63336. this.releaseInternalTextures();
  63337. this._createInternalTextures();
  63338. for (var i = 0; i < this._internalTextures.length; i++) {
  63339. var texture = this._textures[i];
  63340. texture._texture = this._internalTextures[i];
  63341. }
  63342. // Keeps references to frame buffer and stencil/depth buffer
  63343. this._texture = this._internalTextures[0];
  63344. };
  63345. MultiRenderTarget.prototype._createInternalTextures = function () {
  63346. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63347. };
  63348. MultiRenderTarget.prototype._createTextures = function () {
  63349. this._textures = [];
  63350. for (var i = 0; i < this._internalTextures.length; i++) {
  63351. var texture = new BABYLON.Texture(null, this.getScene());
  63352. texture._texture = this._internalTextures[i];
  63353. this._textures.push(texture);
  63354. }
  63355. // Keeps references to frame buffer and stencil/depth buffer
  63356. this._texture = this._internalTextures[0];
  63357. };
  63358. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63359. get: function () {
  63360. return this._samples;
  63361. },
  63362. set: function (value) {
  63363. if (this._samples === value) {
  63364. return;
  63365. }
  63366. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63367. },
  63368. enumerable: true,
  63369. configurable: true
  63370. });
  63371. MultiRenderTarget.prototype.resize = function (size) {
  63372. this.releaseInternalTextures();
  63373. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63374. this._createInternalTextures();
  63375. };
  63376. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63377. var _this = this;
  63378. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63379. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63380. });
  63381. };
  63382. MultiRenderTarget.prototype.dispose = function () {
  63383. this.releaseInternalTextures();
  63384. _super.prototype.dispose.call(this);
  63385. };
  63386. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63387. if (!this._internalTextures) {
  63388. return;
  63389. }
  63390. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63391. if (this._internalTextures[i] !== undefined) {
  63392. this._internalTextures[i].dispose();
  63393. this._internalTextures.splice(i, 1);
  63394. }
  63395. }
  63396. };
  63397. return MultiRenderTarget;
  63398. }(BABYLON.RenderTargetTexture));
  63399. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63400. })(BABYLON || (BABYLON = {}));
  63401. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63402. var BABYLON;
  63403. (function (BABYLON) {
  63404. var MirrorTexture = /** @class */ (function (_super) {
  63405. __extends(MirrorTexture, _super);
  63406. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63407. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63409. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63410. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63411. _this.scene = scene;
  63412. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63413. _this._transformMatrix = BABYLON.Matrix.Zero();
  63414. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63415. _this._adaptiveBlurKernel = 0;
  63416. _this._blurKernelX = 0;
  63417. _this._blurKernelY = 0;
  63418. _this._blurRatio = 1.0;
  63419. _this.ignoreCameraViewport = true;
  63420. _this._updateGammaSpace();
  63421. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63422. _this._updateGammaSpace;
  63423. });
  63424. _this.onBeforeRenderObservable.add(function () {
  63425. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63426. _this._savedViewMatrix = scene.getViewMatrix();
  63427. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63428. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63429. scene.clipPlane = _this.mirrorPlane;
  63430. scene.getEngine().cullBackFaces = false;
  63431. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63432. });
  63433. _this.onAfterRenderObservable.add(function () {
  63434. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63435. scene.getEngine().cullBackFaces = true;
  63436. scene._mirroredCameraPosition = null;
  63437. delete scene.clipPlane;
  63438. });
  63439. return _this;
  63440. }
  63441. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63442. get: function () {
  63443. return this._blurRatio;
  63444. },
  63445. set: function (value) {
  63446. if (this._blurRatio === value) {
  63447. return;
  63448. }
  63449. this._blurRatio = value;
  63450. this._preparePostProcesses();
  63451. },
  63452. enumerable: true,
  63453. configurable: true
  63454. });
  63455. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63456. set: function (value) {
  63457. this._adaptiveBlurKernel = value;
  63458. this._autoComputeBlurKernel();
  63459. },
  63460. enumerable: true,
  63461. configurable: true
  63462. });
  63463. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63464. set: function (value) {
  63465. this.blurKernelX = value;
  63466. this.blurKernelY = value;
  63467. },
  63468. enumerable: true,
  63469. configurable: true
  63470. });
  63471. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63472. get: function () {
  63473. return this._blurKernelX;
  63474. },
  63475. set: function (value) {
  63476. if (this._blurKernelX === value) {
  63477. return;
  63478. }
  63479. this._blurKernelX = value;
  63480. this._preparePostProcesses();
  63481. },
  63482. enumerable: true,
  63483. configurable: true
  63484. });
  63485. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63486. get: function () {
  63487. return this._blurKernelY;
  63488. },
  63489. set: function (value) {
  63490. if (this._blurKernelY === value) {
  63491. return;
  63492. }
  63493. this._blurKernelY = value;
  63494. this._preparePostProcesses();
  63495. },
  63496. enumerable: true,
  63497. configurable: true
  63498. });
  63499. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63500. var engine = this.getScene().getEngine();
  63501. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63502. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63503. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63504. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63505. };
  63506. MirrorTexture.prototype._onRatioRescale = function () {
  63507. if (this._sizeRatio) {
  63508. this.resize(this._initialSizeParameter);
  63509. if (!this._adaptiveBlurKernel) {
  63510. this._preparePostProcesses();
  63511. }
  63512. }
  63513. if (this._adaptiveBlurKernel) {
  63514. this._autoComputeBlurKernel();
  63515. }
  63516. };
  63517. MirrorTexture.prototype._updateGammaSpace = function () {
  63518. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63519. };
  63520. MirrorTexture.prototype._preparePostProcesses = function () {
  63521. this.clearPostProcesses(true);
  63522. if (this._blurKernelX && this._blurKernelY) {
  63523. var engine = this.getScene().getEngine();
  63524. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63525. 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);
  63526. this._blurX.autoClear = false;
  63527. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63528. this._blurX.inputTexture = this._texture;
  63529. }
  63530. else {
  63531. this._blurX.alwaysForcePOT = true;
  63532. }
  63533. 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);
  63534. this._blurY.autoClear = false;
  63535. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63536. this.addPostProcess(this._blurX);
  63537. this.addPostProcess(this._blurY);
  63538. }
  63539. else {
  63540. if (this._blurY) {
  63541. this.removePostProcess(this._blurY);
  63542. this._blurY.dispose();
  63543. this._blurY = null;
  63544. }
  63545. if (this._blurX) {
  63546. this.removePostProcess(this._blurX);
  63547. this._blurX.dispose();
  63548. this._blurX = null;
  63549. }
  63550. }
  63551. };
  63552. MirrorTexture.prototype.clone = function () {
  63553. var scene = this.getScene();
  63554. if (!scene) {
  63555. return this;
  63556. }
  63557. var textureSize = this.getSize();
  63558. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63559. // Base texture
  63560. newTexture.hasAlpha = this.hasAlpha;
  63561. newTexture.level = this.level;
  63562. // Mirror Texture
  63563. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63564. if (this.renderList) {
  63565. newTexture.renderList = this.renderList.slice(0);
  63566. }
  63567. return newTexture;
  63568. };
  63569. MirrorTexture.prototype.serialize = function () {
  63570. if (!this.name) {
  63571. return null;
  63572. }
  63573. var serializationObject = _super.prototype.serialize.call(this);
  63574. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63575. return serializationObject;
  63576. };
  63577. MirrorTexture.prototype.dispose = function () {
  63578. _super.prototype.dispose.call(this);
  63579. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63580. };
  63581. return MirrorTexture;
  63582. }(BABYLON.RenderTargetTexture));
  63583. BABYLON.MirrorTexture = MirrorTexture;
  63584. })(BABYLON || (BABYLON = {}));
  63585. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63586. var BABYLON;
  63587. (function (BABYLON) {
  63588. /**
  63589. * Creates a refraction texture used by refraction channel of the standard material.
  63590. * @param name the texture name
  63591. * @param size size of the underlying texture
  63592. * @param scene root scene
  63593. */
  63594. var RefractionTexture = /** @class */ (function (_super) {
  63595. __extends(RefractionTexture, _super);
  63596. function RefractionTexture(name, size, scene, generateMipMaps) {
  63597. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63598. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63599. _this.depth = 2.0;
  63600. _this.onBeforeRenderObservable.add(function () {
  63601. scene.clipPlane = _this.refractionPlane;
  63602. });
  63603. _this.onAfterRenderObservable.add(function () {
  63604. delete scene.clipPlane;
  63605. });
  63606. return _this;
  63607. }
  63608. RefractionTexture.prototype.clone = function () {
  63609. var scene = this.getScene();
  63610. if (!scene) {
  63611. return this;
  63612. }
  63613. var textureSize = this.getSize();
  63614. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63615. // Base texture
  63616. newTexture.hasAlpha = this.hasAlpha;
  63617. newTexture.level = this.level;
  63618. // Refraction Texture
  63619. newTexture.refractionPlane = this.refractionPlane.clone();
  63620. if (this.renderList) {
  63621. newTexture.renderList = this.renderList.slice(0);
  63622. }
  63623. newTexture.depth = this.depth;
  63624. return newTexture;
  63625. };
  63626. RefractionTexture.prototype.serialize = function () {
  63627. if (!this.name) {
  63628. return null;
  63629. }
  63630. var serializationObject = _super.prototype.serialize.call(this);
  63631. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63632. serializationObject.depth = this.depth;
  63633. return serializationObject;
  63634. };
  63635. return RefractionTexture;
  63636. }(BABYLON.RenderTargetTexture));
  63637. BABYLON.RefractionTexture = RefractionTexture;
  63638. })(BABYLON || (BABYLON = {}));
  63639. //# sourceMappingURL=babylon.refractionTexture.js.map
  63640. var BABYLON;
  63641. (function (BABYLON) {
  63642. /**
  63643. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63644. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63645. */
  63646. var DynamicTexture = /** @class */ (function (_super) {
  63647. __extends(DynamicTexture, _super);
  63648. /**
  63649. * Creates a {BABYLON.DynamicTexture}
  63650. * @param name defines the name of the texture
  63651. * @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
  63652. * @param scene defines the scene where you want the texture
  63653. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63654. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63655. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63656. */
  63657. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63658. if (scene === void 0) { scene = null; }
  63659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63660. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63661. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63662. _this.name = name;
  63663. _this._engine = _this.getScene().getEngine();
  63664. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63665. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63666. _this._generateMipMaps = generateMipMaps;
  63667. if (options.getContext) {
  63668. _this._canvas = options;
  63669. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63670. }
  63671. else {
  63672. _this._canvas = document.createElement("canvas");
  63673. if (options.width || options.width === 0) {
  63674. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63675. }
  63676. else {
  63677. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63678. }
  63679. }
  63680. var textureSize = _this.getSize();
  63681. _this._canvas.width = textureSize.width;
  63682. _this._canvas.height = textureSize.height;
  63683. _this._context = _this._canvas.getContext("2d");
  63684. return _this;
  63685. }
  63686. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63687. /**
  63688. * Gets the current state of canRescale
  63689. */
  63690. get: function () {
  63691. return true;
  63692. },
  63693. enumerable: true,
  63694. configurable: true
  63695. });
  63696. DynamicTexture.prototype._recreate = function (textureSize) {
  63697. this._canvas.width = textureSize.width;
  63698. this._canvas.height = textureSize.height;
  63699. this.releaseInternalTexture();
  63700. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63701. };
  63702. /**
  63703. * Scales the texture
  63704. * @param ratio the scale factor to apply to both width and height
  63705. */
  63706. DynamicTexture.prototype.scale = function (ratio) {
  63707. var textureSize = this.getSize();
  63708. textureSize.width *= ratio;
  63709. textureSize.height *= ratio;
  63710. this._recreate(textureSize);
  63711. };
  63712. /**
  63713. * Resizes the texture
  63714. * @param width the new width
  63715. * @param height the new height
  63716. */
  63717. DynamicTexture.prototype.scaleTo = function (width, height) {
  63718. var textureSize = this.getSize();
  63719. textureSize.width = width;
  63720. textureSize.height = height;
  63721. this._recreate(textureSize);
  63722. };
  63723. /**
  63724. * Gets the context of the canvas used by the texture
  63725. * @returns the canvas context of the dynamic texture
  63726. */
  63727. DynamicTexture.prototype.getContext = function () {
  63728. return this._context;
  63729. };
  63730. /**
  63731. * Clears the texture
  63732. */
  63733. DynamicTexture.prototype.clear = function () {
  63734. var size = this.getSize();
  63735. this._context.fillRect(0, 0, size.width, size.height);
  63736. };
  63737. /**
  63738. * Updates the texture
  63739. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63740. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  63741. */
  63742. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  63743. if (premulAlpha === void 0) { premulAlpha = false; }
  63744. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  63745. };
  63746. /**
  63747. * Draws text onto the texture
  63748. * @param text defines the text to be drawn
  63749. * @param x defines the placement of the text from the left
  63750. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63751. * @param font defines the font to be used with font-style, font-size, font-name
  63752. * @param color defines the color used for the text
  63753. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63754. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63755. * @param update defines whether texture is immediately update (default is true)
  63756. */
  63757. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63758. if (update === void 0) { update = true; }
  63759. var size = this.getSize();
  63760. if (clearColor) {
  63761. this._context.fillStyle = clearColor;
  63762. this._context.fillRect(0, 0, size.width, size.height);
  63763. }
  63764. this._context.font = font;
  63765. if (x === null || x === undefined) {
  63766. var textSize = this._context.measureText(text);
  63767. x = (size.width - textSize.width) / 2;
  63768. }
  63769. if (y === null || y === undefined) {
  63770. var fontSize = parseInt((font.replace(/\D/g, '')));
  63771. y = (size.height / 2) + (fontSize / 3.65);
  63772. }
  63773. this._context.fillStyle = color;
  63774. this._context.fillText(text, x, y);
  63775. if (update) {
  63776. this.update(invertY);
  63777. }
  63778. };
  63779. /**
  63780. * Clones the texture
  63781. * @returns the clone of the texture.
  63782. */
  63783. DynamicTexture.prototype.clone = function () {
  63784. var scene = this.getScene();
  63785. if (!scene) {
  63786. return this;
  63787. }
  63788. var textureSize = this.getSize();
  63789. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63790. // Base texture
  63791. newTexture.hasAlpha = this.hasAlpha;
  63792. newTexture.level = this.level;
  63793. // Dynamic Texture
  63794. newTexture.wrapU = this.wrapU;
  63795. newTexture.wrapV = this.wrapV;
  63796. return newTexture;
  63797. };
  63798. /** @hidden */
  63799. DynamicTexture.prototype._rebuild = function () {
  63800. this.update();
  63801. };
  63802. return DynamicTexture;
  63803. }(BABYLON.Texture));
  63804. BABYLON.DynamicTexture = DynamicTexture;
  63805. })(BABYLON || (BABYLON = {}));
  63806. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63807. var BABYLON;
  63808. (function (BABYLON) {
  63809. var VideoTexture = /** @class */ (function (_super) {
  63810. __extends(VideoTexture, _super);
  63811. /**
  63812. * Creates a video texture.
  63813. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63814. * @param {string | null} name optional name, will detect from video source, if not defined
  63815. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63816. * @param {BABYLON.Scene} scene is obviously the current scene.
  63817. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63818. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63819. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63820. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63821. */
  63822. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63823. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63824. if (invertY === void 0) { invertY = false; }
  63825. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63826. if (settings === void 0) { settings = {
  63827. autoPlay: true,
  63828. loop: true,
  63829. autoUpdateTexture: true,
  63830. }; }
  63831. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63832. _this._stillImageCaptured = false;
  63833. _this._createInternalTexture = function () {
  63834. if (_this._texture != null) {
  63835. return;
  63836. }
  63837. if (!_this._engine.needPOTTextures ||
  63838. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63839. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63840. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63841. }
  63842. else {
  63843. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63844. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63845. _this._generateMipMaps = false;
  63846. }
  63847. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63848. if (!_this.video.autoplay) {
  63849. var oldHandler_1 = _this.video.onplaying;
  63850. _this.video.onplaying = function () {
  63851. _this.video.onplaying = oldHandler_1;
  63852. _this._texture.isReady = true;
  63853. _this._updateInternalTexture();
  63854. _this.video.pause();
  63855. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63856. _this.onLoadObservable.notifyObservers(_this);
  63857. }
  63858. };
  63859. _this.video.play();
  63860. }
  63861. else {
  63862. _this._texture.isReady = true;
  63863. _this._updateInternalTexture();
  63864. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63865. _this.onLoadObservable.notifyObservers(_this);
  63866. }
  63867. }
  63868. };
  63869. _this.reset = function () {
  63870. if (_this._texture == null) {
  63871. return;
  63872. }
  63873. _this._texture.dispose();
  63874. _this._texture = null;
  63875. };
  63876. _this._updateInternalTexture = function (e) {
  63877. if (_this._texture == null || !_this._texture.isReady) {
  63878. return;
  63879. }
  63880. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63881. return;
  63882. }
  63883. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63884. };
  63885. _this._engine = _this.getScene().getEngine();
  63886. _this._generateMipMaps = generateMipMaps;
  63887. _this._samplingMode = samplingMode;
  63888. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63889. _this.name = name || _this._getName(src);
  63890. _this.video = _this._getVideo(src);
  63891. if (settings.autoPlay !== undefined) {
  63892. _this.video.autoplay = settings.autoPlay;
  63893. }
  63894. if (settings.loop !== undefined) {
  63895. _this.video.loop = settings.loop;
  63896. }
  63897. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63898. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63899. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63900. _this.video.addEventListener("emptied", _this.reset);
  63901. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63902. _this._createInternalTexture();
  63903. }
  63904. return _this;
  63905. }
  63906. VideoTexture.prototype._getName = function (src) {
  63907. if (src instanceof HTMLVideoElement) {
  63908. return src.currentSrc;
  63909. }
  63910. if (typeof src === "object") {
  63911. return src.toString();
  63912. }
  63913. return src;
  63914. };
  63915. ;
  63916. VideoTexture.prototype._getVideo = function (src) {
  63917. if (src instanceof HTMLVideoElement) {
  63918. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63919. return src;
  63920. }
  63921. var video = document.createElement("video");
  63922. if (typeof src === "string") {
  63923. BABYLON.Tools.SetCorsBehavior(src, video);
  63924. video.src = src;
  63925. }
  63926. else {
  63927. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63928. src.forEach(function (url) {
  63929. var source = document.createElement("source");
  63930. source.src = url;
  63931. video.appendChild(source);
  63932. });
  63933. }
  63934. return video;
  63935. };
  63936. ;
  63937. /**
  63938. * Internal method to initiate `update`.
  63939. */
  63940. VideoTexture.prototype._rebuild = function () {
  63941. this.update();
  63942. };
  63943. /**
  63944. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63945. */
  63946. VideoTexture.prototype.update = function () {
  63947. if (!this.autoUpdateTexture) {
  63948. // Expecting user to call `updateTexture` manually
  63949. return;
  63950. }
  63951. this.updateTexture(true);
  63952. };
  63953. /**
  63954. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63955. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63956. */
  63957. VideoTexture.prototype.updateTexture = function (isVisible) {
  63958. if (!isVisible) {
  63959. return;
  63960. }
  63961. if (this.video.paused && this._stillImageCaptured) {
  63962. return;
  63963. }
  63964. this._stillImageCaptured = true;
  63965. this._updateInternalTexture();
  63966. };
  63967. /**
  63968. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63969. * @param url New url.
  63970. */
  63971. VideoTexture.prototype.updateURL = function (url) {
  63972. this.video.src = url;
  63973. };
  63974. VideoTexture.prototype.dispose = function () {
  63975. _super.prototype.dispose.call(this);
  63976. this.video.removeEventListener("canplay", this._createInternalTexture);
  63977. this.video.removeEventListener("paused", this._updateInternalTexture);
  63978. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63979. this.video.removeEventListener("emptied", this.reset);
  63980. this.video.pause();
  63981. };
  63982. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63983. var video = document.createElement("video");
  63984. var constraintsDeviceId;
  63985. if (constraints && constraints.deviceId) {
  63986. constraintsDeviceId = {
  63987. exact: constraints.deviceId,
  63988. };
  63989. }
  63990. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63991. if (navigator.mediaDevices) {
  63992. navigator.mediaDevices.getUserMedia({ video: constraints })
  63993. .then(function (stream) {
  63994. if (video.mozSrcObject !== undefined) {
  63995. // hack for Firefox < 19
  63996. video.mozSrcObject = stream;
  63997. }
  63998. else {
  63999. video.srcObject = stream;
  64000. }
  64001. var onPlaying = function () {
  64002. if (onReady) {
  64003. onReady(new VideoTexture("video", video, scene, true, true));
  64004. }
  64005. video.removeEventListener("playing", onPlaying);
  64006. };
  64007. video.addEventListener("playing", onPlaying);
  64008. video.play();
  64009. })
  64010. .catch(function (err) {
  64011. BABYLON.Tools.Error(err.name);
  64012. });
  64013. }
  64014. else {
  64015. navigator.getUserMedia =
  64016. navigator.getUserMedia ||
  64017. navigator.webkitGetUserMedia ||
  64018. navigator.mozGetUserMedia ||
  64019. navigator.msGetUserMedia;
  64020. if (navigator.getUserMedia) {
  64021. navigator.getUserMedia({
  64022. video: {
  64023. deviceId: constraintsDeviceId,
  64024. width: {
  64025. min: (constraints && constraints.minWidth) || 256,
  64026. max: (constraints && constraints.maxWidth) || 640,
  64027. },
  64028. height: {
  64029. min: (constraints && constraints.minHeight) || 256,
  64030. max: (constraints && constraints.maxHeight) || 480,
  64031. },
  64032. },
  64033. }, function (stream) {
  64034. if (video.mozSrcObject !== undefined) {
  64035. // hack for Firefox < 19
  64036. video.mozSrcObject = stream;
  64037. }
  64038. else {
  64039. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64040. }
  64041. video.play();
  64042. if (onReady) {
  64043. onReady(new VideoTexture("video", video, scene, true, true));
  64044. }
  64045. }, function (e) {
  64046. BABYLON.Tools.Error(e.name);
  64047. });
  64048. }
  64049. }
  64050. };
  64051. return VideoTexture;
  64052. }(BABYLON.Texture));
  64053. BABYLON.VideoTexture = VideoTexture;
  64054. })(BABYLON || (BABYLON = {}));
  64055. //# sourceMappingURL=babylon.videoTexture.js.map
  64056. var BABYLON;
  64057. (function (BABYLON) {
  64058. var RawTexture = /** @class */ (function (_super) {
  64059. __extends(RawTexture, _super);
  64060. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64061. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64062. if (invertY === void 0) { invertY = false; }
  64063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64064. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64065. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64066. _this.format = format;
  64067. _this._engine = scene.getEngine();
  64068. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64069. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64070. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64071. return _this;
  64072. }
  64073. RawTexture.prototype.update = function (data) {
  64074. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64075. };
  64076. // Statics
  64077. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64078. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64079. if (invertY === void 0) { invertY = false; }
  64080. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64081. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64082. };
  64083. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64084. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64085. if (invertY === void 0) { invertY = false; }
  64086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64087. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64088. };
  64089. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64090. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64091. if (invertY === void 0) { invertY = false; }
  64092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64093. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64094. };
  64095. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64096. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64097. if (invertY === void 0) { invertY = false; }
  64098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64099. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64100. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64101. };
  64102. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64103. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64104. if (invertY === void 0) { invertY = false; }
  64105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64106. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64107. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64108. };
  64109. return RawTexture;
  64110. }(BABYLON.Texture));
  64111. BABYLON.RawTexture = RawTexture;
  64112. })(BABYLON || (BABYLON = {}));
  64113. //# sourceMappingURL=babylon.rawTexture.js.map
  64114. var BABYLON;
  64115. (function (BABYLON) {
  64116. /**
  64117. * Class used to store 3D textures containing user data
  64118. */
  64119. var RawTexture3D = /** @class */ (function (_super) {
  64120. __extends(RawTexture3D, _super);
  64121. /**
  64122. * Create a new RawTexture3D
  64123. * @param data defines the data of the texture
  64124. * @param width defines the width of the texture
  64125. * @param height defines the height of the texture
  64126. * @param depth defines the depth of the texture
  64127. * @param format defines the texture format to use
  64128. * @param scene defines the hosting scene
  64129. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64130. * @param invertY defines if texture must be stored with Y axis inverted
  64131. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64132. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64133. */
  64134. function RawTexture3D(data, width, height, depth,
  64135. /** Gets or sets the texture format to use */
  64136. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64137. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64138. if (invertY === void 0) { invertY = false; }
  64139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64140. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64141. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64142. _this.format = format;
  64143. _this._engine = scene.getEngine();
  64144. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64145. _this.is3D = true;
  64146. return _this;
  64147. }
  64148. /**
  64149. * Update the texture with new data
  64150. * @param data defines the data to store in the texture
  64151. */
  64152. RawTexture3D.prototype.update = function (data) {
  64153. if (!this._texture) {
  64154. return;
  64155. }
  64156. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64157. };
  64158. return RawTexture3D;
  64159. }(BABYLON.Texture));
  64160. BABYLON.RawTexture3D = RawTexture3D;
  64161. })(BABYLON || (BABYLON = {}));
  64162. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64163. var BABYLON;
  64164. (function (BABYLON) {
  64165. /**
  64166. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64167. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64168. */
  64169. var PostProcessManager = /** @class */ (function () {
  64170. /**
  64171. * Creates a new instance PostProcess
  64172. * @param scene The scene that the post process is associated with.
  64173. */
  64174. function PostProcessManager(scene) {
  64175. this._vertexBuffers = {};
  64176. this._scene = scene;
  64177. }
  64178. PostProcessManager.prototype._prepareBuffers = function () {
  64179. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64180. return;
  64181. }
  64182. // VBO
  64183. var vertices = [];
  64184. vertices.push(1, 1);
  64185. vertices.push(-1, 1);
  64186. vertices.push(-1, -1);
  64187. vertices.push(1, -1);
  64188. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64189. this._buildIndexBuffer();
  64190. };
  64191. PostProcessManager.prototype._buildIndexBuffer = function () {
  64192. // Indices
  64193. var indices = [];
  64194. indices.push(0);
  64195. indices.push(1);
  64196. indices.push(2);
  64197. indices.push(0);
  64198. indices.push(2);
  64199. indices.push(3);
  64200. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64201. };
  64202. /**
  64203. * Rebuilds the vertex buffers of the manager.
  64204. */
  64205. PostProcessManager.prototype._rebuild = function () {
  64206. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64207. if (!vb) {
  64208. return;
  64209. }
  64210. vb._rebuild();
  64211. this._buildIndexBuffer();
  64212. };
  64213. // Methods
  64214. /**
  64215. * Prepares a frame to be run through a post process.
  64216. * @param sourceTexture The input texture to the post procesess. (default: null)
  64217. * @param postProcesses An array of post processes to be run. (default: null)
  64218. * @returns True if the post processes were able to be run.
  64219. */
  64220. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64221. if (sourceTexture === void 0) { sourceTexture = null; }
  64222. if (postProcesses === void 0) { postProcesses = null; }
  64223. var camera = this._scene.activeCamera;
  64224. if (!camera) {
  64225. return false;
  64226. }
  64227. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64228. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64229. return false;
  64230. }
  64231. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64232. return true;
  64233. };
  64234. /**
  64235. * Manually render a set of post processes to a texture.
  64236. * @param postProcesses An array of post processes to be run.
  64237. * @param targetTexture The target texture to render to.
  64238. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64239. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64240. * @param lodLevel defines which lod of the texture to render to
  64241. */
  64242. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64243. if (targetTexture === void 0) { targetTexture = null; }
  64244. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64245. if (faceIndex === void 0) { faceIndex = 0; }
  64246. if (lodLevel === void 0) { lodLevel = 0; }
  64247. var engine = this._scene.getEngine();
  64248. for (var index = 0; index < postProcesses.length; index++) {
  64249. if (index < postProcesses.length - 1) {
  64250. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64251. }
  64252. else {
  64253. if (targetTexture) {
  64254. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64255. }
  64256. else {
  64257. engine.restoreDefaultFramebuffer();
  64258. }
  64259. }
  64260. var pp = postProcesses[index];
  64261. var effect = pp.apply();
  64262. if (effect) {
  64263. pp.onBeforeRenderObservable.notifyObservers(effect);
  64264. // VBOs
  64265. this._prepareBuffers();
  64266. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64267. // Draw order
  64268. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64269. pp.onAfterRenderObservable.notifyObservers(effect);
  64270. }
  64271. }
  64272. // Restore depth buffer
  64273. engine.setDepthBuffer(true);
  64274. engine.setDepthWrite(true);
  64275. };
  64276. /**
  64277. * Finalize the result of the output of the postprocesses.
  64278. * @param doNotPresent If true the result will not be displayed to the screen.
  64279. * @param targetTexture The target texture to render to.
  64280. * @param faceIndex The index of the face to bind the target texture to.
  64281. * @param postProcesses The array of post processes to render.
  64282. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64283. */
  64284. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64285. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64286. var camera = this._scene.activeCamera;
  64287. if (!camera) {
  64288. return;
  64289. }
  64290. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64291. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64292. return;
  64293. }
  64294. var engine = this._scene.getEngine();
  64295. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64296. var pp = postProcesses[index];
  64297. if (index < len - 1) {
  64298. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64299. }
  64300. else {
  64301. if (targetTexture) {
  64302. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64303. pp._outputTexture = targetTexture;
  64304. }
  64305. else {
  64306. engine.restoreDefaultFramebuffer();
  64307. pp._outputTexture = null;
  64308. }
  64309. }
  64310. if (doNotPresent) {
  64311. break;
  64312. }
  64313. var effect = pp.apply();
  64314. if (effect) {
  64315. pp.onBeforeRenderObservable.notifyObservers(effect);
  64316. // VBOs
  64317. this._prepareBuffers();
  64318. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64319. // Draw order
  64320. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64321. pp.onAfterRenderObservable.notifyObservers(effect);
  64322. }
  64323. }
  64324. // Restore states
  64325. engine.setDepthBuffer(true);
  64326. engine.setDepthWrite(true);
  64327. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64328. };
  64329. /**
  64330. * Disposes of the post process manager.
  64331. */
  64332. PostProcessManager.prototype.dispose = function () {
  64333. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64334. if (buffer) {
  64335. buffer.dispose();
  64336. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64337. }
  64338. if (this._indexBuffer) {
  64339. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64340. this._indexBuffer = null;
  64341. }
  64342. };
  64343. return PostProcessManager;
  64344. }());
  64345. BABYLON.PostProcessManager = PostProcessManager;
  64346. })(BABYLON || (BABYLON = {}));
  64347. //# sourceMappingURL=babylon.postProcessManager.js.map
  64348. var BABYLON;
  64349. (function (BABYLON) {
  64350. /**
  64351. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64352. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64353. */
  64354. var PostProcess = /** @class */ (function () {
  64355. /**
  64356. * Creates a new instance PostProcess
  64357. * @param name The name of the PostProcess.
  64358. * @param fragmentUrl The url of the fragment shader to be used.
  64359. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64360. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64361. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64362. * @param camera The camera to apply the render pass to.
  64363. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64364. * @param engine The engine which the post process will be applied. (default: current engine)
  64365. * @param reusable If the post process can be reused on the same frame. (default: false)
  64366. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64367. * @param textureType Type of textures used when performing the post process. (default: 0)
  64368. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64369. * @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
  64370. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64371. */
  64372. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64374. if (defines === void 0) { defines = null; }
  64375. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64376. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64377. if (blockCompilation === void 0) { blockCompilation = false; }
  64378. this.name = name;
  64379. /**
  64380. * Width of the texture to apply the post process on
  64381. */
  64382. this.width = -1;
  64383. /**
  64384. * Height of the texture to apply the post process on
  64385. */
  64386. this.height = -1;
  64387. /**
  64388. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64389. */
  64390. this._outputTexture = null;
  64391. /**
  64392. * If the buffer needs to be cleared before applying the post process. (default: true)
  64393. * Should be set to false if shader will overwrite all previous pixels.
  64394. */
  64395. this.autoClear = true;
  64396. /**
  64397. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64398. */
  64399. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64400. /**
  64401. * Animations to be used for the post processing
  64402. */
  64403. this.animations = new Array();
  64404. /**
  64405. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64406. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64407. */
  64408. this.enablePixelPerfectMode = false;
  64409. /**
  64410. * Force the postprocess to be applied without taking in account viewport
  64411. */
  64412. this.forceFullscreenViewport = true;
  64413. /**
  64414. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64415. *
  64416. * | Value | Type | Description |
  64417. * | ----- | ----------------------------------- | ----------- |
  64418. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  64419. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  64420. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  64421. *
  64422. */
  64423. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64424. /**
  64425. * Force textures to be a power of two (default: false)
  64426. */
  64427. this.alwaysForcePOT = false;
  64428. /**
  64429. * Number of sample textures (default: 1)
  64430. */
  64431. this.samples = 1;
  64432. /**
  64433. * Modify the scale of the post process to be the same as the viewport (default: false)
  64434. */
  64435. this.adaptScaleToCurrentViewport = false;
  64436. this._reusable = false;
  64437. /**
  64438. * Smart array of input and output textures for the post process.
  64439. */
  64440. this._textures = new BABYLON.SmartArray(2);
  64441. /**
  64442. * The index in _textures that corresponds to the output texture.
  64443. */
  64444. this._currentRenderTextureInd = 0;
  64445. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64446. this._texelSize = BABYLON.Vector2.Zero();
  64447. // Events
  64448. /**
  64449. * An event triggered when the postprocess is activated.
  64450. */
  64451. this.onActivateObservable = new BABYLON.Observable();
  64452. /**
  64453. * An event triggered when the postprocess changes its size.
  64454. */
  64455. this.onSizeChangedObservable = new BABYLON.Observable();
  64456. /**
  64457. * An event triggered when the postprocess applies its effect.
  64458. */
  64459. this.onApplyObservable = new BABYLON.Observable();
  64460. /**
  64461. * An event triggered before rendering the postprocess
  64462. */
  64463. this.onBeforeRenderObservable = new BABYLON.Observable();
  64464. /**
  64465. * An event triggered after rendering the postprocess
  64466. */
  64467. this.onAfterRenderObservable = new BABYLON.Observable();
  64468. if (camera != null) {
  64469. this._camera = camera;
  64470. this._scene = camera.getScene();
  64471. camera.attachPostProcess(this);
  64472. this._engine = this._scene.getEngine();
  64473. this._scene.postProcesses.push(this);
  64474. }
  64475. else if (engine) {
  64476. this._engine = engine;
  64477. this._engine.postProcesses.push(this);
  64478. }
  64479. this._options = options;
  64480. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64481. this._reusable = reusable || false;
  64482. this._textureType = textureType;
  64483. this._samplers = samplers || [];
  64484. this._samplers.push("textureSampler");
  64485. this._fragmentUrl = fragmentUrl;
  64486. this._vertexUrl = vertexUrl;
  64487. this._parameters = parameters || [];
  64488. this._parameters.push("scale");
  64489. this._indexParameters = indexParameters;
  64490. if (!blockCompilation) {
  64491. this.updateEffect(defines);
  64492. }
  64493. }
  64494. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64495. /**
  64496. * A function that is added to the onActivateObservable
  64497. */
  64498. set: function (callback) {
  64499. if (this._onActivateObserver) {
  64500. this.onActivateObservable.remove(this._onActivateObserver);
  64501. }
  64502. if (callback) {
  64503. this._onActivateObserver = this.onActivateObservable.add(callback);
  64504. }
  64505. },
  64506. enumerable: true,
  64507. configurable: true
  64508. });
  64509. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64510. /**
  64511. * A function that is added to the onSizeChangedObservable
  64512. */
  64513. set: function (callback) {
  64514. if (this._onSizeChangedObserver) {
  64515. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64516. }
  64517. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64518. },
  64519. enumerable: true,
  64520. configurable: true
  64521. });
  64522. Object.defineProperty(PostProcess.prototype, "onApply", {
  64523. /**
  64524. * A function that is added to the onApplyObservable
  64525. */
  64526. set: function (callback) {
  64527. if (this._onApplyObserver) {
  64528. this.onApplyObservable.remove(this._onApplyObserver);
  64529. }
  64530. this._onApplyObserver = this.onApplyObservable.add(callback);
  64531. },
  64532. enumerable: true,
  64533. configurable: true
  64534. });
  64535. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64536. /**
  64537. * A function that is added to the onBeforeRenderObservable
  64538. */
  64539. set: function (callback) {
  64540. if (this._onBeforeRenderObserver) {
  64541. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64542. }
  64543. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64544. },
  64545. enumerable: true,
  64546. configurable: true
  64547. });
  64548. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64549. /**
  64550. * A function that is added to the onAfterRenderObservable
  64551. */
  64552. set: function (callback) {
  64553. if (this._onAfterRenderObserver) {
  64554. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64555. }
  64556. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64557. },
  64558. enumerable: true,
  64559. configurable: true
  64560. });
  64561. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64562. /**
  64563. * 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
  64564. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64565. */
  64566. get: function () {
  64567. return this._textures.data[this._currentRenderTextureInd];
  64568. },
  64569. set: function (value) {
  64570. this._forcedOutputTexture = value;
  64571. },
  64572. enumerable: true,
  64573. configurable: true
  64574. });
  64575. /**
  64576. * Gets the camera which post process is applied to.
  64577. * @returns The camera the post process is applied to.
  64578. */
  64579. PostProcess.prototype.getCamera = function () {
  64580. return this._camera;
  64581. };
  64582. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64583. /**
  64584. * Gets the texel size of the postprocess.
  64585. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64586. */
  64587. get: function () {
  64588. if (this._shareOutputWithPostProcess) {
  64589. return this._shareOutputWithPostProcess.texelSize;
  64590. }
  64591. if (this._forcedOutputTexture) {
  64592. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64593. }
  64594. return this._texelSize;
  64595. },
  64596. enumerable: true,
  64597. configurable: true
  64598. });
  64599. /**
  64600. * Gets the engine which this post process belongs to.
  64601. * @returns The engine the post process was enabled with.
  64602. */
  64603. PostProcess.prototype.getEngine = function () {
  64604. return this._engine;
  64605. };
  64606. /**
  64607. * The effect that is created when initializing the post process.
  64608. * @returns The created effect corrisponding the the postprocess.
  64609. */
  64610. PostProcess.prototype.getEffect = function () {
  64611. return this._effect;
  64612. };
  64613. /**
  64614. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64615. * @param postProcess The post process to share the output with.
  64616. * @returns This post process.
  64617. */
  64618. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64619. this._disposeTextures();
  64620. this._shareOutputWithPostProcess = postProcess;
  64621. return this;
  64622. };
  64623. /**
  64624. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64625. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64626. */
  64627. PostProcess.prototype.useOwnOutput = function () {
  64628. if (this._textures.length == 0) {
  64629. this._textures = new BABYLON.SmartArray(2);
  64630. }
  64631. this._shareOutputWithPostProcess = null;
  64632. };
  64633. /**
  64634. * Updates the effect with the current post process compile time values and recompiles the shader.
  64635. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64636. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64637. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64638. * @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
  64639. * @param onCompiled Called when the shader has been compiled.
  64640. * @param onError Called if there is an error when compiling a shader.
  64641. */
  64642. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64643. if (defines === void 0) { defines = null; }
  64644. if (uniforms === void 0) { uniforms = null; }
  64645. if (samplers === void 0) { samplers = null; }
  64646. 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);
  64647. };
  64648. /**
  64649. * The post process is reusable if it can be used multiple times within one frame.
  64650. * @returns If the post process is reusable
  64651. */
  64652. PostProcess.prototype.isReusable = function () {
  64653. return this._reusable;
  64654. };
  64655. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64656. PostProcess.prototype.markTextureDirty = function () {
  64657. this.width = -1;
  64658. };
  64659. /**
  64660. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64661. * 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.
  64662. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64663. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64664. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64665. * @returns The target texture that was bound to be written to.
  64666. */
  64667. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64668. var _this = this;
  64669. if (sourceTexture === void 0) { sourceTexture = null; }
  64670. camera = camera || this._camera;
  64671. var scene = camera.getScene();
  64672. var engine = scene.getEngine();
  64673. var maxSize = engine.getCaps().maxTextureSize;
  64674. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64675. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64676. // 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
  64677. var webVRCamera = camera.parent;
  64678. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64679. requiredWidth /= 2;
  64680. }
  64681. var desiredWidth = (this._options.width || requiredWidth);
  64682. var desiredHeight = this._options.height || requiredHeight;
  64683. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64684. if (this.adaptScaleToCurrentViewport) {
  64685. var currentViewport = engine.currentViewport;
  64686. if (currentViewport) {
  64687. desiredWidth *= currentViewport.width;
  64688. desiredHeight *= currentViewport.height;
  64689. }
  64690. }
  64691. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64692. if (!this._options.width) {
  64693. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64694. }
  64695. if (!this._options.height) {
  64696. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64697. }
  64698. }
  64699. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64700. if (this._textures.length > 0) {
  64701. for (var i = 0; i < this._textures.length; i++) {
  64702. this._engine._releaseTexture(this._textures.data[i]);
  64703. }
  64704. this._textures.reset();
  64705. }
  64706. this.width = desiredWidth;
  64707. this.height = desiredHeight;
  64708. var textureSize = { width: this.width, height: this.height };
  64709. var textureOptions = {
  64710. generateMipMaps: false,
  64711. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64712. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64713. samplingMode: this.renderTargetSamplingMode,
  64714. type: this._textureType
  64715. };
  64716. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64717. if (this._reusable) {
  64718. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64719. }
  64720. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64721. this.onSizeChangedObservable.notifyObservers(this);
  64722. }
  64723. this._textures.forEach(function (texture) {
  64724. if (texture.samples !== _this.samples) {
  64725. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64726. }
  64727. });
  64728. }
  64729. var target;
  64730. if (this._shareOutputWithPostProcess) {
  64731. target = this._shareOutputWithPostProcess.inputTexture;
  64732. }
  64733. else if (this._forcedOutputTexture) {
  64734. target = this._forcedOutputTexture;
  64735. this.width = this._forcedOutputTexture.width;
  64736. this.height = this._forcedOutputTexture.height;
  64737. }
  64738. else {
  64739. target = this.inputTexture;
  64740. }
  64741. // Bind the input of this post process to be used as the output of the previous post process.
  64742. if (this.enablePixelPerfectMode) {
  64743. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64744. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  64745. }
  64746. else {
  64747. this._scaleRatio.copyFromFloats(1, 1);
  64748. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  64749. }
  64750. this.onActivateObservable.notifyObservers(camera);
  64751. // Clear
  64752. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64753. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64754. }
  64755. if (this._reusable) {
  64756. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64757. }
  64758. return target;
  64759. };
  64760. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64761. /**
  64762. * If the post process is supported.
  64763. */
  64764. get: function () {
  64765. return this._effect.isSupported;
  64766. },
  64767. enumerable: true,
  64768. configurable: true
  64769. });
  64770. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64771. /**
  64772. * The aspect ratio of the output texture.
  64773. */
  64774. get: function () {
  64775. if (this._shareOutputWithPostProcess) {
  64776. return this._shareOutputWithPostProcess.aspectRatio;
  64777. }
  64778. if (this._forcedOutputTexture) {
  64779. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64780. }
  64781. return this.width / this.height;
  64782. },
  64783. enumerable: true,
  64784. configurable: true
  64785. });
  64786. /**
  64787. * Get a value indicating if the post-process is ready to be used
  64788. * @returns true if the post-process is ready (shader is compiled)
  64789. */
  64790. PostProcess.prototype.isReady = function () {
  64791. return this._effect && this._effect.isReady();
  64792. };
  64793. /**
  64794. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64795. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64796. */
  64797. PostProcess.prototype.apply = function () {
  64798. // Check
  64799. if (!this._effect || !this._effect.isReady())
  64800. return null;
  64801. // States
  64802. this._engine.enableEffect(this._effect);
  64803. this._engine.setState(false);
  64804. this._engine.setDepthBuffer(false);
  64805. this._engine.setDepthWrite(false);
  64806. // Alpha
  64807. this._engine.setAlphaMode(this.alphaMode);
  64808. if (this.alphaConstants) {
  64809. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64810. }
  64811. // Bind the output texture of the preivous post process as the input to this post process.
  64812. var source;
  64813. if (this._shareOutputWithPostProcess) {
  64814. source = this._shareOutputWithPostProcess.inputTexture;
  64815. }
  64816. else if (this._forcedOutputTexture) {
  64817. source = this._forcedOutputTexture;
  64818. }
  64819. else {
  64820. source = this.inputTexture;
  64821. }
  64822. this._effect._bindTexture("textureSampler", source);
  64823. // Parameters
  64824. this._effect.setVector2("scale", this._scaleRatio);
  64825. this.onApplyObservable.notifyObservers(this._effect);
  64826. return this._effect;
  64827. };
  64828. PostProcess.prototype._disposeTextures = function () {
  64829. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64830. return;
  64831. }
  64832. if (this._textures.length > 0) {
  64833. for (var i = 0; i < this._textures.length; i++) {
  64834. this._engine._releaseTexture(this._textures.data[i]);
  64835. }
  64836. }
  64837. this._textures.dispose();
  64838. };
  64839. /**
  64840. * Disposes the post process.
  64841. * @param camera The camera to dispose the post process on.
  64842. */
  64843. PostProcess.prototype.dispose = function (camera) {
  64844. camera = camera || this._camera;
  64845. this._disposeTextures();
  64846. if (this._scene) {
  64847. var index_1 = this._scene.postProcesses.indexOf(this);
  64848. if (index_1 !== -1) {
  64849. this._scene.postProcesses.splice(index_1, 1);
  64850. }
  64851. }
  64852. else {
  64853. var index_2 = this._engine.postProcesses.indexOf(this);
  64854. if (index_2 !== -1) {
  64855. this._engine.postProcesses.splice(index_2, 1);
  64856. }
  64857. }
  64858. if (!camera) {
  64859. return;
  64860. }
  64861. camera.detachPostProcess(this);
  64862. var index = camera._postProcesses.indexOf(this);
  64863. if (index === 0 && camera._postProcesses.length > 0) {
  64864. var firstPostProcess = this._camera._getFirstPostProcess();
  64865. if (firstPostProcess) {
  64866. firstPostProcess.markTextureDirty();
  64867. }
  64868. }
  64869. this.onActivateObservable.clear();
  64870. this.onAfterRenderObservable.clear();
  64871. this.onApplyObservable.clear();
  64872. this.onBeforeRenderObservable.clear();
  64873. this.onSizeChangedObservable.clear();
  64874. };
  64875. return PostProcess;
  64876. }());
  64877. BABYLON.PostProcess = PostProcess;
  64878. })(BABYLON || (BABYLON = {}));
  64879. //# sourceMappingURL=babylon.postProcess.js.map
  64880. var BABYLON;
  64881. (function (BABYLON) {
  64882. var PassPostProcess = /** @class */ (function (_super) {
  64883. __extends(PassPostProcess, _super);
  64884. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64885. if (camera === void 0) { camera = null; }
  64886. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64887. if (blockCompilation === void 0) { blockCompilation = false; }
  64888. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64889. }
  64890. return PassPostProcess;
  64891. }(BABYLON.PostProcess));
  64892. BABYLON.PassPostProcess = PassPostProcess;
  64893. })(BABYLON || (BABYLON = {}));
  64894. //# sourceMappingURL=babylon.passPostProcess.js.map
  64895. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64896. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64897. s = arguments[i];
  64898. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64899. t[p] = s[p];
  64900. }
  64901. return t;
  64902. };
  64903. var BABYLON;
  64904. (function (BABYLON) {
  64905. /**
  64906. * Default implementation IShadowGenerator.
  64907. * This is the main object responsible of generating shadows in the framework.
  64908. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64909. */
  64910. var ShadowGenerator = /** @class */ (function () {
  64911. /**
  64912. * Creates a ShadowGenerator object.
  64913. * A ShadowGenerator is the required tool to use the shadows.
  64914. * Each light casting shadows needs to use its own ShadowGenerator.
  64915. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64916. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64917. * @param light The light object generating the shadows.
  64918. * @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.
  64919. */
  64920. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64921. this._bias = 0.00005;
  64922. this._normalBias = 0;
  64923. this._blurBoxOffset = 1;
  64924. this._blurScale = 2;
  64925. this._blurKernel = 1;
  64926. this._useKernelBlur = false;
  64927. this._filter = ShadowGenerator.FILTER_NONE;
  64928. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64929. this._contactHardeningLightSizeUVRatio = 0.1;
  64930. this._darkness = 0;
  64931. this._transparencyShadow = false;
  64932. /**
  64933. * Controls the extent to which the shadows fade out at the edge of the frustum
  64934. * Used only by directionals and spots
  64935. */
  64936. this.frustumEdgeFalloff = 0;
  64937. /**
  64938. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64939. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64940. * It might on the other hand introduce peter panning.
  64941. */
  64942. this.forceBackFacesOnly = false;
  64943. this._lightDirection = BABYLON.Vector3.Zero();
  64944. this._viewMatrix = BABYLON.Matrix.Zero();
  64945. this._projectionMatrix = BABYLON.Matrix.Zero();
  64946. this._transformMatrix = BABYLON.Matrix.Zero();
  64947. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64948. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64949. this._currentFaceIndex = 0;
  64950. this._currentFaceIndexCache = 0;
  64951. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64952. this._mapSize = mapSize;
  64953. this._light = light;
  64954. this._scene = light.getScene();
  64955. light._shadowGenerator = this;
  64956. // Texture type fallback from float to int if not supported.
  64957. var caps = this._scene.getEngine().getCaps();
  64958. if (!useFullFloatFirst) {
  64959. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64960. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64961. }
  64962. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64963. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64964. }
  64965. else {
  64966. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64967. }
  64968. }
  64969. else {
  64970. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64971. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64972. }
  64973. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64974. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64975. }
  64976. else {
  64977. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64978. }
  64979. }
  64980. this._initializeGenerator();
  64981. this._applyFilterValues();
  64982. }
  64983. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64984. /**
  64985. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64986. */
  64987. get: function () {
  64988. return this._bias;
  64989. },
  64990. /**
  64991. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64992. */
  64993. set: function (bias) {
  64994. this._bias = bias;
  64995. },
  64996. enumerable: true,
  64997. configurable: true
  64998. });
  64999. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65000. /**
  65001. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65002. */
  65003. get: function () {
  65004. return this._normalBias;
  65005. },
  65006. /**
  65007. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65008. */
  65009. set: function (normalBias) {
  65010. this._normalBias = normalBias;
  65011. },
  65012. enumerable: true,
  65013. configurable: true
  65014. });
  65015. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65016. /**
  65017. * Gets the blur box offset: offset applied during the blur pass.
  65018. * Only usefull if useKernelBlur = false
  65019. */
  65020. get: function () {
  65021. return this._blurBoxOffset;
  65022. },
  65023. /**
  65024. * Sets the blur box offset: offset applied during the blur pass.
  65025. * Only usefull if useKernelBlur = false
  65026. */
  65027. set: function (value) {
  65028. if (this._blurBoxOffset === value) {
  65029. return;
  65030. }
  65031. this._blurBoxOffset = value;
  65032. this._disposeBlurPostProcesses();
  65033. },
  65034. enumerable: true,
  65035. configurable: true
  65036. });
  65037. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65038. /**
  65039. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65040. * 2 means half of the size.
  65041. */
  65042. get: function () {
  65043. return this._blurScale;
  65044. },
  65045. /**
  65046. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65047. * 2 means half of the size.
  65048. */
  65049. set: function (value) {
  65050. if (this._blurScale === value) {
  65051. return;
  65052. }
  65053. this._blurScale = value;
  65054. this._disposeBlurPostProcesses();
  65055. },
  65056. enumerable: true,
  65057. configurable: true
  65058. });
  65059. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65060. /**
  65061. * Gets the blur kernel: kernel size of the blur pass.
  65062. * Only usefull if useKernelBlur = true
  65063. */
  65064. get: function () {
  65065. return this._blurKernel;
  65066. },
  65067. /**
  65068. * Sets the blur kernel: kernel size of the blur pass.
  65069. * Only usefull if useKernelBlur = true
  65070. */
  65071. set: function (value) {
  65072. if (this._blurKernel === value) {
  65073. return;
  65074. }
  65075. this._blurKernel = value;
  65076. this._disposeBlurPostProcesses();
  65077. },
  65078. enumerable: true,
  65079. configurable: true
  65080. });
  65081. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65082. /**
  65083. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65084. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65085. */
  65086. get: function () {
  65087. return this._useKernelBlur;
  65088. },
  65089. /**
  65090. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65091. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65092. */
  65093. set: function (value) {
  65094. if (this._useKernelBlur === value) {
  65095. return;
  65096. }
  65097. this._useKernelBlur = value;
  65098. this._disposeBlurPostProcesses();
  65099. },
  65100. enumerable: true,
  65101. configurable: true
  65102. });
  65103. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65104. /**
  65105. * Gets the depth scale used in ESM mode.
  65106. */
  65107. get: function () {
  65108. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65109. },
  65110. /**
  65111. * Sets the depth scale used in ESM mode.
  65112. * This can override the scale stored on the light.
  65113. */
  65114. set: function (value) {
  65115. this._depthScale = value;
  65116. },
  65117. enumerable: true,
  65118. configurable: true
  65119. });
  65120. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65121. /**
  65122. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65123. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65124. */
  65125. get: function () {
  65126. return this._filter;
  65127. },
  65128. /**
  65129. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65130. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65131. */
  65132. set: function (value) {
  65133. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65134. if (this._light.needCube()) {
  65135. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65136. this.useExponentialShadowMap = true;
  65137. return;
  65138. }
  65139. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65140. this.useCloseExponentialShadowMap = true;
  65141. return;
  65142. }
  65143. // PCF on cubemap would also be expensive
  65144. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65145. this.usePoissonSampling = true;
  65146. return;
  65147. }
  65148. }
  65149. // Weblg1 fallback for PCF.
  65150. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65151. if (this._scene.getEngine().webGLVersion === 1) {
  65152. this.usePoissonSampling = true;
  65153. return;
  65154. }
  65155. }
  65156. if (this._filter === value) {
  65157. return;
  65158. }
  65159. this._filter = value;
  65160. this._disposeBlurPostProcesses();
  65161. this._applyFilterValues();
  65162. this._light._markMeshesAsLightDirty();
  65163. },
  65164. enumerable: true,
  65165. configurable: true
  65166. });
  65167. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65168. /**
  65169. * Gets if the current filter is set to Poisson Sampling.
  65170. */
  65171. get: function () {
  65172. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65173. },
  65174. /**
  65175. * Sets the current filter to Poisson Sampling.
  65176. */
  65177. set: function (value) {
  65178. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65179. return;
  65180. }
  65181. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65182. },
  65183. enumerable: true,
  65184. configurable: true
  65185. });
  65186. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65187. /**
  65188. * Gets if the current filter is set to VSM.
  65189. * DEPRECATED. Should use useExponentialShadowMap instead.
  65190. */
  65191. get: function () {
  65192. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65193. return this.useExponentialShadowMap;
  65194. },
  65195. /**
  65196. * Sets the current filter is to VSM.
  65197. * DEPRECATED. Should use useExponentialShadowMap instead.
  65198. */
  65199. set: function (value) {
  65200. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65201. this.useExponentialShadowMap = value;
  65202. },
  65203. enumerable: true,
  65204. configurable: true
  65205. });
  65206. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65207. /**
  65208. * Gets if the current filter is set to blurred VSM.
  65209. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65210. */
  65211. get: function () {
  65212. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65213. return this.useBlurExponentialShadowMap;
  65214. },
  65215. /**
  65216. * Sets the current filter is to blurred VSM.
  65217. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65218. */
  65219. set: function (value) {
  65220. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65221. this.useBlurExponentialShadowMap = value;
  65222. },
  65223. enumerable: true,
  65224. configurable: true
  65225. });
  65226. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65227. /**
  65228. * Gets if the current filter is set to ESM.
  65229. */
  65230. get: function () {
  65231. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65232. },
  65233. /**
  65234. * Sets the current filter is to ESM.
  65235. */
  65236. set: function (value) {
  65237. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65238. return;
  65239. }
  65240. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65241. },
  65242. enumerable: true,
  65243. configurable: true
  65244. });
  65245. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65246. /**
  65247. * Gets if the current filter is set to filtered ESM.
  65248. */
  65249. get: function () {
  65250. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65251. },
  65252. /**
  65253. * Gets if the current filter is set to filtered ESM.
  65254. */
  65255. set: function (value) {
  65256. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65257. return;
  65258. }
  65259. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65260. },
  65261. enumerable: true,
  65262. configurable: true
  65263. });
  65264. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65265. /**
  65266. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65267. * exponential to prevent steep falloff artifacts).
  65268. */
  65269. get: function () {
  65270. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65271. },
  65272. /**
  65273. * Sets the current filter to "close ESM" (using the inverse of the
  65274. * exponential to prevent steep falloff artifacts).
  65275. */
  65276. set: function (value) {
  65277. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65278. return;
  65279. }
  65280. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65281. },
  65282. enumerable: true,
  65283. configurable: true
  65284. });
  65285. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65286. /**
  65287. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65288. * exponential to prevent steep falloff artifacts).
  65289. */
  65290. get: function () {
  65291. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65292. },
  65293. /**
  65294. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65295. * exponential to prevent steep falloff artifacts).
  65296. */
  65297. set: function (value) {
  65298. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65299. return;
  65300. }
  65301. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65302. },
  65303. enumerable: true,
  65304. configurable: true
  65305. });
  65306. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65307. /**
  65308. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65309. */
  65310. get: function () {
  65311. return this.filter === ShadowGenerator.FILTER_PCF;
  65312. },
  65313. /**
  65314. * Sets the current filter to "PCF" (percentage closer filtering).
  65315. */
  65316. set: function (value) {
  65317. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65318. return;
  65319. }
  65320. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65321. },
  65322. enumerable: true,
  65323. configurable: true
  65324. });
  65325. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65326. /**
  65327. * Gets the PCF or PCSS Quality.
  65328. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65329. */
  65330. get: function () {
  65331. return this._filteringQuality;
  65332. },
  65333. /**
  65334. * Sets the PCF or PCSS Quality.
  65335. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65336. */
  65337. set: function (filteringQuality) {
  65338. this._filteringQuality = filteringQuality;
  65339. },
  65340. enumerable: true,
  65341. configurable: true
  65342. });
  65343. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65344. /**
  65345. * Gets if the current filter is set to "PCSS" (contact hardening).
  65346. */
  65347. get: function () {
  65348. return this.filter === ShadowGenerator.FILTER_PCSS;
  65349. },
  65350. /**
  65351. * Sets the current filter to "PCSS" (contact hardening).
  65352. */
  65353. set: function (value) {
  65354. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65355. return;
  65356. }
  65357. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65358. },
  65359. enumerable: true,
  65360. configurable: true
  65361. });
  65362. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65363. /**
  65364. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65365. * Using a ratio helps keeping shape stability independently of the map size.
  65366. *
  65367. * It does not account for the light projection as it was having too much
  65368. * instability during the light setup or during light position changes.
  65369. *
  65370. * Only valid if useContactHardeningShadow is true.
  65371. */
  65372. get: function () {
  65373. return this._contactHardeningLightSizeUVRatio;
  65374. },
  65375. /**
  65376. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65377. * Using a ratio helps keeping shape stability independently of the map size.
  65378. *
  65379. * It does not account for the light projection as it was having too much
  65380. * instability during the light setup or during light position changes.
  65381. *
  65382. * Only valid if useContactHardeningShadow is true.
  65383. */
  65384. set: function (contactHardeningLightSizeUVRatio) {
  65385. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65386. },
  65387. enumerable: true,
  65388. configurable: true
  65389. });
  65390. /**
  65391. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65392. * 0 means strongest and 1 would means no shadow.
  65393. * @returns the darkness.
  65394. */
  65395. ShadowGenerator.prototype.getDarkness = function () {
  65396. return this._darkness;
  65397. };
  65398. /**
  65399. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65400. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65401. * @returns the shadow generator allowing fluent coding.
  65402. */
  65403. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65404. if (darkness >= 1.0)
  65405. this._darkness = 1.0;
  65406. else if (darkness <= 0.0)
  65407. this._darkness = 0.0;
  65408. else
  65409. this._darkness = darkness;
  65410. return this;
  65411. };
  65412. /**
  65413. * Sets the ability to have transparent shadow (boolean).
  65414. * @param transparent True if transparent else False
  65415. * @returns the shadow generator allowing fluent coding
  65416. */
  65417. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65418. this._transparencyShadow = transparent;
  65419. return this;
  65420. };
  65421. /**
  65422. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65423. * @returns The render target texture if present otherwise, null
  65424. */
  65425. ShadowGenerator.prototype.getShadowMap = function () {
  65426. return this._shadowMap;
  65427. };
  65428. /**
  65429. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65430. * @returns The render target texture if the shadow map is present otherwise, null
  65431. */
  65432. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65433. if (this._shadowMap2) {
  65434. return this._shadowMap2;
  65435. }
  65436. return this._shadowMap;
  65437. };
  65438. /**
  65439. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65440. * @param mesh Mesh to add
  65441. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65442. * @returns the Shadow Generator itself
  65443. */
  65444. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65445. if (includeDescendants === void 0) { includeDescendants = true; }
  65446. if (!this._shadowMap) {
  65447. return this;
  65448. }
  65449. if (!this._shadowMap.renderList) {
  65450. this._shadowMap.renderList = [];
  65451. }
  65452. this._shadowMap.renderList.push(mesh);
  65453. if (includeDescendants) {
  65454. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65455. }
  65456. return this;
  65457. var _a;
  65458. };
  65459. /**
  65460. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65461. * @param mesh Mesh to remove
  65462. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65463. * @returns the Shadow Generator itself
  65464. */
  65465. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65466. if (includeDescendants === void 0) { includeDescendants = true; }
  65467. if (!this._shadowMap || !this._shadowMap.renderList) {
  65468. return this;
  65469. }
  65470. var index = this._shadowMap.renderList.indexOf(mesh);
  65471. if (index !== -1) {
  65472. this._shadowMap.renderList.splice(index, 1);
  65473. }
  65474. if (includeDescendants) {
  65475. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65476. var child = _a[_i];
  65477. this.removeShadowCaster(child);
  65478. }
  65479. }
  65480. return this;
  65481. };
  65482. /**
  65483. * Returns the associated light object.
  65484. * @returns the light generating the shadow
  65485. */
  65486. ShadowGenerator.prototype.getLight = function () {
  65487. return this._light;
  65488. };
  65489. ShadowGenerator.prototype._initializeGenerator = function () {
  65490. this._light._markMeshesAsLightDirty();
  65491. this._initializeShadowMap();
  65492. };
  65493. ShadowGenerator.prototype._initializeShadowMap = function () {
  65494. var _this = this;
  65495. // Render target
  65496. var engine = this._scene.getEngine();
  65497. if (engine.webGLVersion > 1) {
  65498. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65499. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65500. }
  65501. else {
  65502. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65503. }
  65504. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65505. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65506. this._shadowMap.anisotropicFilteringLevel = 1;
  65507. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65508. this._shadowMap.renderParticles = false;
  65509. this._shadowMap.ignoreCameraViewport = true;
  65510. // Record Face Index before render.
  65511. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65512. _this._currentFaceIndex = faceIndex;
  65513. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65514. engine.setColorWrite(false);
  65515. }
  65516. });
  65517. // Custom render function.
  65518. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65519. // Blur if required afer render.
  65520. this._shadowMap.onAfterUnbindObservable.add(function () {
  65521. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65522. engine.setColorWrite(true);
  65523. }
  65524. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65525. return;
  65526. }
  65527. var shadowMap = _this.getShadowMapForRendering();
  65528. if (shadowMap) {
  65529. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65530. }
  65531. });
  65532. // Clear according to the chosen filter.
  65533. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65534. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65535. this._shadowMap.onClearObservable.add(function (engine) {
  65536. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65537. engine.clear(clearOne, false, true, false);
  65538. }
  65539. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65540. engine.clear(clearZero, true, true, false);
  65541. }
  65542. else {
  65543. engine.clear(clearOne, true, true, false);
  65544. }
  65545. });
  65546. };
  65547. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65548. var _this = this;
  65549. var engine = this._scene.getEngine();
  65550. var targetSize = this._mapSize / this.blurScale;
  65551. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65552. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65553. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65554. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65555. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65556. }
  65557. if (this.useKernelBlur) {
  65558. 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);
  65559. this._kernelBlurXPostprocess.width = targetSize;
  65560. this._kernelBlurXPostprocess.height = targetSize;
  65561. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65562. effect.setTexture("textureSampler", _this._shadowMap);
  65563. });
  65564. 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);
  65565. this._kernelBlurXPostprocess.autoClear = false;
  65566. this._kernelBlurYPostprocess.autoClear = false;
  65567. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65568. this._kernelBlurXPostprocess.packedFloat = true;
  65569. this._kernelBlurYPostprocess.packedFloat = true;
  65570. }
  65571. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65572. }
  65573. else {
  65574. 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);
  65575. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65576. effect.setFloat2("screenSize", targetSize, targetSize);
  65577. effect.setTexture("textureSampler", _this._shadowMap);
  65578. });
  65579. this._boxBlurPostprocess.autoClear = false;
  65580. this._blurPostProcesses = [this._boxBlurPostprocess];
  65581. }
  65582. };
  65583. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65584. var index;
  65585. var engine = this._scene.getEngine();
  65586. if (depthOnlySubMeshes.length) {
  65587. engine.setColorWrite(false);
  65588. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65589. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65590. }
  65591. engine.setColorWrite(true);
  65592. }
  65593. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65594. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65595. }
  65596. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65597. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65598. }
  65599. if (this._transparencyShadow) {
  65600. for (index = 0; index < transparentSubMeshes.length; index++) {
  65601. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65602. }
  65603. }
  65604. };
  65605. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65606. var _this = this;
  65607. var mesh = subMesh.getRenderingMesh();
  65608. var scene = this._scene;
  65609. var engine = scene.getEngine();
  65610. var material = subMesh.getMaterial();
  65611. if (!material) {
  65612. return;
  65613. }
  65614. // Culling
  65615. engine.setState(material.backFaceCulling);
  65616. // Managing instances
  65617. var batch = mesh._getInstancesRenderList(subMesh._id);
  65618. if (batch.mustReturn) {
  65619. return;
  65620. }
  65621. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65622. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65623. engine.enableEffect(this._effect);
  65624. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65625. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65626. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65627. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65628. this._effect.setVector3("lightData", this._cachedDirection);
  65629. }
  65630. else {
  65631. this._effect.setVector3("lightData", this._cachedPosition);
  65632. }
  65633. if (scene.activeCamera) {
  65634. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65635. }
  65636. // Alpha test
  65637. if (material && material.needAlphaTesting()) {
  65638. var alphaTexture = material.getAlphaTestTexture();
  65639. if (alphaTexture) {
  65640. this._effect.setTexture("diffuseSampler", alphaTexture);
  65641. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65642. }
  65643. }
  65644. // Bones
  65645. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65646. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65647. }
  65648. // Morph targets
  65649. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65650. if (this.forceBackFacesOnly) {
  65651. engine.setState(true, 0, false, true);
  65652. }
  65653. // Draw
  65654. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65655. if (this.forceBackFacesOnly) {
  65656. engine.setState(true, 0, false, false);
  65657. }
  65658. }
  65659. else {
  65660. // Need to reset refresh rate of the shadowMap
  65661. if (this._shadowMap) {
  65662. this._shadowMap.resetRefreshCounter();
  65663. }
  65664. }
  65665. };
  65666. ShadowGenerator.prototype._applyFilterValues = function () {
  65667. if (!this._shadowMap) {
  65668. return;
  65669. }
  65670. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65671. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65672. }
  65673. else {
  65674. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65675. }
  65676. };
  65677. /**
  65678. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65679. * @param onCompiled Callback triggered at the and of the effects compilation
  65680. * @param options Sets of optional options forcing the compilation with different modes
  65681. */
  65682. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65683. var _this = this;
  65684. var localOptions = __assign({ useInstances: false }, options);
  65685. var shadowMap = this.getShadowMap();
  65686. if (!shadowMap) {
  65687. if (onCompiled) {
  65688. onCompiled(this);
  65689. }
  65690. return;
  65691. }
  65692. var renderList = shadowMap.renderList;
  65693. if (!renderList) {
  65694. if (onCompiled) {
  65695. onCompiled(this);
  65696. }
  65697. return;
  65698. }
  65699. var subMeshes = new Array();
  65700. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65701. var mesh = renderList_1[_i];
  65702. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65703. }
  65704. if (subMeshes.length === 0) {
  65705. if (onCompiled) {
  65706. onCompiled(this);
  65707. }
  65708. return;
  65709. }
  65710. var currentIndex = 0;
  65711. var checkReady = function () {
  65712. if (!_this._scene || !_this._scene.getEngine()) {
  65713. return;
  65714. }
  65715. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65716. currentIndex++;
  65717. if (currentIndex >= subMeshes.length) {
  65718. if (onCompiled) {
  65719. onCompiled(_this);
  65720. }
  65721. return;
  65722. }
  65723. }
  65724. setTimeout(checkReady, 16);
  65725. };
  65726. checkReady();
  65727. };
  65728. /**
  65729. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65730. * @param options Sets of optional options forcing the compilation with different modes
  65731. * @returns A promise that resolves when the compilation completes
  65732. */
  65733. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65734. var _this = this;
  65735. return new Promise(function (resolve) {
  65736. _this.forceCompilation(function () {
  65737. resolve();
  65738. }, options);
  65739. });
  65740. };
  65741. /**
  65742. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65743. * @param subMesh The submesh we want to render in the shadow map
  65744. * @param useInstances Defines wether will draw in the map using instances
  65745. * @returns true if ready otherwise, false
  65746. */
  65747. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65748. var defines = [];
  65749. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65750. defines.push("#define FLOAT");
  65751. }
  65752. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65753. defines.push("#define ESM");
  65754. }
  65755. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65756. defines.push("#define DEPTHTEXTURE");
  65757. }
  65758. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65759. var mesh = subMesh.getMesh();
  65760. var material = subMesh.getMaterial();
  65761. // Normal bias.
  65762. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65763. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65764. defines.push("#define NORMAL");
  65765. if (mesh.nonUniformScaling) {
  65766. defines.push("#define NONUNIFORMSCALING");
  65767. }
  65768. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65769. defines.push("#define DIRECTIONINLIGHTDATA");
  65770. }
  65771. }
  65772. // Alpha test
  65773. if (material && material.needAlphaTesting()) {
  65774. var alphaTexture = material.getAlphaTestTexture();
  65775. if (alphaTexture) {
  65776. defines.push("#define ALPHATEST");
  65777. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65778. attribs.push(BABYLON.VertexBuffer.UVKind);
  65779. defines.push("#define UV1");
  65780. }
  65781. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65782. if (alphaTexture.coordinatesIndex === 1) {
  65783. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65784. defines.push("#define UV2");
  65785. }
  65786. }
  65787. }
  65788. }
  65789. // Bones
  65790. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65791. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65792. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65793. if (mesh.numBoneInfluencers > 4) {
  65794. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65795. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65796. }
  65797. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65798. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65799. }
  65800. else {
  65801. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65802. }
  65803. // Morph targets
  65804. var manager = mesh.morphTargetManager;
  65805. var morphInfluencers = 0;
  65806. if (manager) {
  65807. if (manager.numInfluencers > 0) {
  65808. defines.push("#define MORPHTARGETS");
  65809. morphInfluencers = manager.numInfluencers;
  65810. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65811. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65812. }
  65813. }
  65814. // Instances
  65815. if (useInstances) {
  65816. defines.push("#define INSTANCES");
  65817. attribs.push("world0");
  65818. attribs.push("world1");
  65819. attribs.push("world2");
  65820. attribs.push("world3");
  65821. }
  65822. // Get correct effect
  65823. var join = defines.join("\n");
  65824. if (this._cachedDefines !== join) {
  65825. this._cachedDefines = join;
  65826. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65827. }
  65828. if (!this._effect.isReady()) {
  65829. return false;
  65830. }
  65831. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65832. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65833. this._initializeBlurRTTAndPostProcesses();
  65834. }
  65835. }
  65836. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65837. return false;
  65838. }
  65839. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65840. return false;
  65841. }
  65842. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65843. return false;
  65844. }
  65845. return true;
  65846. };
  65847. /**
  65848. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65849. * @param defines Defines of the material we want to update
  65850. * @param lightIndex Index of the light in the enabled light list of the material
  65851. */
  65852. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65853. var scene = this._scene;
  65854. var light = this._light;
  65855. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65856. return;
  65857. }
  65858. defines["SHADOW" + lightIndex] = true;
  65859. if (this.useContactHardeningShadow) {
  65860. defines["SHADOWPCSS" + lightIndex] = true;
  65861. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65862. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65863. }
  65864. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65865. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65866. }
  65867. // else default to high.
  65868. }
  65869. if (this.usePercentageCloserFiltering) {
  65870. defines["SHADOWPCF" + lightIndex] = true;
  65871. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65872. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65873. }
  65874. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65875. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65876. }
  65877. // else default to high.
  65878. }
  65879. else if (this.usePoissonSampling) {
  65880. defines["SHADOWPOISSON" + lightIndex] = true;
  65881. }
  65882. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65883. defines["SHADOWESM" + lightIndex] = true;
  65884. }
  65885. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65886. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65887. }
  65888. if (light.needCube()) {
  65889. defines["SHADOWCUBE" + lightIndex] = true;
  65890. }
  65891. };
  65892. /**
  65893. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65894. * defined in the generator but impacting the effect).
  65895. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65896. * @param effect The effect we are binfing the information for
  65897. */
  65898. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65899. var light = this._light;
  65900. var scene = this._scene;
  65901. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65902. return;
  65903. }
  65904. var camera = scene.activeCamera;
  65905. if (!camera) {
  65906. return;
  65907. }
  65908. var shadowMap = this.getShadowMap();
  65909. if (!shadowMap) {
  65910. return;
  65911. }
  65912. if (!light.needCube()) {
  65913. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65914. }
  65915. // Only PCF uses depth stencil texture.
  65916. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65917. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65918. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65919. }
  65920. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65921. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65922. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65923. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65924. }
  65925. else {
  65926. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65927. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65928. }
  65929. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65930. };
  65931. /**
  65932. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65933. * (eq to shadow prjection matrix * light transform matrix)
  65934. * @returns The transform matrix used to create the shadow map
  65935. */
  65936. ShadowGenerator.prototype.getTransformMatrix = function () {
  65937. var scene = this._scene;
  65938. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65939. return this._transformMatrix;
  65940. }
  65941. this._currentRenderID = scene.getRenderId();
  65942. this._currentFaceIndexCache = this._currentFaceIndex;
  65943. var lightPosition = this._light.position;
  65944. if (this._light.computeTransformedInformation()) {
  65945. lightPosition = this._light.transformedPosition;
  65946. }
  65947. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65948. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65949. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65950. }
  65951. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65952. this._cachedPosition.copyFrom(lightPosition);
  65953. this._cachedDirection.copyFrom(this._lightDirection);
  65954. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65955. var shadowMap = this.getShadowMap();
  65956. if (shadowMap) {
  65957. var renderList = shadowMap.renderList;
  65958. if (renderList) {
  65959. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65960. }
  65961. }
  65962. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65963. }
  65964. return this._transformMatrix;
  65965. };
  65966. /**
  65967. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65968. * Cube and 2D textures for instance.
  65969. */
  65970. ShadowGenerator.prototype.recreateShadowMap = function () {
  65971. var shadowMap = this._shadowMap;
  65972. if (!shadowMap) {
  65973. return;
  65974. }
  65975. // Track render list.
  65976. var renderList = shadowMap.renderList;
  65977. // Clean up existing data.
  65978. this._disposeRTTandPostProcesses();
  65979. // Reinitializes.
  65980. this._initializeGenerator();
  65981. // Reaffect the filter to ensure a correct fallback if necessary.
  65982. this.filter = this.filter;
  65983. // Reaffect the filter.
  65984. this._applyFilterValues();
  65985. // Reaffect Render List.
  65986. this._shadowMap.renderList = renderList;
  65987. };
  65988. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65989. if (this._shadowMap2) {
  65990. this._shadowMap2.dispose();
  65991. this._shadowMap2 = null;
  65992. }
  65993. if (this._boxBlurPostprocess) {
  65994. this._boxBlurPostprocess.dispose();
  65995. this._boxBlurPostprocess = null;
  65996. }
  65997. if (this._kernelBlurXPostprocess) {
  65998. this._kernelBlurXPostprocess.dispose();
  65999. this._kernelBlurXPostprocess = null;
  66000. }
  66001. if (this._kernelBlurYPostprocess) {
  66002. this._kernelBlurYPostprocess.dispose();
  66003. this._kernelBlurYPostprocess = null;
  66004. }
  66005. this._blurPostProcesses = [];
  66006. };
  66007. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66008. if (this._shadowMap) {
  66009. this._shadowMap.dispose();
  66010. this._shadowMap = null;
  66011. }
  66012. this._disposeBlurPostProcesses();
  66013. };
  66014. /**
  66015. * Disposes the ShadowGenerator.
  66016. * Returns nothing.
  66017. */
  66018. ShadowGenerator.prototype.dispose = function () {
  66019. this._disposeRTTandPostProcesses();
  66020. if (this._light) {
  66021. this._light._shadowGenerator = null;
  66022. this._light._markMeshesAsLightDirty();
  66023. }
  66024. };
  66025. /**
  66026. * Serializes the shadow generator setup to a json object.
  66027. * @returns The serialized JSON object
  66028. */
  66029. ShadowGenerator.prototype.serialize = function () {
  66030. var serializationObject = {};
  66031. var shadowMap = this.getShadowMap();
  66032. if (!shadowMap) {
  66033. return serializationObject;
  66034. }
  66035. serializationObject.lightId = this._light.id;
  66036. serializationObject.mapSize = shadowMap.getRenderSize();
  66037. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66038. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66039. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66040. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66041. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66042. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66043. serializationObject.depthScale = this.depthScale;
  66044. serializationObject.darkness = this.getDarkness();
  66045. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66046. serializationObject.blurKernel = this.blurKernel;
  66047. serializationObject.blurScale = this.blurScale;
  66048. serializationObject.useKernelBlur = this.useKernelBlur;
  66049. serializationObject.transparencyShadow = this._transparencyShadow;
  66050. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66051. serializationObject.bias = this.bias;
  66052. serializationObject.normalBias = this.normalBias;
  66053. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66054. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66055. serializationObject.filteringQuality = this.filteringQuality;
  66056. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66057. serializationObject.renderList = [];
  66058. if (shadowMap.renderList) {
  66059. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66060. var mesh = shadowMap.renderList[meshIndex];
  66061. serializationObject.renderList.push(mesh.id);
  66062. }
  66063. }
  66064. return serializationObject;
  66065. };
  66066. /**
  66067. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66068. * @param parsedShadowGenerator The JSON object to parse
  66069. * @param scene The scene to create the shadow map for
  66070. * @returns The parsed shadow generator
  66071. */
  66072. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66073. //casting to point light, as light is missing the position attr and typescript complains.
  66074. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66075. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66076. var shadowMap = shadowGenerator.getShadowMap();
  66077. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66078. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66079. meshes.forEach(function (mesh) {
  66080. if (!shadowMap) {
  66081. return;
  66082. }
  66083. if (!shadowMap.renderList) {
  66084. shadowMap.renderList = [];
  66085. }
  66086. shadowMap.renderList.push(mesh);
  66087. });
  66088. }
  66089. if (parsedShadowGenerator.usePoissonSampling) {
  66090. shadowGenerator.usePoissonSampling = true;
  66091. }
  66092. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66093. shadowGenerator.useExponentialShadowMap = true;
  66094. }
  66095. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66096. shadowGenerator.useBlurExponentialShadowMap = true;
  66097. }
  66098. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66099. shadowGenerator.useCloseExponentialShadowMap = true;
  66100. }
  66101. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66102. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66103. }
  66104. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66105. shadowGenerator.usePercentageCloserFiltering = true;
  66106. }
  66107. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66108. shadowGenerator.useContactHardeningShadow = true;
  66109. }
  66110. if (parsedShadowGenerator.filteringQuality) {
  66111. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66112. }
  66113. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66114. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66115. }
  66116. // Backward compat
  66117. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66118. shadowGenerator.useExponentialShadowMap = true;
  66119. }
  66120. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66121. shadowGenerator.useBlurExponentialShadowMap = true;
  66122. }
  66123. if (parsedShadowGenerator.depthScale) {
  66124. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66125. }
  66126. if (parsedShadowGenerator.blurScale) {
  66127. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66128. }
  66129. if (parsedShadowGenerator.blurBoxOffset) {
  66130. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66131. }
  66132. if (parsedShadowGenerator.useKernelBlur) {
  66133. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66134. }
  66135. if (parsedShadowGenerator.blurKernel) {
  66136. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66137. }
  66138. if (parsedShadowGenerator.bias !== undefined) {
  66139. shadowGenerator.bias = parsedShadowGenerator.bias;
  66140. }
  66141. if (parsedShadowGenerator.normalBias !== undefined) {
  66142. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66143. }
  66144. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66145. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66146. }
  66147. if (parsedShadowGenerator.darkness) {
  66148. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66149. }
  66150. if (parsedShadowGenerator.transparencyShadow) {
  66151. shadowGenerator.setTransparencyShadow(true);
  66152. }
  66153. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66154. return shadowGenerator;
  66155. };
  66156. /**
  66157. * Shadow generator mode None: no filtering applied.
  66158. */
  66159. ShadowGenerator.FILTER_NONE = 0;
  66160. /**
  66161. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66162. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66163. */
  66164. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66165. /**
  66166. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66167. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66168. */
  66169. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66170. /**
  66171. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66172. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66173. */
  66174. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66175. /**
  66176. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66177. * edge artifacts on steep falloff.
  66178. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66179. */
  66180. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66181. /**
  66182. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66183. * edge artifacts on steep falloff.
  66184. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66185. */
  66186. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66187. /**
  66188. * Shadow generator mode PCF: Percentage Closer Filtering
  66189. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66190. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66191. */
  66192. ShadowGenerator.FILTER_PCF = 6;
  66193. /**
  66194. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66195. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66196. * Contact Hardening
  66197. */
  66198. ShadowGenerator.FILTER_PCSS = 7;
  66199. /**
  66200. * Reserved for PCF and PCSS
  66201. * Highest Quality.
  66202. *
  66203. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66204. *
  66205. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66206. */
  66207. ShadowGenerator.QUALITY_HIGH = 0;
  66208. /**
  66209. * Reserved for PCF and PCSS
  66210. * Good tradeoff for quality/perf cross devices
  66211. *
  66212. * Execute PCF on a 3*3 kernel.
  66213. *
  66214. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66215. */
  66216. ShadowGenerator.QUALITY_MEDIUM = 1;
  66217. /**
  66218. * Reserved for PCF and PCSS
  66219. * The lowest quality but the fastest.
  66220. *
  66221. * Execute PCF on a 1*1 kernel.
  66222. *
  66223. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66224. */
  66225. ShadowGenerator.QUALITY_LOW = 2;
  66226. return ShadowGenerator;
  66227. }());
  66228. BABYLON.ShadowGenerator = ShadowGenerator;
  66229. })(BABYLON || (BABYLON = {}));
  66230. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66231. var BABYLON;
  66232. (function (BABYLON) {
  66233. var DefaultLoadingScreen = /** @class */ (function () {
  66234. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66235. if (_loadingText === void 0) { _loadingText = ""; }
  66236. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66237. var _this = this;
  66238. this._renderingCanvas = _renderingCanvas;
  66239. this._loadingText = _loadingText;
  66240. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66241. // Resize
  66242. this._resizeLoadingUI = function () {
  66243. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66244. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66245. if (!_this._loadingDiv) {
  66246. return;
  66247. }
  66248. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66249. _this._loadingDiv.style.left = canvasRect.left + "px";
  66250. _this._loadingDiv.style.top = canvasRect.top + "px";
  66251. _this._loadingDiv.style.width = canvasRect.width + "px";
  66252. _this._loadingDiv.style.height = canvasRect.height + "px";
  66253. };
  66254. }
  66255. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66256. if (this._loadingDiv) {
  66257. // Do not add a loading screen if there is already one
  66258. return;
  66259. }
  66260. this._loadingDiv = document.createElement("div");
  66261. this._loadingDiv.id = "babylonjsLoadingDiv";
  66262. this._loadingDiv.style.opacity = "0";
  66263. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66264. this._loadingDiv.style.pointerEvents = "none";
  66265. // Loading text
  66266. this._loadingTextDiv = document.createElement("div");
  66267. this._loadingTextDiv.style.position = "absolute";
  66268. this._loadingTextDiv.style.left = "0";
  66269. this._loadingTextDiv.style.top = "50%";
  66270. this._loadingTextDiv.style.marginTop = "80px";
  66271. this._loadingTextDiv.style.width = "100%";
  66272. this._loadingTextDiv.style.height = "20px";
  66273. this._loadingTextDiv.style.fontFamily = "Arial";
  66274. this._loadingTextDiv.style.fontSize = "14px";
  66275. this._loadingTextDiv.style.color = "white";
  66276. this._loadingTextDiv.style.textAlign = "center";
  66277. this._loadingTextDiv.innerHTML = "Loading";
  66278. this._loadingDiv.appendChild(this._loadingTextDiv);
  66279. //set the predefined text
  66280. this._loadingTextDiv.innerHTML = this._loadingText;
  66281. // Generating keyframes
  66282. var style = document.createElement('style');
  66283. style.type = 'text/css';
  66284. 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 }";
  66285. style.innerHTML = keyFrames;
  66286. document.getElementsByTagName('head')[0].appendChild(style);
  66287. // Loading img
  66288. var imgBack = new Image();
  66289. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4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ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  66290. imgBack.style.position = "absolute";
  66291. imgBack.style.left = "50%";
  66292. imgBack.style.top = "50%";
  66293. imgBack.style.marginLeft = "-60px";
  66294. imgBack.style.marginTop = "-60px";
  66295. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66296. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66297. imgBack.style.transformOrigin = "50% 50%";
  66298. imgBack.style.webkitTransformOrigin = "50% 50%";
  66299. this._loadingDiv.appendChild(imgBack);
  66300. this._resizeLoadingUI();
  66301. window.addEventListener("resize", this._resizeLoadingUI);
  66302. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66303. document.body.appendChild(this._loadingDiv);
  66304. this._loadingDiv.style.opacity = "1";
  66305. };
  66306. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66307. var _this = this;
  66308. if (!this._loadingDiv) {
  66309. return;
  66310. }
  66311. var onTransitionEnd = function () {
  66312. if (!_this._loadingDiv) {
  66313. return;
  66314. }
  66315. document.body.removeChild(_this._loadingDiv);
  66316. window.removeEventListener("resize", _this._resizeLoadingUI);
  66317. _this._loadingDiv = null;
  66318. };
  66319. this._loadingDiv.style.opacity = "0";
  66320. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66321. };
  66322. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66323. set: function (text) {
  66324. this._loadingText = text;
  66325. if (this._loadingTextDiv) {
  66326. this._loadingTextDiv.innerHTML = this._loadingText;
  66327. }
  66328. },
  66329. enumerable: true,
  66330. configurable: true
  66331. });
  66332. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66333. get: function () {
  66334. return this._loadingDivBackgroundColor;
  66335. },
  66336. set: function (color) {
  66337. this._loadingDivBackgroundColor = color;
  66338. if (!this._loadingDiv) {
  66339. return;
  66340. }
  66341. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66342. },
  66343. enumerable: true,
  66344. configurable: true
  66345. });
  66346. return DefaultLoadingScreen;
  66347. }());
  66348. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66349. })(BABYLON || (BABYLON = {}));
  66350. //# sourceMappingURL=babylon.loadingScreen.js.map
  66351. var BABYLON;
  66352. (function (BABYLON) {
  66353. var SceneLoaderProgressEvent = /** @class */ (function () {
  66354. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66355. this.lengthComputable = lengthComputable;
  66356. this.loaded = loaded;
  66357. this.total = total;
  66358. }
  66359. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66360. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66361. };
  66362. return SceneLoaderProgressEvent;
  66363. }());
  66364. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66365. var SceneLoader = /** @class */ (function () {
  66366. function SceneLoader() {
  66367. }
  66368. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66369. get: function () {
  66370. return 0;
  66371. },
  66372. enumerable: true,
  66373. configurable: true
  66374. });
  66375. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66376. get: function () {
  66377. return 1;
  66378. },
  66379. enumerable: true,
  66380. configurable: true
  66381. });
  66382. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66383. get: function () {
  66384. return 2;
  66385. },
  66386. enumerable: true,
  66387. configurable: true
  66388. });
  66389. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66390. get: function () {
  66391. return 3;
  66392. },
  66393. enumerable: true,
  66394. configurable: true
  66395. });
  66396. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66397. get: function () {
  66398. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66399. },
  66400. set: function (value) {
  66401. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66402. },
  66403. enumerable: true,
  66404. configurable: true
  66405. });
  66406. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66407. get: function () {
  66408. return SceneLoader._ShowLoadingScreen;
  66409. },
  66410. set: function (value) {
  66411. SceneLoader._ShowLoadingScreen = value;
  66412. },
  66413. enumerable: true,
  66414. configurable: true
  66415. });
  66416. Object.defineProperty(SceneLoader, "loggingLevel", {
  66417. get: function () {
  66418. return SceneLoader._loggingLevel;
  66419. },
  66420. set: function (value) {
  66421. SceneLoader._loggingLevel = value;
  66422. },
  66423. enumerable: true,
  66424. configurable: true
  66425. });
  66426. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66427. get: function () {
  66428. return SceneLoader._CleanBoneMatrixWeights;
  66429. },
  66430. set: function (value) {
  66431. SceneLoader._CleanBoneMatrixWeights = value;
  66432. },
  66433. enumerable: true,
  66434. configurable: true
  66435. });
  66436. SceneLoader._getDefaultPlugin = function () {
  66437. return SceneLoader._registeredPlugins[".babylon"];
  66438. };
  66439. SceneLoader._getPluginForExtension = function (extension) {
  66440. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66441. if (registeredPlugin) {
  66442. return registeredPlugin;
  66443. }
  66444. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  66445. return SceneLoader._getDefaultPlugin();
  66446. };
  66447. SceneLoader._getPluginForDirectLoad = function (data) {
  66448. for (var extension in SceneLoader._registeredPlugins) {
  66449. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66450. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66451. return SceneLoader._registeredPlugins[extension];
  66452. }
  66453. }
  66454. return SceneLoader._getDefaultPlugin();
  66455. };
  66456. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66457. if (sceneFilename.name) {
  66458. sceneFilename = sceneFilename.name;
  66459. }
  66460. var queryStringPosition = sceneFilename.indexOf("?");
  66461. if (queryStringPosition !== -1) {
  66462. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66463. }
  66464. var dotPosition = sceneFilename.lastIndexOf(".");
  66465. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66466. return SceneLoader._getPluginForExtension(extension);
  66467. };
  66468. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66469. SceneLoader._getDirectLoad = function (sceneFilename) {
  66470. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66471. return sceneFilename.substr(5);
  66472. }
  66473. return null;
  66474. };
  66475. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66476. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66477. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66478. var plugin;
  66479. if (registeredPlugin.plugin.createPlugin) {
  66480. plugin = registeredPlugin.plugin.createPlugin();
  66481. }
  66482. else {
  66483. plugin = registeredPlugin.plugin;
  66484. }
  66485. var useArrayBuffer = registeredPlugin.isBinary;
  66486. var database;
  66487. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66488. var dataCallback = function (data, responseURL) {
  66489. if (scene.isDisposed) {
  66490. onError("Scene has been disposed");
  66491. return;
  66492. }
  66493. scene.database = database;
  66494. onSuccess(plugin, data, responseURL);
  66495. };
  66496. var request = null;
  66497. var pluginDisposed = false;
  66498. var onDisposeObservable = plugin.onDisposeObservable;
  66499. if (onDisposeObservable) {
  66500. onDisposeObservable.add(function () {
  66501. pluginDisposed = true;
  66502. if (request) {
  66503. request.abort();
  66504. request = null;
  66505. }
  66506. onDispose();
  66507. });
  66508. }
  66509. var manifestChecked = function () {
  66510. if (pluginDisposed) {
  66511. return;
  66512. }
  66513. var url = rootUrl + sceneFilename;
  66514. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66515. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66516. } : undefined, database, useArrayBuffer, function (request, exception) {
  66517. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66518. });
  66519. };
  66520. if (directLoad) {
  66521. dataCallback(directLoad);
  66522. return plugin;
  66523. }
  66524. if (rootUrl.indexOf("file:") === -1) {
  66525. var engine = scene.getEngine();
  66526. var canUseOfflineSupport = engine.enableOfflineSupport;
  66527. if (canUseOfflineSupport) {
  66528. // Also check for exceptions
  66529. var exceptionFound = false;
  66530. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66531. var regex = _a[_i];
  66532. if (regex.test(rootUrl + sceneFilename)) {
  66533. exceptionFound = true;
  66534. break;
  66535. }
  66536. }
  66537. canUseOfflineSupport = !exceptionFound;
  66538. }
  66539. if (canUseOfflineSupport) {
  66540. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66541. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66542. }
  66543. else {
  66544. manifestChecked();
  66545. }
  66546. }
  66547. // Loading file from disk via input file or drag'n'drop
  66548. else {
  66549. var fileOrString = sceneFilename;
  66550. if (fileOrString.name) { // File
  66551. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66552. }
  66553. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66554. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66555. }
  66556. else {
  66557. onError("Unable to find file named " + sceneFilename);
  66558. }
  66559. }
  66560. return plugin;
  66561. };
  66562. // Public functions
  66563. SceneLoader.GetPluginForExtension = function (extension) {
  66564. return SceneLoader._getPluginForExtension(extension).plugin;
  66565. };
  66566. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66567. return !!SceneLoader._registeredPlugins[extension];
  66568. };
  66569. SceneLoader.RegisterPlugin = function (plugin) {
  66570. if (typeof plugin.extensions === "string") {
  66571. var extension = plugin.extensions;
  66572. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66573. plugin: plugin,
  66574. isBinary: false
  66575. };
  66576. }
  66577. else {
  66578. var extensions = plugin.extensions;
  66579. Object.keys(extensions).forEach(function (extension) {
  66580. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66581. plugin: plugin,
  66582. isBinary: extensions[extension].isBinary
  66583. };
  66584. });
  66585. }
  66586. };
  66587. /**
  66588. * Import meshes into a scene
  66589. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66590. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66591. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66592. * @param scene the instance of BABYLON.Scene to append to
  66593. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66594. * @param onProgress a callback with a progress event for each file being loaded
  66595. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66596. * @param pluginExtension the extension used to determine the plugin
  66597. * @returns The loaded plugin
  66598. */
  66599. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66600. if (sceneFilename === void 0) { sceneFilename = ""; }
  66601. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66602. if (onSuccess === void 0) { onSuccess = null; }
  66603. if (onProgress === void 0) { onProgress = null; }
  66604. if (onError === void 0) { onError = null; }
  66605. if (pluginExtension === void 0) { pluginExtension = null; }
  66606. if (!scene) {
  66607. BABYLON.Tools.Error("No scene available to import mesh to");
  66608. return null;
  66609. }
  66610. if (!sceneFilename) {
  66611. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66612. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66613. }
  66614. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66615. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66616. return null;
  66617. }
  66618. var loadingToken = {};
  66619. scene._addPendingData(loadingToken);
  66620. var disposeHandler = function () {
  66621. scene._removePendingData(loadingToken);
  66622. };
  66623. var errorHandler = function (message, exception) {
  66624. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66625. if (onError) {
  66626. onError(scene, errorMessage, exception);
  66627. }
  66628. else {
  66629. BABYLON.Tools.Error(errorMessage);
  66630. // should the exception be thrown?
  66631. }
  66632. disposeHandler();
  66633. };
  66634. var progressHandler = onProgress ? function (event) {
  66635. try {
  66636. onProgress(event);
  66637. }
  66638. catch (e) {
  66639. errorHandler("Error in onProgress callback", e);
  66640. }
  66641. } : undefined;
  66642. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66643. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66644. if (onSuccess) {
  66645. try {
  66646. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66647. }
  66648. catch (e) {
  66649. errorHandler("Error in onSuccess callback", e);
  66650. }
  66651. }
  66652. scene._removePendingData(loadingToken);
  66653. };
  66654. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66655. if (plugin.rewriteRootURL) {
  66656. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66657. }
  66658. if (sceneFilename === "") {
  66659. if (sceneFilename === "") {
  66660. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66661. }
  66662. }
  66663. if (plugin.importMesh) {
  66664. var syncedPlugin = plugin;
  66665. var meshes = new Array();
  66666. var particleSystems = new Array();
  66667. var skeletons = new Array();
  66668. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66669. return;
  66670. }
  66671. scene.loadingPluginName = plugin.name;
  66672. successHandler(meshes, particleSystems, skeletons, []);
  66673. }
  66674. else {
  66675. var asyncedPlugin = plugin;
  66676. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66677. scene.loadingPluginName = plugin.name;
  66678. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66679. }).catch(function (error) {
  66680. errorHandler(error.message, error);
  66681. });
  66682. }
  66683. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66684. };
  66685. /**
  66686. * Import meshes into a scene
  66687. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66688. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66689. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66690. * @param scene the instance of BABYLON.Scene to append to
  66691. * @param onProgress a callback with a progress event for each file being loaded
  66692. * @param pluginExtension the extension used to determine the plugin
  66693. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66694. */
  66695. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66696. if (sceneFilename === void 0) { sceneFilename = ""; }
  66697. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66698. if (onProgress === void 0) { onProgress = null; }
  66699. if (pluginExtension === void 0) { pluginExtension = null; }
  66700. return new Promise(function (resolve, reject) {
  66701. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66702. resolve({
  66703. meshes: meshes,
  66704. particleSystems: particleSystems,
  66705. skeletons: skeletons,
  66706. animationGroups: animationGroups
  66707. });
  66708. }, onProgress, function (scene, message, exception) {
  66709. reject(exception || new Error(message));
  66710. }, pluginExtension);
  66711. });
  66712. };
  66713. /**
  66714. * Load a scene
  66715. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66716. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66717. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66718. * @param onSuccess a callback with the scene when import succeeds
  66719. * @param onProgress a callback with a progress event for each file being loaded
  66720. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66721. * @param pluginExtension the extension used to determine the plugin
  66722. * @returns The loaded plugin
  66723. */
  66724. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66725. if (onSuccess === void 0) { onSuccess = null; }
  66726. if (onProgress === void 0) { onProgress = null; }
  66727. if (onError === void 0) { onError = null; }
  66728. if (pluginExtension === void 0) { pluginExtension = null; }
  66729. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66730. };
  66731. /**
  66732. * Load a scene
  66733. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66734. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66735. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66736. * @param onProgress a callback with a progress event for each file being loaded
  66737. * @param pluginExtension the extension used to determine the plugin
  66738. * @returns The loaded scene
  66739. */
  66740. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66741. if (onProgress === void 0) { onProgress = null; }
  66742. if (pluginExtension === void 0) { pluginExtension = null; }
  66743. return new Promise(function (resolve, reject) {
  66744. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66745. resolve(scene);
  66746. }, onProgress, function (scene, message, exception) {
  66747. reject(exception || new Error(message));
  66748. }, pluginExtension);
  66749. });
  66750. };
  66751. /**
  66752. * Append a scene
  66753. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66754. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66755. * @param scene is the instance of BABYLON.Scene to append to
  66756. * @param onSuccess a callback with the scene when import succeeds
  66757. * @param onProgress a callback with a progress event for each file being loaded
  66758. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66759. * @param pluginExtension the extension used to determine the plugin
  66760. * @returns The loaded plugin
  66761. */
  66762. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66763. if (sceneFilename === void 0) { sceneFilename = ""; }
  66764. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66765. if (onSuccess === void 0) { onSuccess = null; }
  66766. if (onProgress === void 0) { onProgress = null; }
  66767. if (onError === void 0) { onError = null; }
  66768. if (pluginExtension === void 0) { pluginExtension = null; }
  66769. if (!scene) {
  66770. BABYLON.Tools.Error("No scene available to append to");
  66771. return null;
  66772. }
  66773. if (!sceneFilename) {
  66774. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66775. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66776. }
  66777. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66778. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66779. return null;
  66780. }
  66781. if (SceneLoader.ShowLoadingScreen) {
  66782. scene.getEngine().displayLoadingUI();
  66783. }
  66784. var loadingToken = {};
  66785. scene._addPendingData(loadingToken);
  66786. var disposeHandler = function () {
  66787. scene._removePendingData(loadingToken);
  66788. scene.getEngine().hideLoadingUI();
  66789. };
  66790. var errorHandler = function (message, exception) {
  66791. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66792. if (onError) {
  66793. onError(scene, errorMessage, exception);
  66794. }
  66795. else {
  66796. BABYLON.Tools.Error(errorMessage);
  66797. // should the exception be thrown?
  66798. }
  66799. disposeHandler();
  66800. };
  66801. var progressHandler = onProgress ? function (event) {
  66802. try {
  66803. onProgress(event);
  66804. }
  66805. catch (e) {
  66806. errorHandler("Error in onProgress callback", e);
  66807. }
  66808. } : undefined;
  66809. var successHandler = function () {
  66810. if (onSuccess) {
  66811. try {
  66812. onSuccess(scene);
  66813. }
  66814. catch (e) {
  66815. errorHandler("Error in onSuccess callback", e);
  66816. }
  66817. }
  66818. scene._removePendingData(loadingToken);
  66819. };
  66820. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66821. if (sceneFilename === "") {
  66822. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66823. }
  66824. if (plugin.load) {
  66825. var syncedPlugin = plugin;
  66826. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66827. return;
  66828. }
  66829. scene.loadingPluginName = plugin.name;
  66830. successHandler();
  66831. }
  66832. else {
  66833. var asyncedPlugin = plugin;
  66834. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66835. scene.loadingPluginName = plugin.name;
  66836. successHandler();
  66837. }).catch(function (error) {
  66838. errorHandler(error.message, error);
  66839. });
  66840. }
  66841. if (SceneLoader.ShowLoadingScreen) {
  66842. scene.executeWhenReady(function () {
  66843. scene.getEngine().hideLoadingUI();
  66844. });
  66845. }
  66846. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66847. };
  66848. /**
  66849. * Append a scene
  66850. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66851. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66852. * @param scene is the instance of BABYLON.Scene to append to
  66853. * @param onProgress a callback with a progress event for each file being loaded
  66854. * @param pluginExtension the extension used to determine the plugin
  66855. * @returns The given scene
  66856. */
  66857. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66858. if (sceneFilename === void 0) { sceneFilename = ""; }
  66859. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66860. if (onProgress === void 0) { onProgress = null; }
  66861. if (pluginExtension === void 0) { pluginExtension = null; }
  66862. return new Promise(function (resolve, reject) {
  66863. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66864. resolve(scene);
  66865. }, onProgress, function (scene, message, exception) {
  66866. reject(exception || new Error(message));
  66867. }, pluginExtension);
  66868. });
  66869. };
  66870. /**
  66871. * Load a scene into an asset container
  66872. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66873. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66874. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  66875. * @param onSuccess a callback with the scene when import succeeds
  66876. * @param onProgress a callback with a progress event for each file being loaded
  66877. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66878. * @param pluginExtension the extension used to determine the plugin
  66879. * @returns The loaded plugin
  66880. */
  66881. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66882. if (sceneFilename === void 0) { sceneFilename = ""; }
  66883. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66884. if (onSuccess === void 0) { onSuccess = null; }
  66885. if (onProgress === void 0) { onProgress = null; }
  66886. if (onError === void 0) { onError = null; }
  66887. if (pluginExtension === void 0) { pluginExtension = null; }
  66888. if (!scene) {
  66889. BABYLON.Tools.Error("No scene available to load asset container to");
  66890. return null;
  66891. }
  66892. if (!sceneFilename) {
  66893. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  66894. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  66895. }
  66896. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66897. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66898. return null;
  66899. }
  66900. var loadingToken = {};
  66901. scene._addPendingData(loadingToken);
  66902. var disposeHandler = function () {
  66903. scene._removePendingData(loadingToken);
  66904. };
  66905. var errorHandler = function (message, exception) {
  66906. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66907. if (onError) {
  66908. onError(scene, errorMessage, exception);
  66909. }
  66910. else {
  66911. BABYLON.Tools.Error(errorMessage);
  66912. // should the exception be thrown?
  66913. }
  66914. disposeHandler();
  66915. };
  66916. var progressHandler = onProgress ? function (event) {
  66917. try {
  66918. onProgress(event);
  66919. }
  66920. catch (e) {
  66921. errorHandler("Error in onProgress callback", e);
  66922. }
  66923. } : undefined;
  66924. var successHandler = function (assets) {
  66925. if (onSuccess) {
  66926. try {
  66927. onSuccess(assets);
  66928. }
  66929. catch (e) {
  66930. errorHandler("Error in onSuccess callback", e);
  66931. }
  66932. }
  66933. scene._removePendingData(loadingToken);
  66934. };
  66935. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66936. if (plugin.loadAssetContainer) {
  66937. var syncedPlugin = plugin;
  66938. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66939. if (!assetContainer) {
  66940. return;
  66941. }
  66942. scene.loadingPluginName = plugin.name;
  66943. successHandler(assetContainer);
  66944. }
  66945. else if (plugin.loadAssetContainerAsync) {
  66946. var asyncedPlugin = plugin;
  66947. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66948. scene.loadingPluginName = plugin.name;
  66949. successHandler(assetContainer);
  66950. }).catch(function (error) {
  66951. errorHandler(error.message, error);
  66952. });
  66953. }
  66954. else {
  66955. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66956. }
  66957. if (SceneLoader.ShowLoadingScreen) {
  66958. scene.executeWhenReady(function () {
  66959. scene.getEngine().hideLoadingUI();
  66960. });
  66961. }
  66962. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66963. };
  66964. /**
  66965. * Load a scene into an asset container
  66966. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  66967. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  66968. * @param scene is the instance of BABYLON.Scene to append to
  66969. * @param onProgress a callback with a progress event for each file being loaded
  66970. * @param pluginExtension the extension used to determine the plugin
  66971. * @returns The loaded asset container
  66972. */
  66973. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66974. if (sceneFilename === void 0) { sceneFilename = ""; }
  66975. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  66976. if (onProgress === void 0) { onProgress = null; }
  66977. if (pluginExtension === void 0) { pluginExtension = null; }
  66978. return new Promise(function (resolve, reject) {
  66979. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66980. resolve(assetContainer);
  66981. }, onProgress, function (scene, message, exception) {
  66982. reject(exception || new Error(message));
  66983. }, pluginExtension);
  66984. });
  66985. };
  66986. // Flags
  66987. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66988. SceneLoader._ShowLoadingScreen = true;
  66989. SceneLoader._CleanBoneMatrixWeights = false;
  66990. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66991. // Members
  66992. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66993. SceneLoader._registeredPlugins = {};
  66994. return SceneLoader;
  66995. }());
  66996. BABYLON.SceneLoader = SceneLoader;
  66997. ;
  66998. })(BABYLON || (BABYLON = {}));
  66999. //# sourceMappingURL=babylon.sceneLoader.js.map
  67000. var BABYLON;
  67001. (function (BABYLON) {
  67002. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67003. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67004. var parsedMaterial = parsedData.materials[index];
  67005. if (parsedMaterial.id === id) {
  67006. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67007. }
  67008. }
  67009. return null;
  67010. };
  67011. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67012. for (var i in names) {
  67013. if (mesh.name === names[i]) {
  67014. hierarchyIds.push(mesh.id);
  67015. return true;
  67016. }
  67017. }
  67018. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67019. hierarchyIds.push(mesh.id);
  67020. return true;
  67021. }
  67022. return false;
  67023. };
  67024. var logOperation = function (operation, producer) {
  67025. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67026. };
  67027. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67028. if (addToScene === void 0) { addToScene = false; }
  67029. var container = new BABYLON.AssetContainer(scene);
  67030. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67031. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67032. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67033. // and avoid problems with multiple concurrent .babylon loads.
  67034. var log = "importScene has failed JSON parse";
  67035. try {
  67036. var parsedData = JSON.parse(data);
  67037. log = "";
  67038. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67039. var index;
  67040. var cache;
  67041. // Lights
  67042. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67043. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67044. var parsedLight = parsedData.lights[index];
  67045. var light = BABYLON.Light.Parse(parsedLight, scene);
  67046. if (light) {
  67047. container.lights.push(light);
  67048. log += (index === 0 ? "\n\tLights:" : "");
  67049. log += "\n\t\t" + light.toString(fullDetails);
  67050. }
  67051. }
  67052. }
  67053. // Animations
  67054. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67055. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67056. var parsedAnimation = parsedData.animations[index];
  67057. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67058. scene.animations.push(animation);
  67059. container.animations.push(animation);
  67060. log += (index === 0 ? "\n\tAnimations:" : "");
  67061. log += "\n\t\t" + animation.toString(fullDetails);
  67062. }
  67063. }
  67064. // Materials
  67065. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67066. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67067. var parsedMaterial = parsedData.materials[index];
  67068. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67069. container.materials.push(mat);
  67070. log += (index === 0 ? "\n\tMaterials:" : "");
  67071. log += "\n\t\t" + mat.toString(fullDetails);
  67072. }
  67073. }
  67074. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67075. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67076. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67077. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67078. container.multiMaterials.push(mmat);
  67079. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67080. log += "\n\t\t" + mmat.toString(fullDetails);
  67081. }
  67082. }
  67083. // Morph targets
  67084. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67085. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67086. var managerData = _a[_i];
  67087. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67088. }
  67089. }
  67090. // Skeletons
  67091. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67092. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67093. var parsedSkeleton = parsedData.skeletons[index];
  67094. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67095. container.skeletons.push(skeleton);
  67096. log += (index === 0 ? "\n\tSkeletons:" : "");
  67097. log += "\n\t\t" + skeleton.toString(fullDetails);
  67098. }
  67099. }
  67100. // Geometries
  67101. var geometries = parsedData.geometries;
  67102. if (geometries !== undefined && geometries !== null) {
  67103. var addedGeometry = new Array();
  67104. // Boxes
  67105. var boxes = geometries.boxes;
  67106. if (boxes !== undefined && boxes !== null) {
  67107. for (index = 0, cache = boxes.length; index < cache; index++) {
  67108. var parsedBox = boxes[index];
  67109. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67110. }
  67111. }
  67112. // Spheres
  67113. var spheres = geometries.spheres;
  67114. if (spheres !== undefined && spheres !== null) {
  67115. for (index = 0, cache = spheres.length; index < cache; index++) {
  67116. var parsedSphere = spheres[index];
  67117. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67118. }
  67119. }
  67120. // Cylinders
  67121. var cylinders = geometries.cylinders;
  67122. if (cylinders !== undefined && cylinders !== null) {
  67123. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67124. var parsedCylinder = cylinders[index];
  67125. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67126. }
  67127. }
  67128. // Toruses
  67129. var toruses = geometries.toruses;
  67130. if (toruses !== undefined && toruses !== null) {
  67131. for (index = 0, cache = toruses.length; index < cache; index++) {
  67132. var parsedTorus = toruses[index];
  67133. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67134. }
  67135. }
  67136. // Grounds
  67137. var grounds = geometries.grounds;
  67138. if (grounds !== undefined && grounds !== null) {
  67139. for (index = 0, cache = grounds.length; index < cache; index++) {
  67140. var parsedGround = grounds[index];
  67141. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67142. }
  67143. }
  67144. // Planes
  67145. var planes = geometries.planes;
  67146. if (planes !== undefined && planes !== null) {
  67147. for (index = 0, cache = planes.length; index < cache; index++) {
  67148. var parsedPlane = planes[index];
  67149. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67150. }
  67151. }
  67152. // TorusKnots
  67153. var torusKnots = geometries.torusKnots;
  67154. if (torusKnots !== undefined && torusKnots !== null) {
  67155. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67156. var parsedTorusKnot = torusKnots[index];
  67157. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67158. }
  67159. }
  67160. // VertexData
  67161. var vertexData = geometries.vertexData;
  67162. if (vertexData !== undefined && vertexData !== null) {
  67163. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67164. var parsedVertexData = vertexData[index];
  67165. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67166. }
  67167. }
  67168. addedGeometry.forEach(function (g) {
  67169. if (g) {
  67170. container.geometries.push(g);
  67171. }
  67172. });
  67173. }
  67174. // Transform nodes
  67175. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67176. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67177. var parsedTransformNode = parsedData.transformNodes[index];
  67178. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67179. container.transformNodes.push(node);
  67180. }
  67181. }
  67182. // Meshes
  67183. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67184. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67185. var parsedMesh = parsedData.meshes[index];
  67186. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67187. container.meshes.push(mesh);
  67188. log += (index === 0 ? "\n\tMeshes:" : "");
  67189. log += "\n\t\t" + mesh.toString(fullDetails);
  67190. }
  67191. }
  67192. // Cameras
  67193. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67194. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67195. var parsedCamera = parsedData.cameras[index];
  67196. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67197. container.cameras.push(camera);
  67198. log += (index === 0 ? "\n\tCameras:" : "");
  67199. log += "\n\t\t" + camera.toString(fullDetails);
  67200. }
  67201. }
  67202. // Browsing all the graph to connect the dots
  67203. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67204. var camera = scene.cameras[index];
  67205. if (camera._waitingParentId) {
  67206. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67207. camera._waitingParentId = null;
  67208. }
  67209. }
  67210. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67211. var light_1 = scene.lights[index];
  67212. if (light_1 && light_1._waitingParentId) {
  67213. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67214. light_1._waitingParentId = null;
  67215. }
  67216. }
  67217. // Sounds
  67218. // TODO: add sound
  67219. var loadedSounds = [];
  67220. var loadedSound;
  67221. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67222. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67223. var parsedSound = parsedData.sounds[index];
  67224. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67225. if (!parsedSound.url)
  67226. parsedSound.url = parsedSound.name;
  67227. if (!loadedSounds[parsedSound.url]) {
  67228. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67229. loadedSounds[parsedSound.url] = loadedSound;
  67230. container.sounds.push(loadedSound);
  67231. }
  67232. else {
  67233. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67234. }
  67235. }
  67236. else {
  67237. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67238. }
  67239. }
  67240. }
  67241. loadedSounds = [];
  67242. // Connect parents & children and parse actions
  67243. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67244. var transformNode = scene.transformNodes[index];
  67245. if (transformNode._waitingParentId) {
  67246. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67247. transformNode._waitingParentId = null;
  67248. }
  67249. }
  67250. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67251. var mesh = scene.meshes[index];
  67252. if (mesh._waitingParentId) {
  67253. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67254. mesh._waitingParentId = null;
  67255. }
  67256. if (mesh._waitingActions) {
  67257. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67258. mesh._waitingActions = null;
  67259. }
  67260. }
  67261. // freeze world matrix application
  67262. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67263. var currentMesh = scene.meshes[index];
  67264. if (currentMesh._waitingFreezeWorldMatrix) {
  67265. currentMesh.freezeWorldMatrix();
  67266. currentMesh._waitingFreezeWorldMatrix = null;
  67267. }
  67268. else {
  67269. currentMesh.computeWorldMatrix(true);
  67270. }
  67271. }
  67272. // Particles Systems
  67273. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67274. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67275. var parsedParticleSystem = parsedData.particleSystems[index];
  67276. if (parsedParticleSystem.activeParticleCount) {
  67277. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67278. container.particleSystems.push(ps);
  67279. }
  67280. else {
  67281. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67282. container.particleSystems.push(ps);
  67283. }
  67284. }
  67285. }
  67286. // Lens flares
  67287. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67288. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67289. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67290. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67291. container.lensFlareSystems.push(lf);
  67292. }
  67293. }
  67294. // Shadows
  67295. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67296. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67297. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67298. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67299. container.shadowGenerators.push(sg);
  67300. }
  67301. }
  67302. // Lights exclusions / inclusions
  67303. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67304. var light_2 = scene.lights[index];
  67305. // Excluded check
  67306. if (light_2._excludedMeshesIds.length > 0) {
  67307. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67308. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67309. if (excludedMesh) {
  67310. light_2.excludedMeshes.push(excludedMesh);
  67311. }
  67312. }
  67313. light_2._excludedMeshesIds = [];
  67314. }
  67315. // Included check
  67316. if (light_2._includedOnlyMeshesIds.length > 0) {
  67317. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67318. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67319. if (includedOnlyMesh) {
  67320. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67321. }
  67322. }
  67323. light_2._includedOnlyMeshesIds = [];
  67324. }
  67325. }
  67326. // Effect layers
  67327. if (parsedData.effectLayers) {
  67328. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67329. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67330. container.effectLayers.push(effectLayer);
  67331. }
  67332. }
  67333. // Actions (scene)
  67334. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67335. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67336. }
  67337. if (!addToScene) {
  67338. container.removeAllFromScene();
  67339. }
  67340. }
  67341. catch (err) {
  67342. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67343. if (onError) {
  67344. onError(msg, err);
  67345. }
  67346. else {
  67347. BABYLON.Tools.Log(msg);
  67348. throw err;
  67349. }
  67350. }
  67351. finally {
  67352. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67353. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67354. }
  67355. }
  67356. return container;
  67357. };
  67358. BABYLON.SceneLoader.RegisterPlugin({
  67359. name: "babylon.js",
  67360. extensions: ".babylon",
  67361. canDirectLoad: function (data) {
  67362. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67363. return true;
  67364. }
  67365. return false;
  67366. },
  67367. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67368. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67369. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67370. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67371. // and avoid problems with multiple concurrent .babylon loads.
  67372. var log = "importMesh has failed JSON parse";
  67373. try {
  67374. var parsedData = JSON.parse(data);
  67375. log = "";
  67376. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67377. if (!meshesNames) {
  67378. meshesNames = null;
  67379. }
  67380. else if (!Array.isArray(meshesNames)) {
  67381. meshesNames = [meshesNames];
  67382. }
  67383. var hierarchyIds = new Array();
  67384. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67385. var loadedSkeletonsIds = [];
  67386. var loadedMaterialsIds = [];
  67387. var index;
  67388. var cache;
  67389. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67390. var parsedMesh = parsedData.meshes[index];
  67391. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67392. if (meshesNames !== null) {
  67393. // Remove found mesh name from list.
  67394. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67395. }
  67396. //Geometry?
  67397. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67398. //does the file contain geometries?
  67399. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67400. //find the correct geometry and add it to the scene
  67401. var found = false;
  67402. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67403. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67404. return;
  67405. }
  67406. else {
  67407. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67408. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67409. switch (geometryType) {
  67410. case "boxes":
  67411. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67412. break;
  67413. case "spheres":
  67414. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67415. break;
  67416. case "cylinders":
  67417. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67418. break;
  67419. case "toruses":
  67420. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67421. break;
  67422. case "grounds":
  67423. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67424. break;
  67425. case "planes":
  67426. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67427. break;
  67428. case "torusKnots":
  67429. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67430. break;
  67431. case "vertexData":
  67432. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67433. break;
  67434. }
  67435. found = true;
  67436. }
  67437. });
  67438. }
  67439. });
  67440. if (found === false) {
  67441. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67442. }
  67443. }
  67444. }
  67445. // Material ?
  67446. if (parsedMesh.materialId) {
  67447. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67448. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67449. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67450. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67451. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67452. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67453. var subMatId = parsedMultiMaterial.materials[matIndex];
  67454. loadedMaterialsIds.push(subMatId);
  67455. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67456. if (mat) {
  67457. log += "\n\tMaterial " + mat.toString(fullDetails);
  67458. }
  67459. }
  67460. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67461. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67462. if (mmat) {
  67463. materialFound = true;
  67464. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67465. }
  67466. break;
  67467. }
  67468. }
  67469. }
  67470. if (materialFound === false) {
  67471. loadedMaterialsIds.push(parsedMesh.materialId);
  67472. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67473. if (!mat) {
  67474. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67475. }
  67476. else {
  67477. log += "\n\tMaterial " + mat.toString(fullDetails);
  67478. }
  67479. }
  67480. }
  67481. // Skeleton ?
  67482. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67483. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67484. if (skeletonAlreadyLoaded === false) {
  67485. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67486. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67487. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67488. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67489. skeletons.push(skeleton);
  67490. loadedSkeletonsIds.push(parsedSkeleton.id);
  67491. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67492. }
  67493. }
  67494. }
  67495. }
  67496. // Morph targets ?
  67497. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67498. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67499. var managerData = _a[_i];
  67500. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67501. }
  67502. }
  67503. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67504. meshes.push(mesh);
  67505. log += "\n\tMesh " + mesh.toString(fullDetails);
  67506. }
  67507. }
  67508. // Connecting parents
  67509. var currentMesh;
  67510. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67511. currentMesh = scene.meshes[index];
  67512. if (currentMesh._waitingParentId) {
  67513. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67514. currentMesh._waitingParentId = null;
  67515. }
  67516. }
  67517. // freeze and compute world matrix application
  67518. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67519. currentMesh = scene.meshes[index];
  67520. if (currentMesh._waitingFreezeWorldMatrix) {
  67521. currentMesh.freezeWorldMatrix();
  67522. currentMesh._waitingFreezeWorldMatrix = null;
  67523. }
  67524. else {
  67525. currentMesh.computeWorldMatrix(true);
  67526. }
  67527. }
  67528. }
  67529. // Particles
  67530. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67531. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67532. var parsedParticleSystem = parsedData.particleSystems[index];
  67533. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67534. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67535. }
  67536. }
  67537. }
  67538. return true;
  67539. }
  67540. catch (err) {
  67541. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67542. if (onError) {
  67543. onError(msg, err);
  67544. }
  67545. else {
  67546. BABYLON.Tools.Log(msg);
  67547. throw err;
  67548. }
  67549. }
  67550. finally {
  67551. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67552. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67553. }
  67554. }
  67555. return false;
  67556. },
  67557. load: function (scene, data, rootUrl, onError) {
  67558. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67559. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67560. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67561. // and avoid problems with multiple concurrent .babylon loads.
  67562. var log = "importScene has failed JSON parse";
  67563. try {
  67564. var parsedData = JSON.parse(data);
  67565. log = "";
  67566. // Scene
  67567. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67568. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67569. }
  67570. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67571. scene.autoClear = parsedData.autoClear;
  67572. }
  67573. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67574. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67575. }
  67576. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67577. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67578. }
  67579. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67580. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67581. }
  67582. // Fog
  67583. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67584. scene.fogMode = parsedData.fogMode;
  67585. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67586. scene.fogStart = parsedData.fogStart;
  67587. scene.fogEnd = parsedData.fogEnd;
  67588. scene.fogDensity = parsedData.fogDensity;
  67589. log += "\tFog mode for scene: ";
  67590. switch (scene.fogMode) {
  67591. // getters not compiling, so using hardcoded
  67592. case 1:
  67593. log += "exp\n";
  67594. break;
  67595. case 2:
  67596. log += "exp2\n";
  67597. break;
  67598. case 3:
  67599. log += "linear\n";
  67600. break;
  67601. }
  67602. }
  67603. //Physics
  67604. if (parsedData.physicsEnabled) {
  67605. var physicsPlugin;
  67606. if (parsedData.physicsEngine === "cannon") {
  67607. physicsPlugin = new BABYLON.CannonJSPlugin();
  67608. }
  67609. else if (parsedData.physicsEngine === "oimo") {
  67610. physicsPlugin = new BABYLON.OimoJSPlugin();
  67611. }
  67612. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67613. //else - default engine, which is currently oimo
  67614. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67615. scene.enablePhysics(physicsGravity, physicsPlugin);
  67616. }
  67617. // Metadata
  67618. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67619. scene.metadata = parsedData.metadata;
  67620. }
  67621. //collisions, if defined. otherwise, default is true
  67622. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67623. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67624. }
  67625. scene.workerCollisions = !!parsedData.workerCollisions;
  67626. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67627. if (!container) {
  67628. return false;
  67629. }
  67630. if (parsedData.autoAnimate) {
  67631. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67632. }
  67633. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67634. scene.setActiveCameraByID(parsedData.activeCameraID);
  67635. }
  67636. // Environment texture
  67637. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67638. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67639. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67640. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67641. if (parsedData.environmentTextureRotationY) {
  67642. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67643. }
  67644. scene.environmentTexture = hdrTexture;
  67645. }
  67646. else {
  67647. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67648. if (parsedData.environmentTextureRotationY) {
  67649. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67650. }
  67651. scene.environmentTexture = cubeTexture;
  67652. }
  67653. if (parsedData.createDefaultSkybox === true) {
  67654. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67655. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67656. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67657. }
  67658. }
  67659. // Finish
  67660. return true;
  67661. }
  67662. catch (err) {
  67663. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67664. if (onError) {
  67665. onError(msg, err);
  67666. }
  67667. else {
  67668. BABYLON.Tools.Log(msg);
  67669. throw err;
  67670. }
  67671. }
  67672. finally {
  67673. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67674. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67675. }
  67676. }
  67677. return false;
  67678. },
  67679. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67680. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67681. return container;
  67682. }
  67683. });
  67684. })(BABYLON || (BABYLON = {}));
  67685. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67686. var BABYLON;
  67687. (function (BABYLON) {
  67688. var FilesInput = /** @class */ (function () {
  67689. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67690. this.onProcessFileCallback = function () { return true; };
  67691. this._engine = engine;
  67692. this._currentScene = scene;
  67693. this._sceneLoadedCallback = sceneLoadedCallback;
  67694. this._progressCallback = progressCallback;
  67695. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67696. this._textureLoadingCallback = textureLoadingCallback;
  67697. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67698. this._onReloadCallback = onReloadCallback;
  67699. this._errorCallback = errorCallback;
  67700. }
  67701. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67702. var _this = this;
  67703. if (elementToMonitor) {
  67704. this._elementToMonitor = elementToMonitor;
  67705. this._dragEnterHandler = function (e) { _this.drag(e); };
  67706. this._dragOverHandler = function (e) { _this.drag(e); };
  67707. this._dropHandler = function (e) { _this.drop(e); };
  67708. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67709. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67710. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67711. }
  67712. };
  67713. FilesInput.prototype.dispose = function () {
  67714. if (!this._elementToMonitor) {
  67715. return;
  67716. }
  67717. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67718. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67719. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67720. };
  67721. FilesInput.prototype.renderFunction = function () {
  67722. if (this._additionalRenderLoopLogicCallback) {
  67723. this._additionalRenderLoopLogicCallback();
  67724. }
  67725. if (this._currentScene) {
  67726. if (this._textureLoadingCallback) {
  67727. var remaining = this._currentScene.getWaitingItemsCount();
  67728. if (remaining > 0) {
  67729. this._textureLoadingCallback(remaining);
  67730. }
  67731. }
  67732. this._currentScene.render();
  67733. }
  67734. };
  67735. FilesInput.prototype.drag = function (e) {
  67736. e.stopPropagation();
  67737. e.preventDefault();
  67738. };
  67739. FilesInput.prototype.drop = function (eventDrop) {
  67740. eventDrop.stopPropagation();
  67741. eventDrop.preventDefault();
  67742. this.loadFiles(eventDrop);
  67743. };
  67744. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67745. var _this = this;
  67746. var reader = folder.createReader();
  67747. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67748. reader.readEntries(function (entries) {
  67749. remaining.count += entries.length;
  67750. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67751. var entry = entries_1[_i];
  67752. if (entry.isFile) {
  67753. entry.file(function (file) {
  67754. file.correctName = relativePath + file.name;
  67755. files.push(file);
  67756. if (--remaining.count === 0) {
  67757. callback();
  67758. }
  67759. });
  67760. }
  67761. else if (entry.isDirectory) {
  67762. _this._traverseFolder(entry, files, remaining, callback);
  67763. }
  67764. }
  67765. if (--remaining.count) {
  67766. callback();
  67767. }
  67768. });
  67769. };
  67770. FilesInput.prototype._processFiles = function (files) {
  67771. for (var i = 0; i < files.length; i++) {
  67772. var name = files[i].correctName.toLowerCase();
  67773. var extension = name.split('.').pop();
  67774. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67775. continue;
  67776. }
  67777. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67778. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67779. this._sceneFileToLoad = files[i];
  67780. }
  67781. else {
  67782. FilesInput.FilesToLoad[name] = files[i];
  67783. }
  67784. }
  67785. };
  67786. FilesInput.prototype.loadFiles = function (event) {
  67787. var _this = this;
  67788. if (this._startingProcessingFilesCallback)
  67789. this._startingProcessingFilesCallback();
  67790. // Handling data transfer via drag'n'drop
  67791. if (event && event.dataTransfer && event.dataTransfer.files) {
  67792. this._filesToLoad = event.dataTransfer.files;
  67793. }
  67794. // Handling files from input files
  67795. if (event && event.target && event.target.files) {
  67796. this._filesToLoad = event.target.files;
  67797. }
  67798. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67799. var files_1 = new Array();
  67800. var folders = [];
  67801. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67802. for (var i = 0; i < this._filesToLoad.length; i++) {
  67803. var fileToLoad = this._filesToLoad[i];
  67804. var name_1 = fileToLoad.name.toLowerCase();
  67805. var entry = void 0;
  67806. fileToLoad.correctName = name_1;
  67807. if (items) {
  67808. var item = items[i];
  67809. if (item.getAsEntry) {
  67810. entry = item.getAsEntry();
  67811. }
  67812. else if (item.webkitGetAsEntry) {
  67813. entry = item.webkitGetAsEntry();
  67814. }
  67815. }
  67816. if (!entry) {
  67817. files_1.push(fileToLoad);
  67818. }
  67819. else {
  67820. if (entry.isDirectory) {
  67821. folders.push(entry);
  67822. }
  67823. else {
  67824. files_1.push(fileToLoad);
  67825. }
  67826. }
  67827. }
  67828. if (folders.length === 0) {
  67829. this._processFiles(files_1);
  67830. this._processReload();
  67831. }
  67832. else {
  67833. var remaining = { count: folders.length };
  67834. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67835. var folder = folders_1[_i];
  67836. this._traverseFolder(folder, files_1, remaining, function () {
  67837. _this._processFiles(files_1);
  67838. if (remaining.count === 0) {
  67839. _this._processReload();
  67840. }
  67841. });
  67842. }
  67843. }
  67844. }
  67845. };
  67846. FilesInput.prototype._processReload = function () {
  67847. if (this._onReloadCallback) {
  67848. this._onReloadCallback(this._sceneFileToLoad);
  67849. }
  67850. else {
  67851. this.reload();
  67852. }
  67853. };
  67854. FilesInput.prototype.reload = function () {
  67855. var _this = this;
  67856. // If a scene file has been provided
  67857. if (this._sceneFileToLoad) {
  67858. if (this._currentScene) {
  67859. if (BABYLON.Tools.errorsCount > 0) {
  67860. BABYLON.Tools.ClearLogCache();
  67861. }
  67862. this._engine.stopRenderLoop();
  67863. }
  67864. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67865. if (_this._progressCallback) {
  67866. _this._progressCallback(progress);
  67867. }
  67868. }).then(function (scene) {
  67869. if (_this._currentScene) {
  67870. _this._currentScene.dispose();
  67871. }
  67872. _this._currentScene = scene;
  67873. if (_this._sceneLoadedCallback) {
  67874. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67875. }
  67876. // Wait for textures and shaders to be ready
  67877. _this._currentScene.executeWhenReady(function () {
  67878. _this._engine.runRenderLoop(function () {
  67879. _this.renderFunction();
  67880. });
  67881. });
  67882. }).catch(function (error) {
  67883. if (_this._errorCallback) {
  67884. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67885. }
  67886. });
  67887. }
  67888. else {
  67889. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67890. }
  67891. };
  67892. FilesInput.FilesToLoad = {};
  67893. return FilesInput;
  67894. }());
  67895. BABYLON.FilesInput = FilesInput;
  67896. })(BABYLON || (BABYLON = {}));
  67897. //# sourceMappingURL=babylon.filesInput.js.map
  67898. var BABYLON;
  67899. (function (BABYLON) {
  67900. /**
  67901. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67902. * The underlying implementation relies on an associative array to ensure the best performances.
  67903. * The value can be anything including 'null' but except 'undefined'
  67904. */
  67905. var StringDictionary = /** @class */ (function () {
  67906. function StringDictionary() {
  67907. this._count = 0;
  67908. this._data = {};
  67909. }
  67910. /**
  67911. * This will clear this dictionary and copy the content from the 'source' one.
  67912. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67913. * @param source the dictionary to take the content from and copy to this dictionary
  67914. */
  67915. StringDictionary.prototype.copyFrom = function (source) {
  67916. var _this = this;
  67917. this.clear();
  67918. source.forEach(function (t, v) { return _this.add(t, v); });
  67919. };
  67920. /**
  67921. * Get a value based from its key
  67922. * @param key the given key to get the matching value from
  67923. * @return the value if found, otherwise undefined is returned
  67924. */
  67925. StringDictionary.prototype.get = function (key) {
  67926. var val = this._data[key];
  67927. if (val !== undefined) {
  67928. return val;
  67929. }
  67930. return undefined;
  67931. };
  67932. /**
  67933. * Get a value from its key or add it if it doesn't exist.
  67934. * This method will ensure you that a given key/data will be present in the dictionary.
  67935. * @param key the given key to get the matching value from
  67936. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67937. * The factory will only be invoked if there's no data for the given key.
  67938. * @return the value corresponding to the key.
  67939. */
  67940. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67941. var val = this.get(key);
  67942. if (val !== undefined) {
  67943. return val;
  67944. }
  67945. val = factory(key);
  67946. if (val) {
  67947. this.add(key, val);
  67948. }
  67949. return val;
  67950. };
  67951. /**
  67952. * Get a value from its key if present in the dictionary otherwise add it
  67953. * @param key the key to get the value from
  67954. * @param val if there's no such key/value pair in the dictionary add it with this value
  67955. * @return the value corresponding to the key
  67956. */
  67957. StringDictionary.prototype.getOrAdd = function (key, val) {
  67958. var curVal = this.get(key);
  67959. if (curVal !== undefined) {
  67960. return curVal;
  67961. }
  67962. this.add(key, val);
  67963. return val;
  67964. };
  67965. /**
  67966. * Check if there's a given key in the dictionary
  67967. * @param key the key to check for
  67968. * @return true if the key is present, false otherwise
  67969. */
  67970. StringDictionary.prototype.contains = function (key) {
  67971. return this._data[key] !== undefined;
  67972. };
  67973. /**
  67974. * Add a new key and its corresponding value
  67975. * @param key the key to add
  67976. * @param value the value corresponding to the key
  67977. * @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
  67978. */
  67979. StringDictionary.prototype.add = function (key, value) {
  67980. if (this._data[key] !== undefined) {
  67981. return false;
  67982. }
  67983. this._data[key] = value;
  67984. ++this._count;
  67985. return true;
  67986. };
  67987. StringDictionary.prototype.set = function (key, value) {
  67988. if (this._data[key] === undefined) {
  67989. return false;
  67990. }
  67991. this._data[key] = value;
  67992. return true;
  67993. };
  67994. /**
  67995. * Get the element of the given key and remove it from the dictionary
  67996. * @param key
  67997. */
  67998. StringDictionary.prototype.getAndRemove = function (key) {
  67999. var val = this.get(key);
  68000. if (val !== undefined) {
  68001. delete this._data[key];
  68002. --this._count;
  68003. return val;
  68004. }
  68005. return null;
  68006. };
  68007. /**
  68008. * Remove a key/value from the dictionary.
  68009. * @param key the key to remove
  68010. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68011. */
  68012. StringDictionary.prototype.remove = function (key) {
  68013. if (this.contains(key)) {
  68014. delete this._data[key];
  68015. --this._count;
  68016. return true;
  68017. }
  68018. return false;
  68019. };
  68020. /**
  68021. * Clear the whole content of the dictionary
  68022. */
  68023. StringDictionary.prototype.clear = function () {
  68024. this._data = {};
  68025. this._count = 0;
  68026. };
  68027. Object.defineProperty(StringDictionary.prototype, "count", {
  68028. get: function () {
  68029. return this._count;
  68030. },
  68031. enumerable: true,
  68032. configurable: true
  68033. });
  68034. /**
  68035. * Execute a callback on each key/val of the dictionary.
  68036. * Note that you can remove any element in this dictionary in the callback implementation
  68037. * @param callback the callback to execute on a given key/value pair
  68038. */
  68039. StringDictionary.prototype.forEach = function (callback) {
  68040. for (var cur in this._data) {
  68041. var val = this._data[cur];
  68042. callback(cur, val);
  68043. }
  68044. };
  68045. /**
  68046. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68047. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68048. * Note that you can remove any element in this dictionary in the callback implementation
  68049. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68050. */
  68051. StringDictionary.prototype.first = function (callback) {
  68052. for (var cur in this._data) {
  68053. var val = this._data[cur];
  68054. var res = callback(cur, val);
  68055. if (res) {
  68056. return res;
  68057. }
  68058. }
  68059. return null;
  68060. };
  68061. return StringDictionary;
  68062. }());
  68063. BABYLON.StringDictionary = StringDictionary;
  68064. })(BABYLON || (BABYLON = {}));
  68065. //# sourceMappingURL=babylon.stringDictionary.js.map
  68066. var BABYLON;
  68067. (function (BABYLON) {
  68068. var Tags = /** @class */ (function () {
  68069. function Tags() {
  68070. }
  68071. Tags.EnableFor = function (obj) {
  68072. obj._tags = obj._tags || {};
  68073. obj.hasTags = function () {
  68074. return Tags.HasTags(obj);
  68075. };
  68076. obj.addTags = function (tagsString) {
  68077. return Tags.AddTagsTo(obj, tagsString);
  68078. };
  68079. obj.removeTags = function (tagsString) {
  68080. return Tags.RemoveTagsFrom(obj, tagsString);
  68081. };
  68082. obj.matchesTagsQuery = function (tagsQuery) {
  68083. return Tags.MatchesQuery(obj, tagsQuery);
  68084. };
  68085. };
  68086. Tags.DisableFor = function (obj) {
  68087. delete obj._tags;
  68088. delete obj.hasTags;
  68089. delete obj.addTags;
  68090. delete obj.removeTags;
  68091. delete obj.matchesTagsQuery;
  68092. };
  68093. Tags.HasTags = function (obj) {
  68094. if (!obj._tags) {
  68095. return false;
  68096. }
  68097. return !BABYLON.Tools.IsEmpty(obj._tags);
  68098. };
  68099. Tags.GetTags = function (obj, asString) {
  68100. if (asString === void 0) { asString = true; }
  68101. if (!obj._tags) {
  68102. return null;
  68103. }
  68104. if (asString) {
  68105. var tagsArray = [];
  68106. for (var tag in obj._tags) {
  68107. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68108. tagsArray.push(tag);
  68109. }
  68110. }
  68111. return tagsArray.join(" ");
  68112. }
  68113. else {
  68114. return obj._tags;
  68115. }
  68116. };
  68117. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68118. // a tag cannot start with '||', '&&', and '!'
  68119. // it cannot contain whitespaces
  68120. Tags.AddTagsTo = function (obj, tagsString) {
  68121. if (!tagsString) {
  68122. return;
  68123. }
  68124. if (typeof tagsString !== "string") {
  68125. return;
  68126. }
  68127. var tags = tagsString.split(" ");
  68128. tags.forEach(function (tag, index, array) {
  68129. Tags._AddTagTo(obj, tag);
  68130. });
  68131. };
  68132. Tags._AddTagTo = function (obj, tag) {
  68133. tag = tag.trim();
  68134. if (tag === "" || tag === "true" || tag === "false") {
  68135. return;
  68136. }
  68137. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68138. return;
  68139. }
  68140. Tags.EnableFor(obj);
  68141. obj._tags[tag] = true;
  68142. };
  68143. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68144. if (!Tags.HasTags(obj)) {
  68145. return;
  68146. }
  68147. var tags = tagsString.split(" ");
  68148. for (var t in tags) {
  68149. Tags._RemoveTagFrom(obj, tags[t]);
  68150. }
  68151. };
  68152. Tags._RemoveTagFrom = function (obj, tag) {
  68153. delete obj._tags[tag];
  68154. };
  68155. Tags.MatchesQuery = function (obj, tagsQuery) {
  68156. if (tagsQuery === undefined) {
  68157. return true;
  68158. }
  68159. if (tagsQuery === "") {
  68160. return Tags.HasTags(obj);
  68161. }
  68162. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68163. };
  68164. return Tags;
  68165. }());
  68166. BABYLON.Tags = Tags;
  68167. })(BABYLON || (BABYLON = {}));
  68168. //# sourceMappingURL=babylon.tags.js.map
  68169. var BABYLON;
  68170. (function (BABYLON) {
  68171. /**
  68172. * Class used to evalaute queries containing `and` and `or` operators
  68173. */
  68174. var AndOrNotEvaluator = /** @class */ (function () {
  68175. function AndOrNotEvaluator() {
  68176. }
  68177. /**
  68178. * Evaluate a query
  68179. * @param query defines the query to evaluate
  68180. * @param evaluateCallback defines the callback used to filter result
  68181. * @returns true if the query matches
  68182. */
  68183. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68184. if (!query.match(/\([^\(\)]*\)/g)) {
  68185. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68186. }
  68187. else {
  68188. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68189. // remove parenthesis
  68190. r = r.slice(1, r.length - 1);
  68191. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68192. });
  68193. }
  68194. if (query === "true") {
  68195. return true;
  68196. }
  68197. if (query === "false") {
  68198. return false;
  68199. }
  68200. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68201. };
  68202. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68203. evaluateCallback = evaluateCallback || (function (r) {
  68204. return r === "true" ? true : false;
  68205. });
  68206. var result;
  68207. var or = parenthesisContent.split("||");
  68208. for (var i in or) {
  68209. if (or.hasOwnProperty(i)) {
  68210. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68211. var and = ori.split("&&");
  68212. if (and.length > 1) {
  68213. for (var j = 0; j < and.length; ++j) {
  68214. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68215. if (andj !== "true" && andj !== "false") {
  68216. if (andj[0] === "!") {
  68217. result = !evaluateCallback(andj.substring(1));
  68218. }
  68219. else {
  68220. result = evaluateCallback(andj);
  68221. }
  68222. }
  68223. else {
  68224. result = andj === "true" ? true : false;
  68225. }
  68226. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68227. ori = "false";
  68228. break;
  68229. }
  68230. }
  68231. }
  68232. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68233. result = true;
  68234. break;
  68235. }
  68236. // result equals false (or undefined)
  68237. if (ori !== "true" && ori !== "false") {
  68238. if (ori[0] === "!") {
  68239. result = !evaluateCallback(ori.substring(1));
  68240. }
  68241. else {
  68242. result = evaluateCallback(ori);
  68243. }
  68244. }
  68245. else {
  68246. result = ori === "true" ? true : false;
  68247. }
  68248. }
  68249. }
  68250. // the whole parenthesis scope is replaced by 'true' or 'false'
  68251. return result ? "true" : "false";
  68252. };
  68253. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68254. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68255. // remove whitespaces
  68256. r = r.replace(/[\s]/g, function () { return ""; });
  68257. return r.length % 2 ? "!" : "";
  68258. });
  68259. booleanString = booleanString.trim();
  68260. if (booleanString === "!true") {
  68261. booleanString = "false";
  68262. }
  68263. else if (booleanString === "!false") {
  68264. booleanString = "true";
  68265. }
  68266. return booleanString;
  68267. };
  68268. return AndOrNotEvaluator;
  68269. }());
  68270. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68271. })(BABYLON || (BABYLON = {}));
  68272. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68273. var BABYLON;
  68274. (function (BABYLON) {
  68275. /**
  68276. * Class used to enable access to IndexedDB
  68277. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68278. */
  68279. var Database = /** @class */ (function () {
  68280. /**
  68281. * Creates a new Database
  68282. * @param urlToScene defines the url to load the scene
  68283. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68284. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68285. */
  68286. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68287. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68288. var _this = this;
  68289. // Handling various flavors of prefixed version of IndexedDB
  68290. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68291. this.callbackManifestChecked = callbackManifestChecked;
  68292. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68293. this.db = null;
  68294. this._enableSceneOffline = false;
  68295. this._enableTexturesOffline = false;
  68296. this.manifestVersionFound = 0;
  68297. this.mustUpdateRessources = false;
  68298. this.hasReachedQuota = false;
  68299. if (!Database.IDBStorageEnabled) {
  68300. this.callbackManifestChecked(true);
  68301. }
  68302. else {
  68303. if (disableManifestCheck) {
  68304. this._enableSceneOffline = true;
  68305. this._enableTexturesOffline = true;
  68306. this.manifestVersionFound = 1;
  68307. BABYLON.Tools.SetImmediate(function () {
  68308. _this.callbackManifestChecked(true);
  68309. });
  68310. }
  68311. else {
  68312. this._checkManifestFile();
  68313. }
  68314. }
  68315. }
  68316. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68317. /**
  68318. * Gets a boolean indicating if scene must be saved in the database
  68319. */
  68320. get: function () {
  68321. return this._enableSceneOffline;
  68322. },
  68323. enumerable: true,
  68324. configurable: true
  68325. });
  68326. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68327. /**
  68328. * Gets a boolean indicating if textures must be saved in the database
  68329. */
  68330. get: function () {
  68331. return this._enableTexturesOffline;
  68332. },
  68333. enumerable: true,
  68334. configurable: true
  68335. });
  68336. Database.prototype._checkManifestFile = function () {
  68337. var _this = this;
  68338. var noManifestFile = function () {
  68339. _this._enableSceneOffline = false;
  68340. _this._enableTexturesOffline = false;
  68341. _this.callbackManifestChecked(false);
  68342. };
  68343. var timeStampUsed = false;
  68344. var manifestURL = this.currentSceneUrl + ".manifest";
  68345. var xhr = new XMLHttpRequest();
  68346. if (navigator.onLine) {
  68347. // Adding a timestamp to by-pass browsers' cache
  68348. timeStampUsed = true;
  68349. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68350. }
  68351. xhr.open("GET", manifestURL, true);
  68352. xhr.addEventListener("load", function () {
  68353. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68354. try {
  68355. var manifestFile = JSON.parse(xhr.response);
  68356. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68357. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68358. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68359. _this.manifestVersionFound = manifestFile.version;
  68360. }
  68361. if (_this.callbackManifestChecked) {
  68362. _this.callbackManifestChecked(true);
  68363. }
  68364. }
  68365. catch (ex) {
  68366. noManifestFile();
  68367. }
  68368. }
  68369. else {
  68370. noManifestFile();
  68371. }
  68372. }, false);
  68373. xhr.addEventListener("error", function (event) {
  68374. if (timeStampUsed) {
  68375. timeStampUsed = false;
  68376. // Let's retry without the timeStamp
  68377. // It could fail when coupled with HTML5 Offline API
  68378. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68379. xhr.open("GET", retryManifestURL, true);
  68380. xhr.send();
  68381. }
  68382. else {
  68383. noManifestFile();
  68384. }
  68385. }, false);
  68386. try {
  68387. xhr.send();
  68388. }
  68389. catch (ex) {
  68390. BABYLON.Tools.Error("Error on XHR send request.");
  68391. this.callbackManifestChecked(false);
  68392. }
  68393. };
  68394. /**
  68395. * Open the database and make it available
  68396. * @param successCallback defines the callback to call on success
  68397. * @param errorCallback defines the callback to call on error
  68398. */
  68399. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68400. var _this = this;
  68401. var handleError = function () {
  68402. _this.isSupported = false;
  68403. if (errorCallback)
  68404. errorCallback();
  68405. };
  68406. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68407. // Your browser doesn't support IndexedDB
  68408. this.isSupported = false;
  68409. if (errorCallback)
  68410. errorCallback();
  68411. }
  68412. else {
  68413. // If the DB hasn't been opened or created yet
  68414. if (!this.db) {
  68415. this.hasReachedQuota = false;
  68416. this.isSupported = true;
  68417. var request = this.idbFactory.open("babylonjs", 1);
  68418. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68419. request.onerror = function (event) {
  68420. handleError();
  68421. };
  68422. // executes when a version change transaction cannot complete due to other active transactions
  68423. request.onblocked = function (event) {
  68424. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68425. handleError();
  68426. };
  68427. // DB has been opened successfully
  68428. request.onsuccess = function (event) {
  68429. _this.db = request.result;
  68430. successCallback();
  68431. };
  68432. // Initialization of the DB. Creating Scenes & Textures stores
  68433. request.onupgradeneeded = function (event) {
  68434. _this.db = (event.target).result;
  68435. if (_this.db) {
  68436. try {
  68437. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68438. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68439. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68440. }
  68441. catch (ex) {
  68442. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68443. handleError();
  68444. }
  68445. }
  68446. };
  68447. }
  68448. // DB has already been created and opened
  68449. else {
  68450. if (successCallback)
  68451. successCallback();
  68452. }
  68453. }
  68454. };
  68455. /**
  68456. * Loads an image from the database
  68457. * @param url defines the url to load from
  68458. * @param image defines the target DOM image
  68459. */
  68460. Database.prototype.loadImageFromDB = function (url, image) {
  68461. var _this = this;
  68462. var completeURL = Database._ReturnFullUrlLocation(url);
  68463. var saveAndLoadImage = function () {
  68464. if (!_this.hasReachedQuota && _this.db !== null) {
  68465. // the texture is not yet in the DB, let's try to save it
  68466. _this._saveImageIntoDBAsync(completeURL, image);
  68467. }
  68468. // If the texture is not in the DB and we've reached the DB quota limit
  68469. // let's load it directly from the web
  68470. else {
  68471. image.src = url;
  68472. }
  68473. };
  68474. if (!this.mustUpdateRessources) {
  68475. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68476. }
  68477. // First time we're download the images or update requested in the manifest file by a version change
  68478. else {
  68479. saveAndLoadImage();
  68480. }
  68481. };
  68482. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68483. if (this.isSupported && this.db !== null) {
  68484. var texture;
  68485. var transaction = this.db.transaction(["textures"]);
  68486. transaction.onabort = function (event) {
  68487. image.src = url;
  68488. };
  68489. transaction.oncomplete = function (event) {
  68490. var blobTextureURL;
  68491. if (texture) {
  68492. var URL = window.URL || window.webkitURL;
  68493. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68494. image.onerror = function () {
  68495. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68496. image.src = url;
  68497. };
  68498. image.src = blobTextureURL;
  68499. }
  68500. else {
  68501. notInDBCallback();
  68502. }
  68503. };
  68504. var getRequest = transaction.objectStore("textures").get(url);
  68505. getRequest.onsuccess = function (event) {
  68506. texture = (event.target).result;
  68507. };
  68508. getRequest.onerror = function (event) {
  68509. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68510. image.src = url;
  68511. };
  68512. }
  68513. else {
  68514. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68515. image.src = url;
  68516. }
  68517. };
  68518. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68519. var _this = this;
  68520. if (this.isSupported) {
  68521. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68522. var generateBlobUrl = function () {
  68523. var blobTextureURL;
  68524. if (blob) {
  68525. var URL = window.URL || window.webkitURL;
  68526. try {
  68527. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68528. }
  68529. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68530. catch (ex) {
  68531. blobTextureURL = URL.createObjectURL(blob);
  68532. }
  68533. }
  68534. if (blobTextureURL) {
  68535. image.src = blobTextureURL;
  68536. }
  68537. };
  68538. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68539. var xhr = new XMLHttpRequest(), blob;
  68540. xhr.open("GET", url, true);
  68541. xhr.responseType = "blob";
  68542. xhr.addEventListener("load", function () {
  68543. if (xhr.status === 200 && _this.db) {
  68544. // Blob as response (XHR2)
  68545. blob = xhr.response;
  68546. var transaction = _this.db.transaction(["textures"], "readwrite");
  68547. // the transaction could abort because of a QuotaExceededError error
  68548. transaction.onabort = function (event) {
  68549. try {
  68550. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68551. var srcElement = (event.srcElement || event.target);
  68552. var error = srcElement.error;
  68553. if (error && error.name === "QuotaExceededError") {
  68554. _this.hasReachedQuota = true;
  68555. }
  68556. }
  68557. catch (ex) { }
  68558. generateBlobUrl();
  68559. };
  68560. transaction.oncomplete = function (event) {
  68561. generateBlobUrl();
  68562. };
  68563. var newTexture = { textureUrl: url, data: blob };
  68564. try {
  68565. // Put the blob into the dabase
  68566. var addRequest = transaction.objectStore("textures").put(newTexture);
  68567. addRequest.onsuccess = function (event) {
  68568. };
  68569. addRequest.onerror = function (event) {
  68570. generateBlobUrl();
  68571. };
  68572. }
  68573. catch (ex) {
  68574. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68575. if (ex.code === 25) {
  68576. Database.IsUASupportingBlobStorage = false;
  68577. }
  68578. image.src = url;
  68579. }
  68580. }
  68581. else {
  68582. image.src = url;
  68583. }
  68584. }, false);
  68585. xhr.addEventListener("error", function (event) {
  68586. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68587. image.src = url;
  68588. }, false);
  68589. xhr.send();
  68590. }
  68591. else {
  68592. image.src = url;
  68593. }
  68594. }
  68595. else {
  68596. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68597. image.src = url;
  68598. }
  68599. };
  68600. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68601. var _this = this;
  68602. var updateVersion = function () {
  68603. // the version is not yet in the DB or we need to update it
  68604. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68605. };
  68606. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68607. };
  68608. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68609. var _this = this;
  68610. if (this.isSupported && this.db) {
  68611. var version;
  68612. try {
  68613. var transaction = this.db.transaction(["versions"]);
  68614. transaction.oncomplete = function (event) {
  68615. if (version) {
  68616. // If the version in the JSON file is different from the version in DB
  68617. if (_this.manifestVersionFound !== version.data) {
  68618. _this.mustUpdateRessources = true;
  68619. updateInDBCallback();
  68620. }
  68621. else {
  68622. callback(version.data);
  68623. }
  68624. }
  68625. // version was not found in DB
  68626. else {
  68627. _this.mustUpdateRessources = true;
  68628. updateInDBCallback();
  68629. }
  68630. };
  68631. transaction.onabort = function (event) {
  68632. callback(-1);
  68633. };
  68634. var getRequest = transaction.objectStore("versions").get(url);
  68635. getRequest.onsuccess = function (event) {
  68636. version = (event.target).result;
  68637. };
  68638. getRequest.onerror = function (event) {
  68639. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68640. callback(-1);
  68641. };
  68642. }
  68643. catch (ex) {
  68644. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68645. callback(-1);
  68646. }
  68647. }
  68648. else {
  68649. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68650. callback(-1);
  68651. }
  68652. };
  68653. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68654. var _this = this;
  68655. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68656. try {
  68657. // Open a transaction to the database
  68658. var transaction = this.db.transaction(["versions"], "readwrite");
  68659. // the transaction could abort because of a QuotaExceededError error
  68660. transaction.onabort = function (event) {
  68661. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68662. var error = event.srcElement['error'];
  68663. if (error && error.name === "QuotaExceededError") {
  68664. _this.hasReachedQuota = true;
  68665. }
  68666. }
  68667. catch (ex) { }
  68668. callback(-1);
  68669. };
  68670. transaction.oncomplete = function (event) {
  68671. callback(_this.manifestVersionFound);
  68672. };
  68673. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68674. // Put the scene into the database
  68675. var addRequest = transaction.objectStore("versions").put(newVersion);
  68676. addRequest.onsuccess = function (event) {
  68677. };
  68678. addRequest.onerror = function (event) {
  68679. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68680. };
  68681. }
  68682. catch (ex) {
  68683. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68684. callback(-1);
  68685. }
  68686. }
  68687. else {
  68688. callback(-1);
  68689. }
  68690. };
  68691. /**
  68692. * Loads a file from database
  68693. * @param url defines the URL to load from
  68694. * @param sceneLoaded defines a callback to call on success
  68695. * @param progressCallBack defines a callback to call when progress changed
  68696. * @param errorCallback defines a callback to call on error
  68697. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68698. */
  68699. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68700. var _this = this;
  68701. var completeUrl = Database._ReturnFullUrlLocation(url);
  68702. var saveAndLoadFile = function () {
  68703. // the scene is not yet in the DB, let's try to save it
  68704. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68705. };
  68706. this._checkVersionFromDB(completeUrl, function (version) {
  68707. if (version !== -1) {
  68708. if (!_this.mustUpdateRessources) {
  68709. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68710. }
  68711. else {
  68712. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68713. }
  68714. }
  68715. else {
  68716. if (errorCallback) {
  68717. errorCallback();
  68718. }
  68719. }
  68720. });
  68721. };
  68722. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68723. if (this.isSupported && this.db) {
  68724. var targetStore;
  68725. if (url.indexOf(".babylon") !== -1) {
  68726. targetStore = "scenes";
  68727. }
  68728. else {
  68729. targetStore = "textures";
  68730. }
  68731. var file;
  68732. var transaction = this.db.transaction([targetStore]);
  68733. transaction.oncomplete = function (event) {
  68734. if (file) {
  68735. callback(file.data);
  68736. }
  68737. // file was not found in DB
  68738. else {
  68739. notInDBCallback();
  68740. }
  68741. };
  68742. transaction.onabort = function (event) {
  68743. notInDBCallback();
  68744. };
  68745. var getRequest = transaction.objectStore(targetStore).get(url);
  68746. getRequest.onsuccess = function (event) {
  68747. file = (event.target).result;
  68748. };
  68749. getRequest.onerror = function (event) {
  68750. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68751. notInDBCallback();
  68752. };
  68753. }
  68754. else {
  68755. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68756. callback();
  68757. }
  68758. };
  68759. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68760. var _this = this;
  68761. if (this.isSupported) {
  68762. var targetStore;
  68763. if (url.indexOf(".babylon") !== -1) {
  68764. targetStore = "scenes";
  68765. }
  68766. else {
  68767. targetStore = "textures";
  68768. }
  68769. // Create XHR
  68770. var xhr = new XMLHttpRequest();
  68771. var fileData;
  68772. xhr.open("GET", url, true);
  68773. if (useArrayBuffer) {
  68774. xhr.responseType = "arraybuffer";
  68775. }
  68776. if (progressCallback) {
  68777. xhr.onprogress = progressCallback;
  68778. }
  68779. xhr.addEventListener("load", function () {
  68780. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68781. // Blob as response (XHR2)
  68782. //fileData = xhr.responseText;
  68783. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68784. if (!_this.hasReachedQuota && _this.db) {
  68785. // Open a transaction to the database
  68786. var transaction = _this.db.transaction([targetStore], "readwrite");
  68787. // the transaction could abort because of a QuotaExceededError error
  68788. transaction.onabort = function (event) {
  68789. try {
  68790. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68791. var error = event.srcElement['error'];
  68792. if (error && error.name === "QuotaExceededError") {
  68793. _this.hasReachedQuota = true;
  68794. }
  68795. }
  68796. catch (ex) { }
  68797. callback(fileData);
  68798. };
  68799. transaction.oncomplete = function (event) {
  68800. callback(fileData);
  68801. };
  68802. var newFile;
  68803. if (targetStore === "scenes") {
  68804. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68805. }
  68806. else {
  68807. newFile = { textureUrl: url, data: fileData };
  68808. }
  68809. try {
  68810. // Put the scene into the database
  68811. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68812. addRequest.onsuccess = function (event) {
  68813. };
  68814. addRequest.onerror = function (event) {
  68815. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68816. };
  68817. }
  68818. catch (ex) {
  68819. callback(fileData);
  68820. }
  68821. }
  68822. else {
  68823. callback(fileData);
  68824. }
  68825. }
  68826. else {
  68827. callback();
  68828. }
  68829. }, false);
  68830. xhr.addEventListener("error", function (event) {
  68831. BABYLON.Tools.Error("error on XHR request.");
  68832. callback();
  68833. }, false);
  68834. xhr.send();
  68835. }
  68836. else {
  68837. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68838. callback();
  68839. }
  68840. };
  68841. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  68842. Database.IsUASupportingBlobStorage = true;
  68843. /** Gets a boolean indicating if Database storate is enabled */
  68844. Database.IDBStorageEnabled = true;
  68845. Database._ParseURL = function (url) {
  68846. var a = document.createElement('a');
  68847. a.href = url;
  68848. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68849. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68850. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68851. return absLocation;
  68852. };
  68853. Database._ReturnFullUrlLocation = function (url) {
  68854. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68855. return (Database._ParseURL(window.location.href) + url);
  68856. }
  68857. else {
  68858. return url;
  68859. }
  68860. };
  68861. return Database;
  68862. }());
  68863. BABYLON.Database = Database;
  68864. })(BABYLON || (BABYLON = {}));
  68865. //# sourceMappingURL=babylon.database.js.map
  68866. var BABYLON;
  68867. (function (BABYLON) {
  68868. var FresnelParameters = /** @class */ (function () {
  68869. function FresnelParameters() {
  68870. this._isEnabled = true;
  68871. this.leftColor = BABYLON.Color3.White();
  68872. this.rightColor = BABYLON.Color3.Black();
  68873. this.bias = 0;
  68874. this.power = 1;
  68875. }
  68876. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68877. get: function () {
  68878. return this._isEnabled;
  68879. },
  68880. set: function (value) {
  68881. if (this._isEnabled === value) {
  68882. return;
  68883. }
  68884. this._isEnabled = value;
  68885. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68886. },
  68887. enumerable: true,
  68888. configurable: true
  68889. });
  68890. FresnelParameters.prototype.clone = function () {
  68891. var newFresnelParameters = new FresnelParameters();
  68892. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68893. return newFresnelParameters;
  68894. };
  68895. FresnelParameters.prototype.serialize = function () {
  68896. var serializationObject = {};
  68897. serializationObject.isEnabled = this.isEnabled;
  68898. serializationObject.leftColor = this.leftColor.asArray();
  68899. serializationObject.rightColor = this.rightColor.asArray();
  68900. serializationObject.bias = this.bias;
  68901. serializationObject.power = this.power;
  68902. return serializationObject;
  68903. };
  68904. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68905. var fresnelParameters = new FresnelParameters();
  68906. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68907. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68908. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68909. fresnelParameters.bias = parsedFresnelParameters.bias;
  68910. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68911. return fresnelParameters;
  68912. };
  68913. return FresnelParameters;
  68914. }());
  68915. BABYLON.FresnelParameters = FresnelParameters;
  68916. })(BABYLON || (BABYLON = {}));
  68917. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68918. var BABYLON;
  68919. (function (BABYLON) {
  68920. var MultiMaterial = /** @class */ (function (_super) {
  68921. __extends(MultiMaterial, _super);
  68922. function MultiMaterial(name, scene) {
  68923. var _this = _super.call(this, name, scene, true) || this;
  68924. scene.multiMaterials.push(_this);
  68925. _this.subMaterials = new Array();
  68926. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68927. return _this;
  68928. }
  68929. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68930. get: function () {
  68931. return this._subMaterials;
  68932. },
  68933. set: function (value) {
  68934. this._subMaterials = value;
  68935. this._hookArray(value);
  68936. },
  68937. enumerable: true,
  68938. configurable: true
  68939. });
  68940. MultiMaterial.prototype._hookArray = function (array) {
  68941. var _this = this;
  68942. var oldPush = array.push;
  68943. array.push = function () {
  68944. var items = [];
  68945. for (var _i = 0; _i < arguments.length; _i++) {
  68946. items[_i] = arguments[_i];
  68947. }
  68948. var result = oldPush.apply(array, items);
  68949. _this._markAllSubMeshesAsTexturesDirty();
  68950. return result;
  68951. };
  68952. var oldSplice = array.splice;
  68953. array.splice = function (index, deleteCount) {
  68954. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68955. _this._markAllSubMeshesAsTexturesDirty();
  68956. return deleted;
  68957. };
  68958. };
  68959. // Properties
  68960. MultiMaterial.prototype.getSubMaterial = function (index) {
  68961. if (index < 0 || index >= this.subMaterials.length) {
  68962. return this.getScene().defaultMaterial;
  68963. }
  68964. return this.subMaterials[index];
  68965. };
  68966. MultiMaterial.prototype.getActiveTextures = function () {
  68967. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68968. if (subMaterial) {
  68969. return subMaterial.getActiveTextures();
  68970. }
  68971. else {
  68972. return [];
  68973. }
  68974. }));
  68975. var _a;
  68976. };
  68977. // Methods
  68978. MultiMaterial.prototype.getClassName = function () {
  68979. return "MultiMaterial";
  68980. };
  68981. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68982. for (var index = 0; index < this.subMaterials.length; index++) {
  68983. var subMaterial = this.subMaterials[index];
  68984. if (subMaterial) {
  68985. if (subMaterial.storeEffectOnSubMeshes) {
  68986. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68987. return false;
  68988. }
  68989. continue;
  68990. }
  68991. if (!subMaterial.isReady(mesh)) {
  68992. return false;
  68993. }
  68994. }
  68995. }
  68996. return true;
  68997. };
  68998. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68999. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69000. for (var index = 0; index < this.subMaterials.length; index++) {
  69001. var subMaterial = null;
  69002. var current = this.subMaterials[index];
  69003. if (cloneChildren && current) {
  69004. subMaterial = current.clone(name + "-" + current.name);
  69005. }
  69006. else {
  69007. subMaterial = this.subMaterials[index];
  69008. }
  69009. newMultiMaterial.subMaterials.push(subMaterial);
  69010. }
  69011. return newMultiMaterial;
  69012. };
  69013. MultiMaterial.prototype.serialize = function () {
  69014. var serializationObject = {};
  69015. serializationObject.name = this.name;
  69016. serializationObject.id = this.id;
  69017. if (BABYLON.Tags) {
  69018. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69019. }
  69020. serializationObject.materials = [];
  69021. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69022. var subMat = this.subMaterials[matIndex];
  69023. if (subMat) {
  69024. serializationObject.materials.push(subMat.id);
  69025. }
  69026. else {
  69027. serializationObject.materials.push(null);
  69028. }
  69029. }
  69030. return serializationObject;
  69031. };
  69032. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69033. var scene = this.getScene();
  69034. if (!scene) {
  69035. return;
  69036. }
  69037. var index = scene.multiMaterials.indexOf(this);
  69038. if (index >= 0) {
  69039. scene.multiMaterials.splice(index, 1);
  69040. }
  69041. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69042. };
  69043. return MultiMaterial;
  69044. }(BABYLON.Material));
  69045. BABYLON.MultiMaterial = MultiMaterial;
  69046. })(BABYLON || (BABYLON = {}));
  69047. //# sourceMappingURL=babylon.multiMaterial.js.map
  69048. var BABYLON;
  69049. (function (BABYLON) {
  69050. var FreeCameraTouchInput = /** @class */ (function () {
  69051. function FreeCameraTouchInput() {
  69052. this._offsetX = null;
  69053. this._offsetY = null;
  69054. this._pointerPressed = new Array();
  69055. this.touchAngularSensibility = 200000.0;
  69056. this.touchMoveSensibility = 250.0;
  69057. }
  69058. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69059. var _this = this;
  69060. var previousPosition = null;
  69061. if (this._pointerInput === undefined) {
  69062. this._onLostFocus = function (evt) {
  69063. _this._offsetX = null;
  69064. _this._offsetY = null;
  69065. };
  69066. this._pointerInput = function (p, s) {
  69067. var evt = p.event;
  69068. if (evt.pointerType === "mouse") {
  69069. return;
  69070. }
  69071. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69072. if (!noPreventDefault) {
  69073. evt.preventDefault();
  69074. }
  69075. _this._pointerPressed.push(evt.pointerId);
  69076. if (_this._pointerPressed.length !== 1) {
  69077. return;
  69078. }
  69079. previousPosition = {
  69080. x: evt.clientX,
  69081. y: evt.clientY
  69082. };
  69083. }
  69084. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69085. if (!noPreventDefault) {
  69086. evt.preventDefault();
  69087. }
  69088. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69089. if (index === -1) {
  69090. return;
  69091. }
  69092. _this._pointerPressed.splice(index, 1);
  69093. if (index != 0) {
  69094. return;
  69095. }
  69096. previousPosition = null;
  69097. _this._offsetX = null;
  69098. _this._offsetY = null;
  69099. }
  69100. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69101. if (!noPreventDefault) {
  69102. evt.preventDefault();
  69103. }
  69104. if (!previousPosition) {
  69105. return;
  69106. }
  69107. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69108. if (index != 0) {
  69109. return;
  69110. }
  69111. _this._offsetX = evt.clientX - previousPosition.x;
  69112. _this._offsetY = -(evt.clientY - previousPosition.y);
  69113. }
  69114. };
  69115. }
  69116. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69117. if (this._onLostFocus) {
  69118. element.addEventListener("blur", this._onLostFocus);
  69119. }
  69120. };
  69121. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69122. if (this._pointerInput && element) {
  69123. if (this._observer) {
  69124. this.camera.getScene().onPointerObservable.remove(this._observer);
  69125. this._observer = null;
  69126. }
  69127. if (this._onLostFocus) {
  69128. element.removeEventListener("blur", this._onLostFocus);
  69129. this._onLostFocus = null;
  69130. }
  69131. this._pointerPressed = [];
  69132. this._offsetX = null;
  69133. this._offsetY = null;
  69134. }
  69135. };
  69136. FreeCameraTouchInput.prototype.checkInputs = function () {
  69137. if (this._offsetX && this._offsetY) {
  69138. var camera = this.camera;
  69139. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69140. if (this._pointerPressed.length > 1) {
  69141. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69142. }
  69143. else {
  69144. var speed = camera._computeLocalCameraSpeed();
  69145. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69146. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69147. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69148. }
  69149. }
  69150. };
  69151. FreeCameraTouchInput.prototype.getClassName = function () {
  69152. return "FreeCameraTouchInput";
  69153. };
  69154. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69155. return "touch";
  69156. };
  69157. __decorate([
  69158. BABYLON.serialize()
  69159. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69160. __decorate([
  69161. BABYLON.serialize()
  69162. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69163. return FreeCameraTouchInput;
  69164. }());
  69165. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69166. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69167. })(BABYLON || (BABYLON = {}));
  69168. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69169. var BABYLON;
  69170. (function (BABYLON) {
  69171. // We're mainly based on the logic defined into the FreeCamera code
  69172. var TouchCamera = /** @class */ (function (_super) {
  69173. __extends(TouchCamera, _super);
  69174. //-- end properties for backward compatibility for inputs
  69175. function TouchCamera(name, position, scene) {
  69176. var _this = _super.call(this, name, position, scene) || this;
  69177. _this.inputs.addTouch();
  69178. _this._setupInputs();
  69179. return _this;
  69180. }
  69181. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69182. //-- Begin properties for backward compatibility for inputs
  69183. get: function () {
  69184. var touch = this.inputs.attached["touch"];
  69185. if (touch)
  69186. return touch.touchAngularSensibility;
  69187. return 0;
  69188. },
  69189. set: function (value) {
  69190. var touch = this.inputs.attached["touch"];
  69191. if (touch)
  69192. touch.touchAngularSensibility = value;
  69193. },
  69194. enumerable: true,
  69195. configurable: true
  69196. });
  69197. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69198. get: function () {
  69199. var touch = this.inputs.attached["touch"];
  69200. if (touch)
  69201. return touch.touchMoveSensibility;
  69202. return 0;
  69203. },
  69204. set: function (value) {
  69205. var touch = this.inputs.attached["touch"];
  69206. if (touch)
  69207. touch.touchMoveSensibility = value;
  69208. },
  69209. enumerable: true,
  69210. configurable: true
  69211. });
  69212. TouchCamera.prototype.getClassName = function () {
  69213. return "TouchCamera";
  69214. };
  69215. TouchCamera.prototype._setupInputs = function () {
  69216. var mouse = this.inputs.attached["mouse"];
  69217. if (mouse) {
  69218. mouse.touchEnabled = false;
  69219. }
  69220. };
  69221. return TouchCamera;
  69222. }(BABYLON.FreeCamera));
  69223. BABYLON.TouchCamera = TouchCamera;
  69224. })(BABYLON || (BABYLON = {}));
  69225. //# sourceMappingURL=babylon.touchCamera.js.map
  69226. var BABYLON;
  69227. (function (BABYLON) {
  69228. var ProceduralTexture = /** @class */ (function (_super) {
  69229. __extends(ProceduralTexture, _super);
  69230. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69231. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69232. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69233. if (isCube === void 0) { isCube = false; }
  69234. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69235. _this.isCube = isCube;
  69236. _this.isEnabled = true;
  69237. _this._currentRefreshId = -1;
  69238. _this._refreshRate = 1;
  69239. _this._vertexBuffers = {};
  69240. _this._uniforms = new Array();
  69241. _this._samplers = new Array();
  69242. _this._textures = {};
  69243. _this._floats = {};
  69244. _this._floatsArrays = {};
  69245. _this._colors3 = {};
  69246. _this._colors4 = {};
  69247. _this._vectors2 = {};
  69248. _this._vectors3 = {};
  69249. _this._matrices = {};
  69250. _this._fallbackTextureUsed = false;
  69251. scene.proceduralTextures.push(_this);
  69252. _this._engine = scene.getEngine();
  69253. _this.name = name;
  69254. _this.isRenderTarget = true;
  69255. _this._size = size;
  69256. _this._generateMipMaps = generateMipMaps;
  69257. _this.setFragment(fragment);
  69258. _this._fallbackTexture = fallbackTexture;
  69259. if (isCube) {
  69260. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69261. _this.setFloat("face", 0);
  69262. }
  69263. else {
  69264. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69265. }
  69266. // VBO
  69267. var vertices = [];
  69268. vertices.push(1, 1);
  69269. vertices.push(-1, 1);
  69270. vertices.push(-1, -1);
  69271. vertices.push(1, -1);
  69272. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69273. _this._createIndexBuffer();
  69274. return _this;
  69275. }
  69276. ProceduralTexture.prototype._createIndexBuffer = function () {
  69277. var engine = this._engine;
  69278. // Indices
  69279. var indices = [];
  69280. indices.push(0);
  69281. indices.push(1);
  69282. indices.push(2);
  69283. indices.push(0);
  69284. indices.push(2);
  69285. indices.push(3);
  69286. this._indexBuffer = engine.createIndexBuffer(indices);
  69287. };
  69288. ProceduralTexture.prototype._rebuild = function () {
  69289. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69290. if (vb) {
  69291. vb._rebuild();
  69292. }
  69293. this._createIndexBuffer();
  69294. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69295. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69296. }
  69297. };
  69298. ProceduralTexture.prototype.reset = function () {
  69299. if (this._effect === undefined) {
  69300. return;
  69301. }
  69302. var engine = this._engine;
  69303. engine._releaseEffect(this._effect);
  69304. };
  69305. ProceduralTexture.prototype.isReady = function () {
  69306. var _this = this;
  69307. var engine = this._engine;
  69308. var shaders;
  69309. if (!this._fragment) {
  69310. return false;
  69311. }
  69312. if (this._fallbackTextureUsed) {
  69313. return true;
  69314. }
  69315. if (this._fragment.fragmentElement !== undefined) {
  69316. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69317. }
  69318. else {
  69319. shaders = { vertex: "procedural", fragment: this._fragment };
  69320. }
  69321. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69322. _this.releaseInternalTexture();
  69323. if (_this._fallbackTexture) {
  69324. _this._texture = _this._fallbackTexture._texture;
  69325. if (_this._texture) {
  69326. _this._texture.incrementReferences();
  69327. }
  69328. }
  69329. _this._fallbackTextureUsed = true;
  69330. });
  69331. return this._effect.isReady();
  69332. };
  69333. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69334. this._currentRefreshId = -1;
  69335. };
  69336. ProceduralTexture.prototype.setFragment = function (fragment) {
  69337. this._fragment = fragment;
  69338. };
  69339. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69340. get: function () {
  69341. return this._refreshRate;
  69342. },
  69343. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69344. set: function (value) {
  69345. this._refreshRate = value;
  69346. this.resetRefreshCounter();
  69347. },
  69348. enumerable: true,
  69349. configurable: true
  69350. });
  69351. ProceduralTexture.prototype._shouldRender = function () {
  69352. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69353. return false;
  69354. }
  69355. if (this._fallbackTextureUsed) {
  69356. return false;
  69357. }
  69358. if (this._currentRefreshId === -1) { // At least render once
  69359. this._currentRefreshId = 1;
  69360. return true;
  69361. }
  69362. if (this.refreshRate === this._currentRefreshId) {
  69363. this._currentRefreshId = 1;
  69364. return true;
  69365. }
  69366. this._currentRefreshId++;
  69367. return false;
  69368. };
  69369. ProceduralTexture.prototype.getRenderSize = function () {
  69370. return this._size;
  69371. };
  69372. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69373. if (this._fallbackTextureUsed) {
  69374. return;
  69375. }
  69376. this.releaseInternalTexture();
  69377. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69378. // Update properties
  69379. this._size = size;
  69380. this._generateMipMaps = generateMipMaps;
  69381. };
  69382. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69383. if (this._uniforms.indexOf(uniformName) === -1) {
  69384. this._uniforms.push(uniformName);
  69385. }
  69386. };
  69387. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69388. if (this._samplers.indexOf(name) === -1) {
  69389. this._samplers.push(name);
  69390. }
  69391. this._textures[name] = texture;
  69392. return this;
  69393. };
  69394. ProceduralTexture.prototype.setFloat = function (name, value) {
  69395. this._checkUniform(name);
  69396. this._floats[name] = value;
  69397. return this;
  69398. };
  69399. ProceduralTexture.prototype.setFloats = function (name, value) {
  69400. this._checkUniform(name);
  69401. this._floatsArrays[name] = value;
  69402. return this;
  69403. };
  69404. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69405. this._checkUniform(name);
  69406. this._colors3[name] = value;
  69407. return this;
  69408. };
  69409. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69410. this._checkUniform(name);
  69411. this._colors4[name] = value;
  69412. return this;
  69413. };
  69414. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69415. this._checkUniform(name);
  69416. this._vectors2[name] = value;
  69417. return this;
  69418. };
  69419. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69420. this._checkUniform(name);
  69421. this._vectors3[name] = value;
  69422. return this;
  69423. };
  69424. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69425. this._checkUniform(name);
  69426. this._matrices[name] = value;
  69427. return this;
  69428. };
  69429. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69430. var scene = this.getScene();
  69431. if (!scene) {
  69432. return;
  69433. }
  69434. var engine = this._engine;
  69435. // Render
  69436. engine.enableEffect(this._effect);
  69437. engine.setState(false);
  69438. // Texture
  69439. for (var name in this._textures) {
  69440. this._effect.setTexture(name, this._textures[name]);
  69441. }
  69442. // Float
  69443. for (name in this._floats) {
  69444. this._effect.setFloat(name, this._floats[name]);
  69445. }
  69446. // Floats
  69447. for (name in this._floatsArrays) {
  69448. this._effect.setArray(name, this._floatsArrays[name]);
  69449. }
  69450. // Color3
  69451. for (name in this._colors3) {
  69452. this._effect.setColor3(name, this._colors3[name]);
  69453. }
  69454. // Color4
  69455. for (name in this._colors4) {
  69456. var color = this._colors4[name];
  69457. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69458. }
  69459. // Vector2
  69460. for (name in this._vectors2) {
  69461. this._effect.setVector2(name, this._vectors2[name]);
  69462. }
  69463. // Vector3
  69464. for (name in this._vectors3) {
  69465. this._effect.setVector3(name, this._vectors3[name]);
  69466. }
  69467. // Matrix
  69468. for (name in this._matrices) {
  69469. this._effect.setMatrix(name, this._matrices[name]);
  69470. }
  69471. if (!this._texture) {
  69472. return;
  69473. }
  69474. if (this.isCube) {
  69475. for (var face = 0; face < 6; face++) {
  69476. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69477. // VBOs
  69478. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69479. this._effect.setFloat("face", face);
  69480. // Clear
  69481. engine.clear(scene.clearColor, true, true, true);
  69482. // Draw order
  69483. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69484. // Mipmaps
  69485. if (face === 5) {
  69486. engine.generateMipMapsForCubemap(this._texture);
  69487. }
  69488. }
  69489. }
  69490. else {
  69491. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69492. // VBOs
  69493. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69494. // Clear
  69495. engine.clear(scene.clearColor, true, true, true);
  69496. // Draw order
  69497. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69498. }
  69499. // Unbind
  69500. engine.unBindFramebuffer(this._texture, this.isCube);
  69501. if (this.onGenerated) {
  69502. this.onGenerated();
  69503. }
  69504. };
  69505. ProceduralTexture.prototype.clone = function () {
  69506. var textureSize = this.getSize();
  69507. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69508. // Base texture
  69509. newTexture.hasAlpha = this.hasAlpha;
  69510. newTexture.level = this.level;
  69511. // RenderTarget Texture
  69512. newTexture.coordinatesMode = this.coordinatesMode;
  69513. return newTexture;
  69514. };
  69515. ProceduralTexture.prototype.dispose = function () {
  69516. var scene = this.getScene();
  69517. if (!scene) {
  69518. return;
  69519. }
  69520. var index = scene.proceduralTextures.indexOf(this);
  69521. if (index >= 0) {
  69522. scene.proceduralTextures.splice(index, 1);
  69523. }
  69524. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69525. if (vertexBuffer) {
  69526. vertexBuffer.dispose();
  69527. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69528. }
  69529. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69530. this._indexBuffer = null;
  69531. }
  69532. _super.prototype.dispose.call(this);
  69533. };
  69534. __decorate([
  69535. BABYLON.serialize()
  69536. ], ProceduralTexture.prototype, "_size", void 0);
  69537. __decorate([
  69538. BABYLON.serialize()
  69539. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  69540. __decorate([
  69541. BABYLON.serialize()
  69542. ], ProceduralTexture.prototype, "isEnabled", void 0);
  69543. __decorate([
  69544. BABYLON.serialize()
  69545. ], ProceduralTexture.prototype, "refreshRate", null);
  69546. return ProceduralTexture;
  69547. }(BABYLON.Texture));
  69548. BABYLON.ProceduralTexture = ProceduralTexture;
  69549. })(BABYLON || (BABYLON = {}));
  69550. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69551. var BABYLON;
  69552. (function (BABYLON) {
  69553. var CustomProceduralTexture = /** @class */ (function (_super) {
  69554. __extends(CustomProceduralTexture, _super);
  69555. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69556. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69557. _this._animate = true;
  69558. _this._time = 0;
  69559. _this._texturePath = texturePath;
  69560. //Try to load json
  69561. _this.loadJson(texturePath);
  69562. _this.refreshRate = 1;
  69563. return _this;
  69564. }
  69565. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69566. var _this = this;
  69567. var noConfigFile = function () {
  69568. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69569. try {
  69570. _this.setFragment(_this._texturePath);
  69571. }
  69572. catch (ex) {
  69573. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69574. }
  69575. };
  69576. var configFileUrl = jsonUrl + "/config.json";
  69577. var xhr = new XMLHttpRequest();
  69578. xhr.open("GET", configFileUrl, true);
  69579. xhr.addEventListener("load", function () {
  69580. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69581. try {
  69582. _this._config = JSON.parse(xhr.response);
  69583. _this.updateShaderUniforms();
  69584. _this.updateTextures();
  69585. _this.setFragment(_this._texturePath + "/custom");
  69586. _this._animate = _this._config.animate;
  69587. _this.refreshRate = _this._config.refreshrate;
  69588. }
  69589. catch (ex) {
  69590. noConfigFile();
  69591. }
  69592. }
  69593. else {
  69594. noConfigFile();
  69595. }
  69596. }, false);
  69597. xhr.addEventListener("error", function () {
  69598. noConfigFile();
  69599. }, false);
  69600. try {
  69601. xhr.send();
  69602. }
  69603. catch (ex) {
  69604. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69605. }
  69606. };
  69607. CustomProceduralTexture.prototype.isReady = function () {
  69608. if (!_super.prototype.isReady.call(this)) {
  69609. return false;
  69610. }
  69611. for (var name in this._textures) {
  69612. var texture = this._textures[name];
  69613. if (!texture.isReady()) {
  69614. return false;
  69615. }
  69616. }
  69617. return true;
  69618. };
  69619. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69620. var scene = this.getScene();
  69621. if (this._animate && scene) {
  69622. this._time += scene.getAnimationRatio() * 0.03;
  69623. this.updateShaderUniforms();
  69624. }
  69625. _super.prototype.render.call(this, useCameraPostProcess);
  69626. };
  69627. CustomProceduralTexture.prototype.updateTextures = function () {
  69628. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69629. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69630. }
  69631. };
  69632. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69633. if (this._config) {
  69634. for (var j = 0; j < this._config.uniforms.length; j++) {
  69635. var uniform = this._config.uniforms[j];
  69636. switch (uniform.type) {
  69637. case "float":
  69638. this.setFloat(uniform.name, uniform.value);
  69639. break;
  69640. case "color3":
  69641. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69642. break;
  69643. case "color4":
  69644. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69645. break;
  69646. case "vector2":
  69647. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69648. break;
  69649. case "vector3":
  69650. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69651. break;
  69652. }
  69653. }
  69654. }
  69655. this.setFloat("time", this._time);
  69656. };
  69657. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69658. get: function () {
  69659. return this._animate;
  69660. },
  69661. set: function (value) {
  69662. this._animate = value;
  69663. },
  69664. enumerable: true,
  69665. configurable: true
  69666. });
  69667. return CustomProceduralTexture;
  69668. }(BABYLON.ProceduralTexture));
  69669. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69670. })(BABYLON || (BABYLON = {}));
  69671. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69672. var BABYLON;
  69673. (function (BABYLON) {
  69674. var FreeCameraGamepadInput = /** @class */ (function () {
  69675. function FreeCameraGamepadInput() {
  69676. this.gamepadAngularSensibility = 200;
  69677. this.gamepadMoveSensibility = 40;
  69678. // private members
  69679. this._cameraTransform = BABYLON.Matrix.Identity();
  69680. this._deltaTransform = BABYLON.Vector3.Zero();
  69681. this._vector3 = BABYLON.Vector3.Zero();
  69682. this._vector2 = BABYLON.Vector2.Zero();
  69683. }
  69684. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69685. var _this = this;
  69686. var manager = this.camera.getScene().gamepadManager;
  69687. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69688. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69689. // prioritize XBOX gamepads.
  69690. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69691. _this.gamepad = gamepad;
  69692. }
  69693. }
  69694. });
  69695. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69696. if (_this.gamepad === gamepad) {
  69697. _this.gamepad = null;
  69698. }
  69699. });
  69700. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69701. };
  69702. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69703. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69704. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69705. this.gamepad = null;
  69706. };
  69707. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69708. if (this.gamepad && this.gamepad.leftStick) {
  69709. var camera = this.camera;
  69710. var LSValues = this.gamepad.leftStick;
  69711. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69712. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69713. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69714. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69715. var RSValues = this.gamepad.rightStick;
  69716. if (RSValues) {
  69717. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69718. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69719. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69720. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69721. }
  69722. else {
  69723. RSValues = { x: 0, y: 0 };
  69724. }
  69725. if (!camera.rotationQuaternion) {
  69726. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69727. }
  69728. else {
  69729. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69730. }
  69731. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69732. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69733. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69734. camera.cameraDirection.addInPlace(this._deltaTransform);
  69735. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69736. camera.cameraRotation.addInPlace(this._vector2);
  69737. }
  69738. };
  69739. FreeCameraGamepadInput.prototype.getClassName = function () {
  69740. return "FreeCameraGamepadInput";
  69741. };
  69742. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69743. return "gamepad";
  69744. };
  69745. __decorate([
  69746. BABYLON.serialize()
  69747. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69748. __decorate([
  69749. BABYLON.serialize()
  69750. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69751. return FreeCameraGamepadInput;
  69752. }());
  69753. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69754. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69755. })(BABYLON || (BABYLON = {}));
  69756. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69757. var BABYLON;
  69758. (function (BABYLON) {
  69759. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69760. function ArcRotateCameraGamepadInput() {
  69761. this.gamepadRotationSensibility = 80;
  69762. this.gamepadMoveSensibility = 40;
  69763. }
  69764. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69765. var _this = this;
  69766. var manager = this.camera.getScene().gamepadManager;
  69767. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69768. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69769. // prioritize XBOX gamepads.
  69770. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69771. _this.gamepad = gamepad;
  69772. }
  69773. }
  69774. });
  69775. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69776. if (_this.gamepad === gamepad) {
  69777. _this.gamepad = null;
  69778. }
  69779. });
  69780. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69781. };
  69782. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69783. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69784. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69785. this.gamepad = null;
  69786. };
  69787. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69788. if (this.gamepad) {
  69789. var camera = this.camera;
  69790. var RSValues = this.gamepad.rightStick;
  69791. if (RSValues) {
  69792. if (RSValues.x != 0) {
  69793. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69794. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69795. camera.inertialAlphaOffset += normalizedRX;
  69796. }
  69797. }
  69798. if (RSValues.y != 0) {
  69799. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69800. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69801. camera.inertialBetaOffset += normalizedRY;
  69802. }
  69803. }
  69804. }
  69805. var LSValues = this.gamepad.leftStick;
  69806. if (LSValues && LSValues.y != 0) {
  69807. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69808. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69809. this.camera.inertialRadiusOffset -= normalizedLY;
  69810. }
  69811. }
  69812. }
  69813. };
  69814. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69815. return "ArcRotateCameraGamepadInput";
  69816. };
  69817. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69818. return "gamepad";
  69819. };
  69820. __decorate([
  69821. BABYLON.serialize()
  69822. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69823. __decorate([
  69824. BABYLON.serialize()
  69825. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69826. return ArcRotateCameraGamepadInput;
  69827. }());
  69828. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69829. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69830. })(BABYLON || (BABYLON = {}));
  69831. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69832. var BABYLON;
  69833. (function (BABYLON) {
  69834. var GamepadManager = /** @class */ (function () {
  69835. function GamepadManager(_scene) {
  69836. var _this = this;
  69837. this._scene = _scene;
  69838. this._babylonGamepads = [];
  69839. this._oneGamepadConnected = false;
  69840. this._isMonitoring = false;
  69841. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69842. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69843. this._gamepadEventSupported = false;
  69844. }
  69845. else {
  69846. this._gamepadEventSupported = 'GamepadEvent' in window;
  69847. this._gamepadSupport = (navigator.getGamepads ||
  69848. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69849. }
  69850. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69851. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69852. for (var i in _this._babylonGamepads) {
  69853. var gamepad = _this._babylonGamepads[i];
  69854. if (gamepad && gamepad._isConnected) {
  69855. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69856. }
  69857. }
  69858. });
  69859. this._onGamepadConnectedEvent = function (evt) {
  69860. var gamepad = evt.gamepad;
  69861. if (gamepad.index in _this._babylonGamepads) {
  69862. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69863. return;
  69864. }
  69865. }
  69866. var newGamepad;
  69867. if (_this._babylonGamepads[gamepad.index]) {
  69868. newGamepad = _this._babylonGamepads[gamepad.index];
  69869. newGamepad.browserGamepad = gamepad;
  69870. newGamepad._isConnected = true;
  69871. }
  69872. else {
  69873. newGamepad = _this._addNewGamepad(gamepad);
  69874. }
  69875. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69876. _this._startMonitoringGamepads();
  69877. };
  69878. this._onGamepadDisconnectedEvent = function (evt) {
  69879. var gamepad = evt.gamepad;
  69880. // Remove the gamepad from the list of gamepads to monitor.
  69881. for (var i in _this._babylonGamepads) {
  69882. if (_this._babylonGamepads[i].index === gamepad.index) {
  69883. var disconnectedGamepad = _this._babylonGamepads[i];
  69884. disconnectedGamepad._isConnected = false;
  69885. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69886. break;
  69887. }
  69888. }
  69889. };
  69890. if (this._gamepadSupport) {
  69891. //first add already-connected gamepads
  69892. this._updateGamepadObjects();
  69893. if (this._babylonGamepads.length) {
  69894. this._startMonitoringGamepads();
  69895. }
  69896. // Checking if the gamepad connected event is supported (like in Firefox)
  69897. if (this._gamepadEventSupported) {
  69898. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69899. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69900. }
  69901. else {
  69902. this._startMonitoringGamepads();
  69903. }
  69904. }
  69905. }
  69906. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69907. get: function () {
  69908. return this._babylonGamepads;
  69909. },
  69910. enumerable: true,
  69911. configurable: true
  69912. });
  69913. GamepadManager.prototype.getGamepadByType = function (type) {
  69914. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69915. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69916. var gamepad = _a[_i];
  69917. if (gamepad && gamepad.type === type) {
  69918. return gamepad;
  69919. }
  69920. }
  69921. return null;
  69922. };
  69923. GamepadManager.prototype.dispose = function () {
  69924. if (this._gamepadEventSupported) {
  69925. if (this._onGamepadConnectedEvent) {
  69926. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69927. }
  69928. if (this._onGamepadDisconnectedEvent) {
  69929. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69930. }
  69931. this._onGamepadConnectedEvent = null;
  69932. this._onGamepadDisconnectedEvent = null;
  69933. }
  69934. this._babylonGamepads.forEach(function (gamepad) {
  69935. gamepad.dispose();
  69936. });
  69937. this.onGamepadConnectedObservable.clear();
  69938. this.onGamepadDisconnectedObservable.clear();
  69939. this._oneGamepadConnected = false;
  69940. this._stopMonitoringGamepads();
  69941. this._babylonGamepads = [];
  69942. };
  69943. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69944. if (!this._oneGamepadConnected) {
  69945. this._oneGamepadConnected = true;
  69946. }
  69947. var newGamepad;
  69948. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69949. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69950. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69951. }
  69952. // if pose is supported, use the (WebVR) pose enabled controller
  69953. else if (gamepad.pose) {
  69954. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69955. }
  69956. else {
  69957. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69958. }
  69959. this._babylonGamepads[newGamepad.index] = newGamepad;
  69960. return newGamepad;
  69961. };
  69962. GamepadManager.prototype._startMonitoringGamepads = function () {
  69963. if (!this._isMonitoring) {
  69964. this._isMonitoring = true;
  69965. //back-comp
  69966. if (!this._scene) {
  69967. this._checkGamepadsStatus();
  69968. }
  69969. }
  69970. };
  69971. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69972. this._isMonitoring = false;
  69973. };
  69974. GamepadManager.prototype._checkGamepadsStatus = function () {
  69975. var _this = this;
  69976. // Hack to be compatible Chrome
  69977. this._updateGamepadObjects();
  69978. for (var i in this._babylonGamepads) {
  69979. var gamepad = this._babylonGamepads[i];
  69980. if (!gamepad || !gamepad.isConnected) {
  69981. continue;
  69982. }
  69983. gamepad.update();
  69984. }
  69985. if (this._isMonitoring && !this._scene) {
  69986. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69987. }
  69988. };
  69989. // This function is called only on Chrome, which does not properly support
  69990. // connection/disconnection events and forces you to recopy again the gamepad object
  69991. GamepadManager.prototype._updateGamepadObjects = function () {
  69992. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69993. for (var i = 0; i < gamepads.length; i++) {
  69994. var gamepad = gamepads[i];
  69995. if (gamepad) {
  69996. if (!this._babylonGamepads[gamepad.index]) {
  69997. var newGamepad = this._addNewGamepad(gamepad);
  69998. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69999. }
  70000. else {
  70001. // Forced to copy again this object for Chrome for unknown reason
  70002. this._babylonGamepads[i].browserGamepad = gamepad;
  70003. if (!this._babylonGamepads[i].isConnected) {
  70004. this._babylonGamepads[i]._isConnected = true;
  70005. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70006. }
  70007. }
  70008. }
  70009. }
  70010. };
  70011. return GamepadManager;
  70012. }());
  70013. BABYLON.GamepadManager = GamepadManager;
  70014. })(BABYLON || (BABYLON = {}));
  70015. //# sourceMappingURL=babylon.gamepadManager.js.map
  70016. var BABYLON;
  70017. (function (BABYLON) {
  70018. var StickValues = /** @class */ (function () {
  70019. function StickValues(x, y) {
  70020. this.x = x;
  70021. this.y = y;
  70022. }
  70023. return StickValues;
  70024. }());
  70025. BABYLON.StickValues = StickValues;
  70026. var Gamepad = /** @class */ (function () {
  70027. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70028. if (leftStickX === void 0) { leftStickX = 0; }
  70029. if (leftStickY === void 0) { leftStickY = 1; }
  70030. if (rightStickX === void 0) { rightStickX = 2; }
  70031. if (rightStickY === void 0) { rightStickY = 3; }
  70032. this.id = id;
  70033. this.index = index;
  70034. this.browserGamepad = browserGamepad;
  70035. this._isConnected = true;
  70036. this._invertLeftStickY = false;
  70037. this.type = Gamepad.GAMEPAD;
  70038. this._leftStickAxisX = leftStickX;
  70039. this._leftStickAxisY = leftStickY;
  70040. this._rightStickAxisX = rightStickX;
  70041. this._rightStickAxisY = rightStickY;
  70042. if (this.browserGamepad.axes.length >= 2) {
  70043. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70044. }
  70045. if (this.browserGamepad.axes.length >= 4) {
  70046. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70047. }
  70048. }
  70049. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70050. get: function () {
  70051. return this._isConnected;
  70052. },
  70053. enumerable: true,
  70054. configurable: true
  70055. });
  70056. Gamepad.prototype.onleftstickchanged = function (callback) {
  70057. this._onleftstickchanged = callback;
  70058. };
  70059. Gamepad.prototype.onrightstickchanged = function (callback) {
  70060. this._onrightstickchanged = callback;
  70061. };
  70062. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70063. get: function () {
  70064. return this._leftStick;
  70065. },
  70066. set: function (newValues) {
  70067. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70068. this._onleftstickchanged(newValues);
  70069. }
  70070. this._leftStick = newValues;
  70071. },
  70072. enumerable: true,
  70073. configurable: true
  70074. });
  70075. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70076. get: function () {
  70077. return this._rightStick;
  70078. },
  70079. set: function (newValues) {
  70080. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70081. this._onrightstickchanged(newValues);
  70082. }
  70083. this._rightStick = newValues;
  70084. },
  70085. enumerable: true,
  70086. configurable: true
  70087. });
  70088. Gamepad.prototype.update = function () {
  70089. if (this._leftStick) {
  70090. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70091. if (this._invertLeftStickY) {
  70092. this.leftStick.y *= -1;
  70093. }
  70094. }
  70095. if (this._rightStick) {
  70096. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70097. }
  70098. };
  70099. Gamepad.prototype.dispose = function () {
  70100. };
  70101. Gamepad.GAMEPAD = 0;
  70102. Gamepad.GENERIC = 1;
  70103. Gamepad.XBOX = 2;
  70104. Gamepad.POSE_ENABLED = 3;
  70105. return Gamepad;
  70106. }());
  70107. BABYLON.Gamepad = Gamepad;
  70108. var GenericPad = /** @class */ (function (_super) {
  70109. __extends(GenericPad, _super);
  70110. function GenericPad(id, index, browserGamepad) {
  70111. var _this = _super.call(this, id, index, browserGamepad) || this;
  70112. _this.onButtonDownObservable = new BABYLON.Observable();
  70113. _this.onButtonUpObservable = new BABYLON.Observable();
  70114. _this.type = Gamepad.GENERIC;
  70115. _this._buttons = new Array(browserGamepad.buttons.length);
  70116. return _this;
  70117. }
  70118. GenericPad.prototype.onbuttondown = function (callback) {
  70119. this._onbuttondown = callback;
  70120. };
  70121. GenericPad.prototype.onbuttonup = function (callback) {
  70122. this._onbuttonup = callback;
  70123. };
  70124. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70125. if (newValue !== currentValue) {
  70126. if (newValue === 1) {
  70127. if (this._onbuttondown) {
  70128. this._onbuttondown(buttonIndex);
  70129. }
  70130. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70131. }
  70132. if (newValue === 0) {
  70133. if (this._onbuttonup) {
  70134. this._onbuttonup(buttonIndex);
  70135. }
  70136. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70137. }
  70138. }
  70139. return newValue;
  70140. };
  70141. GenericPad.prototype.update = function () {
  70142. _super.prototype.update.call(this);
  70143. for (var index = 0; index < this._buttons.length; index++) {
  70144. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70145. }
  70146. };
  70147. GenericPad.prototype.dispose = function () {
  70148. _super.prototype.dispose.call(this);
  70149. this.onButtonDownObservable.clear();
  70150. this.onButtonUpObservable.clear();
  70151. };
  70152. return GenericPad;
  70153. }(Gamepad));
  70154. BABYLON.GenericPad = GenericPad;
  70155. })(BABYLON || (BABYLON = {}));
  70156. //# sourceMappingURL=babylon.gamepad.js.map
  70157. var BABYLON;
  70158. (function (BABYLON) {
  70159. /**
  70160. * Defines supported buttons for XBox360 compatible gamepads
  70161. */
  70162. var Xbox360Button;
  70163. (function (Xbox360Button) {
  70164. /** A */
  70165. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70166. /** B */
  70167. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70168. /** X */
  70169. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70170. /** Y */
  70171. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70172. /** Start */
  70173. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70174. /** Back */
  70175. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70176. /** Left button */
  70177. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70178. /** Right button */
  70179. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70180. /** Left stick */
  70181. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70182. /** Right stick */
  70183. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70184. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70185. /** Defines values for XBox360 DPad */
  70186. var Xbox360Dpad;
  70187. (function (Xbox360Dpad) {
  70188. /** Up */
  70189. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70190. /** Down */
  70191. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70192. /** Left */
  70193. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70194. /** Right */
  70195. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70196. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70197. /**
  70198. * Defines a XBox360 gamepad
  70199. */
  70200. var Xbox360Pad = /** @class */ (function (_super) {
  70201. __extends(Xbox360Pad, _super);
  70202. /**
  70203. * Creates a new XBox360 gamepad object
  70204. * @param id defines the id of this gamepad
  70205. * @param index defines its index
  70206. * @param gamepad defines the internal HTML gamepad object
  70207. * @param xboxOne defines if it is a XBox One gamepad
  70208. */
  70209. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70210. if (xboxOne === void 0) { xboxOne = false; }
  70211. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70212. _this._leftTrigger = 0;
  70213. _this._rightTrigger = 0;
  70214. /** Observable raised when a button is pressed */
  70215. _this.onButtonDownObservable = new BABYLON.Observable();
  70216. /** Observable raised when a button is released */
  70217. _this.onButtonUpObservable = new BABYLON.Observable();
  70218. /** Observable raised when a pad is pressed */
  70219. _this.onPadDownObservable = new BABYLON.Observable();
  70220. /** Observable raised when a pad is released */
  70221. _this.onPadUpObservable = new BABYLON.Observable();
  70222. _this._buttonA = 0;
  70223. _this._buttonB = 0;
  70224. _this._buttonX = 0;
  70225. _this._buttonY = 0;
  70226. _this._buttonBack = 0;
  70227. _this._buttonStart = 0;
  70228. _this._buttonLB = 0;
  70229. _this._buttonRB = 0;
  70230. _this._buttonLeftStick = 0;
  70231. _this._buttonRightStick = 0;
  70232. _this._dPadUp = 0;
  70233. _this._dPadDown = 0;
  70234. _this._dPadLeft = 0;
  70235. _this._dPadRight = 0;
  70236. _this._isXboxOnePad = false;
  70237. _this.type = BABYLON.Gamepad.XBOX;
  70238. _this._isXboxOnePad = xboxOne;
  70239. return _this;
  70240. }
  70241. /**
  70242. * Defines the callback to call when left trigger is pressed
  70243. * @param callback defines the callback to use
  70244. */
  70245. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70246. this._onlefttriggerchanged = callback;
  70247. };
  70248. /**
  70249. * Defines the callback to call when right trigger is pressed
  70250. * @param callback defines the callback to use
  70251. */
  70252. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70253. this._onrighttriggerchanged = callback;
  70254. };
  70255. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70256. /**
  70257. * Gets or sets left trigger value
  70258. */
  70259. get: function () {
  70260. return this._leftTrigger;
  70261. },
  70262. set: function (newValue) {
  70263. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70264. this._onlefttriggerchanged(newValue);
  70265. }
  70266. this._leftTrigger = newValue;
  70267. },
  70268. enumerable: true,
  70269. configurable: true
  70270. });
  70271. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70272. /**
  70273. * Gets or sets right trigger value
  70274. */
  70275. get: function () {
  70276. return this._rightTrigger;
  70277. },
  70278. set: function (newValue) {
  70279. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70280. this._onrighttriggerchanged(newValue);
  70281. }
  70282. this._rightTrigger = newValue;
  70283. },
  70284. enumerable: true,
  70285. configurable: true
  70286. });
  70287. /**
  70288. * Defines the callback to call when a button is pressed
  70289. * @param callback defines the callback to use
  70290. */
  70291. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70292. this._onbuttondown = callback;
  70293. };
  70294. /**
  70295. * Defines the callback to call when a button is released
  70296. * @param callback defines the callback to use
  70297. */
  70298. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70299. this._onbuttonup = callback;
  70300. };
  70301. /**
  70302. * Defines the callback to call when a pad is pressed
  70303. * @param callback defines the callback to use
  70304. */
  70305. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70306. this._ondpaddown = callback;
  70307. };
  70308. /**
  70309. * Defines the callback to call when a pad is released
  70310. * @param callback defines the callback to use
  70311. */
  70312. Xbox360Pad.prototype.ondpadup = function (callback) {
  70313. this._ondpadup = callback;
  70314. };
  70315. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70316. if (newValue !== currentValue) {
  70317. if (newValue === 1) {
  70318. if (this._onbuttondown) {
  70319. this._onbuttondown(buttonType);
  70320. }
  70321. this.onButtonDownObservable.notifyObservers(buttonType);
  70322. }
  70323. if (newValue === 0) {
  70324. if (this._onbuttonup) {
  70325. this._onbuttonup(buttonType);
  70326. }
  70327. this.onButtonUpObservable.notifyObservers(buttonType);
  70328. }
  70329. }
  70330. return newValue;
  70331. };
  70332. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70333. if (newValue !== currentValue) {
  70334. if (newValue === 1) {
  70335. if (this._ondpaddown) {
  70336. this._ondpaddown(buttonType);
  70337. }
  70338. this.onPadDownObservable.notifyObservers(buttonType);
  70339. }
  70340. if (newValue === 0) {
  70341. if (this._ondpadup) {
  70342. this._ondpadup(buttonType);
  70343. }
  70344. this.onPadUpObservable.notifyObservers(buttonType);
  70345. }
  70346. }
  70347. return newValue;
  70348. };
  70349. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70350. /** Gets or sets value of A button */
  70351. get: function () {
  70352. return this._buttonA;
  70353. },
  70354. set: function (value) {
  70355. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70356. },
  70357. enumerable: true,
  70358. configurable: true
  70359. });
  70360. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70361. /** Gets or sets value of B button */
  70362. get: function () {
  70363. return this._buttonB;
  70364. },
  70365. set: function (value) {
  70366. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70367. },
  70368. enumerable: true,
  70369. configurable: true
  70370. });
  70371. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70372. /** Gets or sets value of X button */
  70373. get: function () {
  70374. return this._buttonX;
  70375. },
  70376. set: function (value) {
  70377. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70378. },
  70379. enumerable: true,
  70380. configurable: true
  70381. });
  70382. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70383. /** Gets or sets value of Y button */
  70384. get: function () {
  70385. return this._buttonY;
  70386. },
  70387. set: function (value) {
  70388. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70389. },
  70390. enumerable: true,
  70391. configurable: true
  70392. });
  70393. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70394. /** Gets or sets value of Start button */
  70395. get: function () {
  70396. return this._buttonStart;
  70397. },
  70398. set: function (value) {
  70399. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70400. },
  70401. enumerable: true,
  70402. configurable: true
  70403. });
  70404. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70405. /** Gets or sets value of Back button */
  70406. get: function () {
  70407. return this._buttonBack;
  70408. },
  70409. set: function (value) {
  70410. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70411. },
  70412. enumerable: true,
  70413. configurable: true
  70414. });
  70415. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70416. /** Gets or sets value of Left button */
  70417. get: function () {
  70418. return this._buttonLB;
  70419. },
  70420. set: function (value) {
  70421. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70422. },
  70423. enumerable: true,
  70424. configurable: true
  70425. });
  70426. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70427. /** Gets or sets value of Right button */
  70428. get: function () {
  70429. return this._buttonRB;
  70430. },
  70431. set: function (value) {
  70432. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70433. },
  70434. enumerable: true,
  70435. configurable: true
  70436. });
  70437. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70438. /** Gets or sets value of left stick */
  70439. get: function () {
  70440. return this._buttonLeftStick;
  70441. },
  70442. set: function (value) {
  70443. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70444. },
  70445. enumerable: true,
  70446. configurable: true
  70447. });
  70448. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70449. /** Gets or sets value of right stick */
  70450. get: function () {
  70451. return this._buttonRightStick;
  70452. },
  70453. set: function (value) {
  70454. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70455. },
  70456. enumerable: true,
  70457. configurable: true
  70458. });
  70459. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70460. /** Gets or sets value of DPad up */
  70461. get: function () {
  70462. return this._dPadUp;
  70463. },
  70464. set: function (value) {
  70465. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70466. },
  70467. enumerable: true,
  70468. configurable: true
  70469. });
  70470. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70471. /** Gets or sets value of DPad down */
  70472. get: function () {
  70473. return this._dPadDown;
  70474. },
  70475. set: function (value) {
  70476. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70477. },
  70478. enumerable: true,
  70479. configurable: true
  70480. });
  70481. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70482. /** Gets or sets value of DPad left */
  70483. get: function () {
  70484. return this._dPadLeft;
  70485. },
  70486. set: function (value) {
  70487. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70488. },
  70489. enumerable: true,
  70490. configurable: true
  70491. });
  70492. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70493. /** Gets or sets value of DPad right */
  70494. get: function () {
  70495. return this._dPadRight;
  70496. },
  70497. set: function (value) {
  70498. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70499. },
  70500. enumerable: true,
  70501. configurable: true
  70502. });
  70503. /**
  70504. * Force the gamepad to synchronize with device values
  70505. */
  70506. Xbox360Pad.prototype.update = function () {
  70507. _super.prototype.update.call(this);
  70508. if (this._isXboxOnePad) {
  70509. this.buttonA = this.browserGamepad.buttons[0].value;
  70510. this.buttonB = this.browserGamepad.buttons[1].value;
  70511. this.buttonX = this.browserGamepad.buttons[2].value;
  70512. this.buttonY = this.browserGamepad.buttons[3].value;
  70513. this.buttonLB = this.browserGamepad.buttons[4].value;
  70514. this.buttonRB = this.browserGamepad.buttons[5].value;
  70515. this.leftTrigger = this.browserGamepad.axes[2];
  70516. this.rightTrigger = this.browserGamepad.axes[5];
  70517. this.buttonBack = this.browserGamepad.buttons[9].value;
  70518. this.buttonStart = this.browserGamepad.buttons[8].value;
  70519. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70520. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70521. this.dPadUp = this.browserGamepad.buttons[11].value;
  70522. this.dPadDown = this.browserGamepad.buttons[12].value;
  70523. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70524. this.dPadRight = this.browserGamepad.buttons[14].value;
  70525. }
  70526. else {
  70527. this.buttonA = this.browserGamepad.buttons[0].value;
  70528. this.buttonB = this.browserGamepad.buttons[1].value;
  70529. this.buttonX = this.browserGamepad.buttons[2].value;
  70530. this.buttonY = this.browserGamepad.buttons[3].value;
  70531. this.buttonLB = this.browserGamepad.buttons[4].value;
  70532. this.buttonRB = this.browserGamepad.buttons[5].value;
  70533. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70534. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70535. this.buttonBack = this.browserGamepad.buttons[8].value;
  70536. this.buttonStart = this.browserGamepad.buttons[9].value;
  70537. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70538. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70539. this.dPadUp = this.browserGamepad.buttons[12].value;
  70540. this.dPadDown = this.browserGamepad.buttons[13].value;
  70541. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70542. this.dPadRight = this.browserGamepad.buttons[15].value;
  70543. }
  70544. };
  70545. Xbox360Pad.prototype.dispose = function () {
  70546. _super.prototype.dispose.call(this);
  70547. this.onButtonDownObservable.clear();
  70548. this.onButtonUpObservable.clear();
  70549. this.onPadDownObservable.clear();
  70550. this.onPadUpObservable.clear();
  70551. };
  70552. return Xbox360Pad;
  70553. }(BABYLON.Gamepad));
  70554. BABYLON.Xbox360Pad = Xbox360Pad;
  70555. })(BABYLON || (BABYLON = {}));
  70556. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70557. var BABYLON;
  70558. (function (BABYLON) {
  70559. /**
  70560. * Defines the types of pose enabled controllers that are supported
  70561. */
  70562. var PoseEnabledControllerType;
  70563. (function (PoseEnabledControllerType) {
  70564. /**
  70565. * HTC Vive
  70566. */
  70567. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70568. /**
  70569. * Oculus Rift
  70570. */
  70571. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70572. /**
  70573. * Windows mixed reality
  70574. */
  70575. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70576. /**
  70577. * Samsung gear VR
  70578. */
  70579. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70580. /**
  70581. * Google Daydream
  70582. */
  70583. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70584. /**
  70585. * Generic
  70586. */
  70587. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70588. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70589. /**
  70590. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70591. */
  70592. var PoseEnabledControllerHelper = /** @class */ (function () {
  70593. function PoseEnabledControllerHelper() {
  70594. }
  70595. /**
  70596. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70597. * @param vrGamepad the gamepad to initialized
  70598. * @returns a vr controller of the type the gamepad identified as
  70599. */
  70600. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70601. // Oculus Touch
  70602. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70603. return new BABYLON.OculusTouchController(vrGamepad);
  70604. }
  70605. // Windows Mixed Reality controllers
  70606. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70607. return new BABYLON.WindowsMotionController(vrGamepad);
  70608. }
  70609. // HTC Vive
  70610. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70611. return new BABYLON.ViveController(vrGamepad);
  70612. }
  70613. // Samsung/Oculus Gear VR or Oculus Go
  70614. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  70615. return new BABYLON.GearVRController(vrGamepad);
  70616. }
  70617. // Google Daydream
  70618. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70619. return new BABYLON.DaydreamController(vrGamepad);
  70620. }
  70621. // Generic
  70622. else {
  70623. return new BABYLON.GenericController(vrGamepad);
  70624. }
  70625. };
  70626. return PoseEnabledControllerHelper;
  70627. }());
  70628. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70629. /**
  70630. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70631. */
  70632. var PoseEnabledController = /** @class */ (function (_super) {
  70633. __extends(PoseEnabledController, _super);
  70634. /**
  70635. * Creates a new PoseEnabledController from a gamepad
  70636. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70637. */
  70638. function PoseEnabledController(browserGamepad) {
  70639. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70640. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70641. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70642. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70643. /**
  70644. * The device position in babylon space
  70645. */
  70646. _this.devicePosition = BABYLON.Vector3.Zero();
  70647. /**
  70648. * The device rotation in babylon space
  70649. */
  70650. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70651. /**
  70652. * The scale factor of the device in babylon space
  70653. */
  70654. _this.deviceScaleFactor = 1;
  70655. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70656. /**
  70657. * Internal, matrix used to convert room space to babylon space
  70658. */
  70659. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70660. /**
  70661. * Node to be used when casting a ray from the controller
  70662. */
  70663. _this._pointingPoseNode = null;
  70664. _this._workingMatrix = BABYLON.Matrix.Identity();
  70665. /**
  70666. * @hidden
  70667. */
  70668. _this._meshAttachedObservable = new BABYLON.Observable();
  70669. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70670. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70671. _this.position = BABYLON.Vector3.Zero();
  70672. _this.rotationQuaternion = new BABYLON.Quaternion();
  70673. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70674. _this._calculatedRotation = new BABYLON.Quaternion();
  70675. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70676. return _this;
  70677. }
  70678. /**
  70679. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70680. */
  70681. PoseEnabledController.prototype.update = function () {
  70682. _super.prototype.update.call(this);
  70683. var pose = this.browserGamepad.pose;
  70684. this.updateFromDevice(pose);
  70685. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70686. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70687. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70688. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70689. if (this._mesh) {
  70690. this._mesh.position.copyFrom(this.devicePosition);
  70691. if (this._mesh.rotationQuaternion) {
  70692. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70693. }
  70694. }
  70695. };
  70696. /**
  70697. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70698. * @param poseData raw pose fromthe device
  70699. */
  70700. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70701. if (poseData) {
  70702. this.rawPose = poseData;
  70703. if (poseData.position) {
  70704. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70705. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70706. this._deviceRoomPosition.z *= -1;
  70707. }
  70708. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70709. this._calculatedPosition.addInPlace(this.position);
  70710. }
  70711. var pose = this.rawPose;
  70712. if (poseData.orientation && pose.orientation) {
  70713. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70714. if (this._mesh) {
  70715. if (this._mesh.getScene().useRightHandedSystem) {
  70716. this._deviceRoomRotationQuaternion.z *= -1;
  70717. this._deviceRoomRotationQuaternion.w *= -1;
  70718. }
  70719. else {
  70720. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70721. }
  70722. }
  70723. // if the camera is set, rotate to the camera's rotation
  70724. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70725. }
  70726. }
  70727. };
  70728. /**
  70729. * Attaches a mesh to the controller
  70730. * @param mesh the mesh to be attached
  70731. */
  70732. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70733. if (this._mesh) {
  70734. this._mesh.parent = null;
  70735. }
  70736. this._mesh = mesh;
  70737. if (this._poseControlledCamera) {
  70738. this._mesh.parent = this._poseControlledCamera;
  70739. }
  70740. if (!this._mesh.rotationQuaternion) {
  70741. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70742. }
  70743. this._meshAttachedObservable.notifyObservers(mesh);
  70744. };
  70745. /**
  70746. * Attaches the controllers mesh to a camera
  70747. * @param camera the camera the mesh should be attached to
  70748. */
  70749. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70750. this._poseControlledCamera = camera;
  70751. if (this._mesh) {
  70752. this._mesh.parent = this._poseControlledCamera;
  70753. }
  70754. };
  70755. /**
  70756. * Disposes of the controller
  70757. */
  70758. PoseEnabledController.prototype.dispose = function () {
  70759. if (this._mesh) {
  70760. this._mesh.dispose();
  70761. }
  70762. this._mesh = null;
  70763. _super.prototype.dispose.call(this);
  70764. };
  70765. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70766. /**
  70767. * The mesh that is attached to the controller
  70768. */
  70769. get: function () {
  70770. return this._mesh;
  70771. },
  70772. enumerable: true,
  70773. configurable: true
  70774. });
  70775. /**
  70776. * Gets the ray of the controller in the direction the controller is pointing
  70777. * @param length the length the resulting ray should be
  70778. * @returns a ray in the direction the controller is pointing
  70779. */
  70780. PoseEnabledController.prototype.getForwardRay = function (length) {
  70781. if (length === void 0) { length = 100; }
  70782. if (!this.mesh) {
  70783. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70784. }
  70785. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70786. var origin = m.getTranslation();
  70787. var forward = new BABYLON.Vector3(0, 0, -1);
  70788. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70789. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70790. return new BABYLON.Ray(origin, direction, length);
  70791. };
  70792. /**
  70793. * Name of the child mesh that can be used to cast a ray from the controller
  70794. */
  70795. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70796. return PoseEnabledController;
  70797. }(BABYLON.Gamepad));
  70798. BABYLON.PoseEnabledController = PoseEnabledController;
  70799. })(BABYLON || (BABYLON = {}));
  70800. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70801. var BABYLON;
  70802. (function (BABYLON) {
  70803. /**
  70804. * Defines the WebVRController object that represents controllers tracked in 3D space
  70805. */
  70806. var WebVRController = /** @class */ (function (_super) {
  70807. __extends(WebVRController, _super);
  70808. /**
  70809. * Creates a new WebVRController from a gamepad
  70810. * @param vrGamepad the gamepad that the WebVRController should be created from
  70811. */
  70812. function WebVRController(vrGamepad) {
  70813. var _this = _super.call(this, vrGamepad) || this;
  70814. // Observables
  70815. /**
  70816. * Fired when the trigger state has changed
  70817. */
  70818. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70819. /**
  70820. * Fired when the main button state has changed
  70821. */
  70822. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70823. /**
  70824. * Fired when the secondary button state has changed
  70825. */
  70826. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70827. /**
  70828. * Fired when the pad state has changed
  70829. */
  70830. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70831. /**
  70832. * Fired when controllers stick values have changed
  70833. */
  70834. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70835. /**
  70836. * X and Y axis corrisponding to the controllers joystick
  70837. */
  70838. _this.pad = { x: 0, y: 0 };
  70839. // avoid GC, store state in a tmp object
  70840. _this._changes = {
  70841. pressChanged: false,
  70842. touchChanged: false,
  70843. valueChanged: false,
  70844. changed: false
  70845. };
  70846. _this._buttons = new Array(vrGamepad.buttons.length);
  70847. _this.hand = vrGamepad.hand;
  70848. return _this;
  70849. }
  70850. /**
  70851. * Fired when a controller button's state has changed
  70852. * @param callback the callback containing the button that was modified
  70853. */
  70854. WebVRController.prototype.onButtonStateChange = function (callback) {
  70855. this._onButtonStateChange = callback;
  70856. };
  70857. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70858. /**
  70859. * The default controller model for the controller
  70860. */
  70861. get: function () {
  70862. return this._defaultModel;
  70863. },
  70864. enumerable: true,
  70865. configurable: true
  70866. });
  70867. /**
  70868. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70869. */
  70870. WebVRController.prototype.update = function () {
  70871. _super.prototype.update.call(this);
  70872. for (var index = 0; index < this._buttons.length; index++) {
  70873. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70874. }
  70875. ;
  70876. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70877. this.pad.x = this.leftStick.x;
  70878. this.pad.y = this.leftStick.y;
  70879. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70880. }
  70881. };
  70882. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70883. if (!newState) {
  70884. newState = {
  70885. pressed: false,
  70886. touched: false,
  70887. value: 0
  70888. };
  70889. }
  70890. if (!currentState) {
  70891. this._buttons[buttonIndex] = {
  70892. pressed: newState.pressed,
  70893. touched: newState.touched,
  70894. value: newState.value
  70895. };
  70896. return;
  70897. }
  70898. this._checkChanges(newState, currentState);
  70899. if (this._changes.changed) {
  70900. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70901. this._handleButtonChange(buttonIndex, newState, this._changes);
  70902. }
  70903. this._buttons[buttonIndex].pressed = newState.pressed;
  70904. this._buttons[buttonIndex].touched = newState.touched;
  70905. // oculus triggers are never 0, thou not touched.
  70906. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70907. };
  70908. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70909. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70910. this._changes.touchChanged = newState.touched !== currentState.touched;
  70911. this._changes.valueChanged = newState.value !== currentState.value;
  70912. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70913. return this._changes;
  70914. };
  70915. /**
  70916. * Disposes of th webVRCOntroller
  70917. */
  70918. WebVRController.prototype.dispose = function () {
  70919. _super.prototype.dispose.call(this);
  70920. this.onTriggerStateChangedObservable.clear();
  70921. this.onMainButtonStateChangedObservable.clear();
  70922. this.onSecondaryButtonStateChangedObservable.clear();
  70923. this.onPadStateChangedObservable.clear();
  70924. this.onPadValuesChangedObservable.clear();
  70925. };
  70926. return WebVRController;
  70927. }(BABYLON.PoseEnabledController));
  70928. BABYLON.WebVRController = WebVRController;
  70929. })(BABYLON || (BABYLON = {}));
  70930. //# sourceMappingURL=babylon.webVRController.js.map
  70931. var BABYLON;
  70932. (function (BABYLON) {
  70933. /**
  70934. * Oculus Touch Controller
  70935. */
  70936. var OculusTouchController = /** @class */ (function (_super) {
  70937. __extends(OculusTouchController, _super);
  70938. /**
  70939. * Creates a new OculusTouchController from a gamepad
  70940. * @param vrGamepad the gamepad that the controller should be created from
  70941. */
  70942. function OculusTouchController(vrGamepad) {
  70943. var _this = _super.call(this, vrGamepad) || this;
  70944. /**
  70945. * Fired when the secondary trigger on this controller is modified
  70946. */
  70947. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70948. /**
  70949. * Fired when the thumb rest on this controller is modified
  70950. */
  70951. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70952. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70953. return _this;
  70954. }
  70955. /**
  70956. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70957. * @param scene scene in which to add meshes
  70958. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70959. */
  70960. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70961. var _this = this;
  70962. var meshName;
  70963. // Hand
  70964. if (this.hand === 'left') {
  70965. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70966. }
  70967. else { // Right is the default if no hand is specified
  70968. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70969. }
  70970. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70971. /*
  70972. Parent Mesh name: oculus_touch_left
  70973. - body
  70974. - trigger
  70975. - thumbstick
  70976. - grip
  70977. - button_y
  70978. - button_x
  70979. - button_enter
  70980. */
  70981. _this._defaultModel = newMeshes[1];
  70982. _this.attachToMesh(_this._defaultModel);
  70983. if (meshLoaded) {
  70984. meshLoaded(_this._defaultModel);
  70985. }
  70986. });
  70987. };
  70988. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70989. /**
  70990. * Fired when the A button on this controller is modified
  70991. */
  70992. get: function () {
  70993. if (this.hand === 'right') {
  70994. return this.onMainButtonStateChangedObservable;
  70995. }
  70996. else {
  70997. throw new Error('No A button on left hand');
  70998. }
  70999. },
  71000. enumerable: true,
  71001. configurable: true
  71002. });
  71003. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71004. /**
  71005. * Fired when the B button on this controller is modified
  71006. */
  71007. get: function () {
  71008. if (this.hand === 'right') {
  71009. return this.onSecondaryButtonStateChangedObservable;
  71010. }
  71011. else {
  71012. throw new Error('No B button on left hand');
  71013. }
  71014. },
  71015. enumerable: true,
  71016. configurable: true
  71017. });
  71018. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71019. /**
  71020. * Fired when the X button on this controller is modified
  71021. */
  71022. get: function () {
  71023. if (this.hand === 'left') {
  71024. return this.onMainButtonStateChangedObservable;
  71025. }
  71026. else {
  71027. throw new Error('No X button on right hand');
  71028. }
  71029. },
  71030. enumerable: true,
  71031. configurable: true
  71032. });
  71033. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71034. /**
  71035. * Fired when the Y button on this controller is modified
  71036. */
  71037. get: function () {
  71038. if (this.hand === 'left') {
  71039. return this.onSecondaryButtonStateChangedObservable;
  71040. }
  71041. else {
  71042. throw new Error('No Y button on right hand');
  71043. }
  71044. },
  71045. enumerable: true,
  71046. configurable: true
  71047. });
  71048. /**
  71049. * Called once for each button that changed state since the last frame
  71050. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71051. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71052. * 2) secondary trigger (same)
  71053. * 3) A (right) X (left), touch, pressed = value
  71054. * 4) B / Y
  71055. * 5) thumb rest
  71056. * @param buttonIdx Which button index changed
  71057. * @param state New state of the button
  71058. * @param changes Which properties on the state changed since last frame
  71059. */
  71060. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71061. var notifyObject = state; //{ state: state, changes: changes };
  71062. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71063. switch (buttonIdx) {
  71064. case 0:
  71065. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71066. return;
  71067. case 1: // index trigger
  71068. if (this._defaultModel) {
  71069. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71070. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71071. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71072. }
  71073. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71074. return;
  71075. case 2: // secondary trigger
  71076. if (this._defaultModel) {
  71077. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71078. }
  71079. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71080. return;
  71081. case 3:
  71082. if (this._defaultModel) {
  71083. if (notifyObject.pressed) {
  71084. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71085. }
  71086. else {
  71087. (this._defaultModel.getChildren()[1]).position.y = 0;
  71088. }
  71089. }
  71090. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71091. return;
  71092. case 4:
  71093. if (this._defaultModel) {
  71094. if (notifyObject.pressed) {
  71095. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71096. }
  71097. else {
  71098. (this._defaultModel.getChildren()[2]).position.y = 0;
  71099. }
  71100. }
  71101. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71102. return;
  71103. case 5:
  71104. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71105. return;
  71106. }
  71107. };
  71108. /**
  71109. * Base Url for the controller model.
  71110. */
  71111. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71112. /**
  71113. * File name for the left controller model.
  71114. */
  71115. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71116. /**
  71117. * File name for the right controller model.
  71118. */
  71119. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71120. return OculusTouchController;
  71121. }(BABYLON.WebVRController));
  71122. BABYLON.OculusTouchController = OculusTouchController;
  71123. })(BABYLON || (BABYLON = {}));
  71124. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71125. var BABYLON;
  71126. (function (BABYLON) {
  71127. /**
  71128. * Vive Controller
  71129. */
  71130. var ViveController = /** @class */ (function (_super) {
  71131. __extends(ViveController, _super);
  71132. /**
  71133. * Creates a new ViveController from a gamepad
  71134. * @param vrGamepad the gamepad that the controller should be created from
  71135. */
  71136. function ViveController(vrGamepad) {
  71137. var _this = _super.call(this, vrGamepad) || this;
  71138. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71139. _this._invertLeftStickY = true;
  71140. return _this;
  71141. }
  71142. /**
  71143. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71144. * @param scene scene in which to add meshes
  71145. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71146. */
  71147. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71148. var _this = this;
  71149. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71150. /*
  71151. Parent Mesh name: ViveWand
  71152. - body
  71153. - r_gripper
  71154. - l_gripper
  71155. - menu_button
  71156. - system_button
  71157. - trackpad
  71158. - trigger
  71159. - LED
  71160. */
  71161. _this._defaultModel = newMeshes[1];
  71162. _this.attachToMesh(_this._defaultModel);
  71163. if (meshLoaded) {
  71164. meshLoaded(_this._defaultModel);
  71165. }
  71166. });
  71167. };
  71168. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71169. /**
  71170. * Fired when the left button on this controller is modified
  71171. */
  71172. get: function () {
  71173. return this.onMainButtonStateChangedObservable;
  71174. },
  71175. enumerable: true,
  71176. configurable: true
  71177. });
  71178. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71179. /**
  71180. * Fired when the right button on this controller is modified
  71181. */
  71182. get: function () {
  71183. return this.onMainButtonStateChangedObservable;
  71184. },
  71185. enumerable: true,
  71186. configurable: true
  71187. });
  71188. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71189. /**
  71190. * Fired when the menu button on this controller is modified
  71191. */
  71192. get: function () {
  71193. return this.onSecondaryButtonStateChangedObservable;
  71194. },
  71195. enumerable: true,
  71196. configurable: true
  71197. });
  71198. /**
  71199. * Called once for each button that changed state since the last frame
  71200. * Vive mapping:
  71201. * 0: touchpad
  71202. * 1: trigger
  71203. * 2: left AND right buttons
  71204. * 3: menu button
  71205. * @param buttonIdx Which button index changed
  71206. * @param state New state of the button
  71207. * @param changes Which properties on the state changed since last frame
  71208. */
  71209. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71210. var notifyObject = state; //{ state: state, changes: changes };
  71211. switch (buttonIdx) {
  71212. case 0:
  71213. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71214. return;
  71215. case 1: // index trigger
  71216. if (this._defaultModel) {
  71217. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71218. }
  71219. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71220. return;
  71221. case 2: // left AND right button
  71222. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71223. return;
  71224. case 3:
  71225. if (this._defaultModel) {
  71226. if (notifyObject.pressed) {
  71227. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71228. }
  71229. else {
  71230. (this._defaultModel.getChildren()[2]).position.y = 0;
  71231. }
  71232. }
  71233. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71234. return;
  71235. }
  71236. };
  71237. /**
  71238. * Base Url for the controller model.
  71239. */
  71240. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71241. /**
  71242. * File name for the controller model.
  71243. */
  71244. ViveController.MODEL_FILENAME = 'wand.babylon';
  71245. return ViveController;
  71246. }(BABYLON.WebVRController));
  71247. BABYLON.ViveController = ViveController;
  71248. })(BABYLON || (BABYLON = {}));
  71249. //# sourceMappingURL=babylon.viveController.js.map
  71250. var BABYLON;
  71251. (function (BABYLON) {
  71252. /**
  71253. * Generic Controller
  71254. */
  71255. var GenericController = /** @class */ (function (_super) {
  71256. __extends(GenericController, _super);
  71257. /**
  71258. * Creates a new GenericController from a gamepad
  71259. * @param vrGamepad the gamepad that the controller should be created from
  71260. */
  71261. function GenericController(vrGamepad) {
  71262. return _super.call(this, vrGamepad) || this;
  71263. }
  71264. /**
  71265. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71266. * @param scene scene in which to add meshes
  71267. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71268. */
  71269. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71270. var _this = this;
  71271. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71272. _this._defaultModel = newMeshes[1];
  71273. _this.attachToMesh(_this._defaultModel);
  71274. if (meshLoaded) {
  71275. meshLoaded(_this._defaultModel);
  71276. }
  71277. });
  71278. };
  71279. /**
  71280. * Called once for each button that changed state since the last frame
  71281. * @param buttonIdx Which button index changed
  71282. * @param state New state of the button
  71283. * @param changes Which properties on the state changed since last frame
  71284. */
  71285. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71286. console.log("Button id: " + buttonIdx + "state: ");
  71287. console.dir(state);
  71288. };
  71289. /**
  71290. * Base Url for the controller model.
  71291. */
  71292. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71293. /**
  71294. * File name for the controller model.
  71295. */
  71296. GenericController.MODEL_FILENAME = 'generic.babylon';
  71297. return GenericController;
  71298. }(BABYLON.WebVRController));
  71299. BABYLON.GenericController = GenericController;
  71300. })(BABYLON || (BABYLON = {}));
  71301. //# sourceMappingURL=babylon.genericController.js.map
  71302. var BABYLON;
  71303. (function (BABYLON) {
  71304. /**
  71305. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71306. */
  71307. var LoadedMeshInfo = /** @class */ (function () {
  71308. function LoadedMeshInfo() {
  71309. /**
  71310. * Map of the button meshes contained in the controller
  71311. */
  71312. this.buttonMeshes = {};
  71313. /**
  71314. * Map of the axis meshes contained in the controller
  71315. */
  71316. this.axisMeshes = {};
  71317. }
  71318. return LoadedMeshInfo;
  71319. }());
  71320. /**
  71321. * Defines the WindowsMotionController object that the state of the windows motion controller
  71322. */
  71323. var WindowsMotionController = /** @class */ (function (_super) {
  71324. __extends(WindowsMotionController, _super);
  71325. /**
  71326. * Creates a new WindowsMotionController from a gamepad
  71327. * @param vrGamepad the gamepad that the controller should be created from
  71328. */
  71329. function WindowsMotionController(vrGamepad) {
  71330. var _this = _super.call(this, vrGamepad) || this;
  71331. _this._mapping = {
  71332. // Semantic button names
  71333. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71334. // A mapping of the button name to glTF model node name
  71335. // that should be transformed by button value.
  71336. buttonMeshNames: {
  71337. 'trigger': 'SELECT',
  71338. 'menu': 'MENU',
  71339. 'grip': 'GRASP',
  71340. 'thumbstick': 'THUMBSTICK_PRESS',
  71341. 'trackpad': 'TOUCHPAD_PRESS'
  71342. },
  71343. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71344. buttonObservableNames: {
  71345. 'trigger': 'onTriggerStateChangedObservable',
  71346. 'menu': 'onSecondaryButtonStateChangedObservable',
  71347. 'grip': 'onMainButtonStateChangedObservable',
  71348. 'thumbstick': 'onPadStateChangedObservable',
  71349. 'trackpad': 'onTrackpadChangedObservable'
  71350. },
  71351. // A mapping of the axis name to glTF model node name
  71352. // that should be transformed by axis value.
  71353. // This array mirrors the browserGamepad.axes array, such that
  71354. // the mesh corresponding to axis 0 is in this array index 0.
  71355. axisMeshNames: [
  71356. 'THUMBSTICK_X',
  71357. 'THUMBSTICK_Y',
  71358. 'TOUCHPAD_TOUCH_X',
  71359. 'TOUCHPAD_TOUCH_Y'
  71360. ],
  71361. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71362. };
  71363. /**
  71364. * Fired when the trackpad on this controller is clicked
  71365. */
  71366. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71367. /**
  71368. * Fired when the trackpad on this controller is modified
  71369. */
  71370. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71371. /**
  71372. * The current x and y values of this controller's trackpad
  71373. */
  71374. _this.trackpad = { x: 0, y: 0 };
  71375. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71376. _this._loadedMeshInfo = null;
  71377. return _this;
  71378. }
  71379. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71380. /**
  71381. * Fired when the trigger on this controller is modified
  71382. */
  71383. get: function () {
  71384. return this.onTriggerStateChangedObservable;
  71385. },
  71386. enumerable: true,
  71387. configurable: true
  71388. });
  71389. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71390. /**
  71391. * Fired when the menu button on this controller is modified
  71392. */
  71393. get: function () {
  71394. return this.onSecondaryButtonStateChangedObservable;
  71395. },
  71396. enumerable: true,
  71397. configurable: true
  71398. });
  71399. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71400. /**
  71401. * Fired when the grip button on this controller is modified
  71402. */
  71403. get: function () {
  71404. return this.onMainButtonStateChangedObservable;
  71405. },
  71406. enumerable: true,
  71407. configurable: true
  71408. });
  71409. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71410. /**
  71411. * Fired when the thumbstick button on this controller is modified
  71412. */
  71413. get: function () {
  71414. return this.onPadStateChangedObservable;
  71415. },
  71416. enumerable: true,
  71417. configurable: true
  71418. });
  71419. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71420. /**
  71421. * Fired when the touchpad button on this controller is modified
  71422. */
  71423. get: function () {
  71424. return this.onTrackpadChangedObservable;
  71425. },
  71426. enumerable: true,
  71427. configurable: true
  71428. });
  71429. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71430. /**
  71431. * Fired when the touchpad values on this controller are modified
  71432. */
  71433. get: function () {
  71434. return this.onTrackpadValuesChangedObservable;
  71435. },
  71436. enumerable: true,
  71437. configurable: true
  71438. });
  71439. WindowsMotionController.prototype._updateTrackpad = function () {
  71440. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  71441. this.trackpad.x = this.browserGamepad["axes"][2];
  71442. this.trackpad.y = this.browserGamepad["axes"][3];
  71443. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71444. }
  71445. };
  71446. /**
  71447. * Called once per frame by the engine.
  71448. */
  71449. WindowsMotionController.prototype.update = function () {
  71450. _super.prototype.update.call(this);
  71451. if (this.browserGamepad.axes) {
  71452. this._updateTrackpad();
  71453. // Only need to animate axes if there is a loaded mesh
  71454. if (this._loadedMeshInfo) {
  71455. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71456. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71457. }
  71458. }
  71459. }
  71460. };
  71461. /**
  71462. * Called once for each button that changed state since the last frame
  71463. * @param buttonIdx Which button index changed
  71464. * @param state New state of the button
  71465. * @param changes Which properties on the state changed since last frame
  71466. */
  71467. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71468. var buttonName = this._mapping.buttons[buttonIdx];
  71469. if (!buttonName) {
  71470. return;
  71471. }
  71472. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  71473. this._updateTrackpad();
  71474. // Only emit events for buttons that we know how to map from index to name
  71475. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71476. if (observable) {
  71477. observable.notifyObservers(state);
  71478. }
  71479. this._lerpButtonTransform(buttonName, state.value);
  71480. };
  71481. /**
  71482. * Moves the buttons on the controller mesh based on their current state
  71483. * @param buttonName the name of the button to move
  71484. * @param buttonValue the value of the button which determines the buttons new position
  71485. */
  71486. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71487. // If there is no loaded mesh, there is nothing to transform.
  71488. if (!this._loadedMeshInfo) {
  71489. return;
  71490. }
  71491. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71492. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71493. return;
  71494. }
  71495. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71496. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71497. };
  71498. /**
  71499. * Moves the axis on the controller mesh based on its current state
  71500. * @param axis the index of the axis
  71501. * @param axisValue the value of the axis which determines the meshes new position
  71502. * @hidden
  71503. */
  71504. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71505. if (!this._loadedMeshInfo) {
  71506. return;
  71507. }
  71508. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71509. if (!meshInfo) {
  71510. return;
  71511. }
  71512. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71513. return;
  71514. }
  71515. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71516. var lerpValue = axisValue * 0.5 + 0.5;
  71517. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71518. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71519. };
  71520. /**
  71521. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71522. * @param scene scene in which to add meshes
  71523. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71524. */
  71525. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71526. var _this = this;
  71527. if (forceDefault === void 0) { forceDefault = false; }
  71528. var path;
  71529. var filename;
  71530. // Checking if GLB loader is present
  71531. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71532. // Determine the device specific folder based on the ID suffix
  71533. var device = 'default';
  71534. if (this.id && !forceDefault) {
  71535. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71536. device = ((match && match[0]) || device);
  71537. }
  71538. // Hand
  71539. if (this.hand === 'left') {
  71540. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71541. }
  71542. else { // Right is the default if no hand is specified
  71543. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71544. }
  71545. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71546. }
  71547. else {
  71548. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71549. path = BABYLON.GenericController.MODEL_BASE_URL;
  71550. filename = BABYLON.GenericController.MODEL_FILENAME;
  71551. }
  71552. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71553. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71554. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71555. if (!_this._loadedMeshInfo) {
  71556. return;
  71557. }
  71558. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71559. _this.attachToMesh(_this._defaultModel);
  71560. if (meshLoaded) {
  71561. meshLoaded(_this._defaultModel);
  71562. }
  71563. }, null, function (scene, message) {
  71564. BABYLON.Tools.Log(message);
  71565. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71566. if (!forceDefault) {
  71567. _this.initControllerMesh(scene, meshLoaded, true);
  71568. }
  71569. });
  71570. };
  71571. /**
  71572. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71573. * can be transformed by button presses and axes values, based on this._mapping.
  71574. *
  71575. * @param scene scene in which the meshes exist
  71576. * @param meshes list of meshes that make up the controller model to process
  71577. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71578. */
  71579. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71580. var loadedMeshInfo = null;
  71581. // Create a new mesh to contain the glTF hierarchy
  71582. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71583. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71584. var childMesh = null;
  71585. for (var i = 0; i < meshes.length; i++) {
  71586. var mesh = meshes[i];
  71587. if (!mesh.parent) {
  71588. // Exclude controller meshes from picking results
  71589. mesh.isPickable = false;
  71590. // Handle root node, attach to the new parentMesh
  71591. childMesh = mesh;
  71592. break;
  71593. }
  71594. }
  71595. if (childMesh) {
  71596. childMesh.setParent(parentMesh);
  71597. // Create our mesh info. Note that this method will always return non-null.
  71598. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71599. }
  71600. else {
  71601. BABYLON.Tools.Warn('Could not find root node in model file.');
  71602. }
  71603. return loadedMeshInfo;
  71604. };
  71605. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71606. var loadedMeshInfo = new LoadedMeshInfo();
  71607. var i;
  71608. loadedMeshInfo.rootNode = rootNode;
  71609. // Reset the caches
  71610. loadedMeshInfo.buttonMeshes = {};
  71611. loadedMeshInfo.axisMeshes = {};
  71612. // Button Meshes
  71613. for (i = 0; i < this._mapping.buttons.length; i++) {
  71614. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71615. if (!buttonMeshName) {
  71616. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71617. continue;
  71618. }
  71619. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71620. if (!buttonMesh) {
  71621. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71622. continue;
  71623. }
  71624. var buttonMeshInfo = {
  71625. index: i,
  71626. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71627. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71628. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71629. };
  71630. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71631. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71632. }
  71633. else {
  71634. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71635. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71636. '(VALUE: ' + !!buttonMeshInfo.value +
  71637. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71638. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71639. ')');
  71640. }
  71641. }
  71642. // Axis Meshes
  71643. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71644. var axisMeshName = this._mapping.axisMeshNames[i];
  71645. if (!axisMeshName) {
  71646. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71647. continue;
  71648. }
  71649. var axisMesh = getChildByName(rootNode, axisMeshName);
  71650. if (!axisMesh) {
  71651. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71652. continue;
  71653. }
  71654. var axisMeshInfo = {
  71655. index: i,
  71656. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71657. min: getImmediateChildByName(axisMesh, 'MIN'),
  71658. max: getImmediateChildByName(axisMesh, 'MAX')
  71659. };
  71660. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71661. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71662. }
  71663. else {
  71664. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71665. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71666. '(VALUE: ' + !!axisMeshInfo.value +
  71667. ', MIN: ' + !!axisMeshInfo.min +
  71668. ', MAX:' + !!axisMeshInfo.max +
  71669. ')');
  71670. }
  71671. }
  71672. // Pointing Ray
  71673. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71674. if (!loadedMeshInfo.pointingPoseNode) {
  71675. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71676. }
  71677. return loadedMeshInfo;
  71678. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71679. function getChildByName(node, name) {
  71680. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71681. }
  71682. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71683. function getImmediateChildByName(node, name) {
  71684. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71685. }
  71686. };
  71687. /**
  71688. * Gets the ray of the controller in the direction the controller is pointing
  71689. * @param length the length the resulting ray should be
  71690. * @returns a ray in the direction the controller is pointing
  71691. */
  71692. WindowsMotionController.prototype.getForwardRay = function (length) {
  71693. if (length === void 0) { length = 100; }
  71694. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71695. return _super.prototype.getForwardRay.call(this, length);
  71696. }
  71697. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71698. var origin = m.getTranslation();
  71699. var forward = new BABYLON.Vector3(0, 0, -1);
  71700. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71701. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71702. return new BABYLON.Ray(origin, direction, length);
  71703. };
  71704. /**
  71705. * Disposes of the controller
  71706. */
  71707. WindowsMotionController.prototype.dispose = function () {
  71708. _super.prototype.dispose.call(this);
  71709. this.onTrackpadChangedObservable.clear();
  71710. };
  71711. /**
  71712. * The base url used to load the left and right controller models
  71713. */
  71714. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71715. /**
  71716. * The name of the left controller model file
  71717. */
  71718. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71719. /**
  71720. * The name of the right controller model file
  71721. */
  71722. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71723. /**
  71724. * The controller name prefix for this controller type
  71725. */
  71726. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71727. /**
  71728. * The controller id pattern for this controller type
  71729. */
  71730. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71731. return WindowsMotionController;
  71732. }(BABYLON.WebVRController));
  71733. BABYLON.WindowsMotionController = WindowsMotionController;
  71734. })(BABYLON || (BABYLON = {}));
  71735. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71736. var BABYLON;
  71737. (function (BABYLON) {
  71738. /**
  71739. * Gear VR Controller
  71740. */
  71741. var GearVRController = /** @class */ (function (_super) {
  71742. __extends(GearVRController, _super);
  71743. /**
  71744. * Creates a new GearVRController from a gamepad
  71745. * @param vrGamepad the gamepad that the controller should be created from
  71746. */
  71747. function GearVRController(vrGamepad) {
  71748. var _this = _super.call(this, vrGamepad) || this;
  71749. _this._buttonIndexToObservableNameMap = [
  71750. 'onTrackpadChangedObservable',
  71751. 'onTriggerStateChangedObservable' // Trigger
  71752. ];
  71753. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71754. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  71755. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  71756. return _this;
  71757. }
  71758. /**
  71759. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71760. * @param scene scene in which to add meshes
  71761. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71762. */
  71763. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71764. var _this = this;
  71765. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71766. _this._defaultModel = newMeshes[1];
  71767. _this.attachToMesh(_this._defaultModel);
  71768. if (meshLoaded) {
  71769. meshLoaded(_this._defaultModel);
  71770. }
  71771. });
  71772. };
  71773. /**
  71774. * Called once for each button that changed state since the last frame
  71775. * @param buttonIdx Which button index changed
  71776. * @param state New state of the button
  71777. * @param changes Which properties on the state changed since last frame
  71778. */
  71779. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71780. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71781. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71782. // Only emit events for buttons that we know how to map from index to observable
  71783. var observable = this[observableName];
  71784. if (observable) {
  71785. observable.notifyObservers(state);
  71786. }
  71787. }
  71788. };
  71789. /**
  71790. * Base Url for the controller model.
  71791. */
  71792. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71793. /**
  71794. * File name for the controller model.
  71795. */
  71796. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71797. /**
  71798. * Gamepad Id prefix used to identify this controller.
  71799. */
  71800. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71801. return GearVRController;
  71802. }(BABYLON.WebVRController));
  71803. BABYLON.GearVRController = GearVRController;
  71804. })(BABYLON || (BABYLON = {}));
  71805. //# sourceMappingURL=babylon.gearVRController.js.map
  71806. var BABYLON;
  71807. (function (BABYLON) {
  71808. /**
  71809. * Google Daydream controller
  71810. */
  71811. var DaydreamController = /** @class */ (function (_super) {
  71812. __extends(DaydreamController, _super);
  71813. /**
  71814. * Creates a new DaydreamController from a gamepad
  71815. * @param vrGamepad the gamepad that the controller should be created from
  71816. */
  71817. function DaydreamController(vrGamepad) {
  71818. var _this = _super.call(this, vrGamepad) || this;
  71819. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71820. return _this;
  71821. }
  71822. /**
  71823. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71824. * @param scene scene in which to add meshes
  71825. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71826. */
  71827. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71828. var _this = this;
  71829. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71830. _this._defaultModel = newMeshes[1];
  71831. _this.attachToMesh(_this._defaultModel);
  71832. if (meshLoaded) {
  71833. meshLoaded(_this._defaultModel);
  71834. }
  71835. });
  71836. };
  71837. /**
  71838. * Called once for each button that changed state since the last frame
  71839. * @param buttonIdx Which button index changed
  71840. * @param state New state of the button
  71841. * @param changes Which properties on the state changed since last frame
  71842. */
  71843. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71844. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71845. if (buttonIdx === 0) {
  71846. var observable = this.onTriggerStateChangedObservable;
  71847. if (observable) {
  71848. observable.notifyObservers(state);
  71849. }
  71850. }
  71851. else {
  71852. // If the app or home buttons are ever made available
  71853. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71854. }
  71855. };
  71856. /**
  71857. * Base Url for the controller model.
  71858. */
  71859. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71860. /**
  71861. * File name for the controller model.
  71862. */
  71863. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71864. /**
  71865. * Gamepad Id prefix used to identify Daydream Controller.
  71866. */
  71867. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71868. return DaydreamController;
  71869. }(BABYLON.WebVRController));
  71870. BABYLON.DaydreamController = DaydreamController;
  71871. })(BABYLON || (BABYLON = {}));
  71872. //# sourceMappingURL=babylon.daydreamController.js.map
  71873. var BABYLON;
  71874. (function (BABYLON) {
  71875. var FollowCamera = /** @class */ (function (_super) {
  71876. __extends(FollowCamera, _super);
  71877. function FollowCamera(name, position, scene, lockedTarget) {
  71878. if (lockedTarget === void 0) { lockedTarget = null; }
  71879. var _this = _super.call(this, name, position, scene) || this;
  71880. _this.radius = 12;
  71881. _this.rotationOffset = 0;
  71882. _this.heightOffset = 4;
  71883. _this.cameraAcceleration = 0.05;
  71884. _this.maxCameraSpeed = 20;
  71885. _this.lockedTarget = lockedTarget;
  71886. return _this;
  71887. }
  71888. FollowCamera.prototype.getRadians = function (degrees) {
  71889. return degrees * Math.PI / 180;
  71890. };
  71891. FollowCamera.prototype.follow = function (cameraTarget) {
  71892. if (!cameraTarget)
  71893. return;
  71894. var yRotation;
  71895. if (cameraTarget.rotationQuaternion) {
  71896. var rotMatrix = new BABYLON.Matrix();
  71897. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71898. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71899. }
  71900. else {
  71901. yRotation = cameraTarget.rotation.y;
  71902. }
  71903. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71904. var targetPosition = cameraTarget.getAbsolutePosition();
  71905. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71906. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71907. var dx = targetX - this.position.x;
  71908. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71909. var dz = (targetZ) - this.position.z;
  71910. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71911. var vy = dy * this.cameraAcceleration;
  71912. var vz = dz * this.cameraAcceleration * 2;
  71913. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71914. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71915. }
  71916. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71917. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71918. }
  71919. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71920. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71921. }
  71922. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71923. this.setTarget(targetPosition);
  71924. };
  71925. FollowCamera.prototype._checkInputs = function () {
  71926. _super.prototype._checkInputs.call(this);
  71927. if (this.lockedTarget) {
  71928. this.follow(this.lockedTarget);
  71929. }
  71930. };
  71931. FollowCamera.prototype.getClassName = function () {
  71932. return "FollowCamera";
  71933. };
  71934. __decorate([
  71935. BABYLON.serialize()
  71936. ], FollowCamera.prototype, "radius", void 0);
  71937. __decorate([
  71938. BABYLON.serialize()
  71939. ], FollowCamera.prototype, "rotationOffset", void 0);
  71940. __decorate([
  71941. BABYLON.serialize()
  71942. ], FollowCamera.prototype, "heightOffset", void 0);
  71943. __decorate([
  71944. BABYLON.serialize()
  71945. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71946. __decorate([
  71947. BABYLON.serialize()
  71948. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71949. __decorate([
  71950. BABYLON.serializeAsMeshReference("lockedTargetId")
  71951. ], FollowCamera.prototype, "lockedTarget", void 0);
  71952. return FollowCamera;
  71953. }(BABYLON.TargetCamera));
  71954. BABYLON.FollowCamera = FollowCamera;
  71955. var ArcFollowCamera = /** @class */ (function (_super) {
  71956. __extends(ArcFollowCamera, _super);
  71957. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71958. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71959. _this.alpha = alpha;
  71960. _this.beta = beta;
  71961. _this.radius = radius;
  71962. _this.target = target;
  71963. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71964. _this.follow();
  71965. return _this;
  71966. }
  71967. ArcFollowCamera.prototype.follow = function () {
  71968. if (!this.target) {
  71969. return;
  71970. }
  71971. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71972. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71973. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71974. var targetPosition = this.target.getAbsolutePosition();
  71975. this.position = targetPosition.add(this._cartesianCoordinates);
  71976. this.setTarget(targetPosition);
  71977. };
  71978. ArcFollowCamera.prototype._checkInputs = function () {
  71979. _super.prototype._checkInputs.call(this);
  71980. this.follow();
  71981. };
  71982. ArcFollowCamera.prototype.getClassName = function () {
  71983. return "ArcFollowCamera";
  71984. };
  71985. return ArcFollowCamera;
  71986. }(BABYLON.TargetCamera));
  71987. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71988. })(BABYLON || (BABYLON = {}));
  71989. //# sourceMappingURL=babylon.followCamera.js.map
  71990. var BABYLON;
  71991. (function (BABYLON) {
  71992. // We're mainly based on the logic defined into the FreeCamera code
  71993. var UniversalCamera = /** @class */ (function (_super) {
  71994. __extends(UniversalCamera, _super);
  71995. //-- end properties for backward compatibility for inputs
  71996. function UniversalCamera(name, position, scene) {
  71997. var _this = _super.call(this, name, position, scene) || this;
  71998. _this.inputs.addGamepad();
  71999. return _this;
  72000. }
  72001. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72002. //-- Begin properties for backward compatibility for inputs
  72003. get: function () {
  72004. var gamepad = this.inputs.attached["gamepad"];
  72005. if (gamepad)
  72006. return gamepad.gamepadAngularSensibility;
  72007. return 0;
  72008. },
  72009. set: function (value) {
  72010. var gamepad = this.inputs.attached["gamepad"];
  72011. if (gamepad)
  72012. gamepad.gamepadAngularSensibility = value;
  72013. },
  72014. enumerable: true,
  72015. configurable: true
  72016. });
  72017. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72018. get: function () {
  72019. var gamepad = this.inputs.attached["gamepad"];
  72020. if (gamepad)
  72021. return gamepad.gamepadMoveSensibility;
  72022. return 0;
  72023. },
  72024. set: function (value) {
  72025. var gamepad = this.inputs.attached["gamepad"];
  72026. if (gamepad)
  72027. gamepad.gamepadMoveSensibility = value;
  72028. },
  72029. enumerable: true,
  72030. configurable: true
  72031. });
  72032. UniversalCamera.prototype.getClassName = function () {
  72033. return "UniversalCamera";
  72034. };
  72035. return UniversalCamera;
  72036. }(BABYLON.TouchCamera));
  72037. BABYLON.UniversalCamera = UniversalCamera;
  72038. })(BABYLON || (BABYLON = {}));
  72039. //# sourceMappingURL=babylon.universalCamera.js.map
  72040. var BABYLON;
  72041. (function (BABYLON) {
  72042. // We're mainly based on the logic defined into the FreeCamera code
  72043. var GamepadCamera = /** @class */ (function (_super) {
  72044. __extends(GamepadCamera, _super);
  72045. //-- end properties for backward compatibility for inputs
  72046. function GamepadCamera(name, position, scene) {
  72047. return _super.call(this, name, position, scene) || this;
  72048. }
  72049. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72050. //-- Begin properties for backward compatibility for inputs
  72051. get: function () {
  72052. var gamepad = this.inputs.attached["gamepad"];
  72053. if (gamepad)
  72054. return gamepad.gamepadAngularSensibility;
  72055. return 0;
  72056. },
  72057. set: function (value) {
  72058. var gamepad = this.inputs.attached["gamepad"];
  72059. if (gamepad)
  72060. gamepad.gamepadAngularSensibility = value;
  72061. },
  72062. enumerable: true,
  72063. configurable: true
  72064. });
  72065. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72066. get: function () {
  72067. var gamepad = this.inputs.attached["gamepad"];
  72068. if (gamepad)
  72069. return gamepad.gamepadMoveSensibility;
  72070. return 0;
  72071. },
  72072. set: function (value) {
  72073. var gamepad = this.inputs.attached["gamepad"];
  72074. if (gamepad)
  72075. gamepad.gamepadMoveSensibility = value;
  72076. },
  72077. enumerable: true,
  72078. configurable: true
  72079. });
  72080. GamepadCamera.prototype.getClassName = function () {
  72081. return "GamepadCamera";
  72082. };
  72083. return GamepadCamera;
  72084. }(BABYLON.UniversalCamera));
  72085. BABYLON.GamepadCamera = GamepadCamera;
  72086. })(BABYLON || (BABYLON = {}));
  72087. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72088. var BABYLON;
  72089. (function (BABYLON) {
  72090. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72091. function PostProcessRenderPipelineManager() {
  72092. this._renderPipelines = {};
  72093. }
  72094. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72095. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72096. };
  72097. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72098. if (unique === void 0) { unique = false; }
  72099. var renderPipeline = this._renderPipelines[renderPipelineName];
  72100. if (!renderPipeline) {
  72101. return;
  72102. }
  72103. renderPipeline._attachCameras(cameras, unique);
  72104. };
  72105. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72106. var renderPipeline = this._renderPipelines[renderPipelineName];
  72107. if (!renderPipeline) {
  72108. return;
  72109. }
  72110. renderPipeline._detachCameras(cameras);
  72111. };
  72112. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72113. var renderPipeline = this._renderPipelines[renderPipelineName];
  72114. if (!renderPipeline) {
  72115. return;
  72116. }
  72117. renderPipeline._enableEffect(renderEffectName, cameras);
  72118. };
  72119. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72120. var renderPipeline = this._renderPipelines[renderPipelineName];
  72121. if (!renderPipeline) {
  72122. return;
  72123. }
  72124. renderPipeline._disableEffect(renderEffectName, cameras);
  72125. };
  72126. PostProcessRenderPipelineManager.prototype.update = function () {
  72127. for (var renderPipelineName in this._renderPipelines) {
  72128. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72129. var pipeline = this._renderPipelines[renderPipelineName];
  72130. if (!pipeline.isSupported) {
  72131. pipeline.dispose();
  72132. delete this._renderPipelines[renderPipelineName];
  72133. }
  72134. else {
  72135. pipeline._update();
  72136. }
  72137. }
  72138. }
  72139. };
  72140. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72141. for (var renderPipelineName in this._renderPipelines) {
  72142. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72143. var pipeline = this._renderPipelines[renderPipelineName];
  72144. pipeline._rebuild();
  72145. }
  72146. }
  72147. };
  72148. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72149. for (var renderPipelineName in this._renderPipelines) {
  72150. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72151. var pipeline = this._renderPipelines[renderPipelineName];
  72152. pipeline.dispose();
  72153. }
  72154. }
  72155. };
  72156. return PostProcessRenderPipelineManager;
  72157. }());
  72158. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72159. })(BABYLON || (BABYLON = {}));
  72160. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72161. var BABYLON;
  72162. (function (BABYLON) {
  72163. /**
  72164. * This represents a set of one or more post processes in Babylon.
  72165. * A post process can be used to apply a shader to a texture after it is rendered.
  72166. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72167. */
  72168. var PostProcessRenderEffect = /** @class */ (function () {
  72169. /**
  72170. * Instantiates a post process render effect.
  72171. * A post process can be used to apply a shader to a texture after it is rendered.
  72172. * @param engine The engine the effect is tied to
  72173. * @param name The name of the effect
  72174. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72175. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72176. */
  72177. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72178. this._name = name;
  72179. this._singleInstance = singleInstance || true;
  72180. this._getPostProcesses = getPostProcesses;
  72181. this._cameras = {};
  72182. this._indicesForCamera = {};
  72183. this._postProcesses = {};
  72184. }
  72185. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72186. /**
  72187. * Checks if all the post processes in the effect are supported.
  72188. */
  72189. get: function () {
  72190. for (var index in this._postProcesses) {
  72191. if (this._postProcesses.hasOwnProperty(index)) {
  72192. var pps = this._postProcesses[index];
  72193. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72194. if (!pps[ppIndex].isSupported) {
  72195. return false;
  72196. }
  72197. }
  72198. }
  72199. }
  72200. return true;
  72201. },
  72202. enumerable: true,
  72203. configurable: true
  72204. });
  72205. /**
  72206. * Updates the current state of the effect
  72207. */
  72208. PostProcessRenderEffect.prototype._update = function () {
  72209. };
  72210. /**
  72211. * Attaches the effect on cameras
  72212. * @param cameras The camera to attach to.
  72213. */
  72214. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72215. var _this = this;
  72216. var cameraKey;
  72217. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72218. if (!cams) {
  72219. return;
  72220. }
  72221. for (var i = 0; i < cams.length; i++) {
  72222. var camera = cams[i];
  72223. var cameraName = camera.name;
  72224. if (this._singleInstance) {
  72225. cameraKey = 0;
  72226. }
  72227. else {
  72228. cameraKey = cameraName;
  72229. }
  72230. if (!this._postProcesses[cameraKey]) {
  72231. var postProcess = this._getPostProcesses();
  72232. if (postProcess) {
  72233. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72234. }
  72235. }
  72236. if (!this._indicesForCamera[cameraName]) {
  72237. this._indicesForCamera[cameraName] = [];
  72238. }
  72239. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72240. var index = camera.attachPostProcess(postProcess);
  72241. _this._indicesForCamera[cameraName].push(index);
  72242. });
  72243. if (!this._cameras[cameraName]) {
  72244. this._cameras[cameraName] = camera;
  72245. }
  72246. }
  72247. };
  72248. /**
  72249. * Detatches the effect on cameras
  72250. * @param cameras The camera to detatch from.
  72251. */
  72252. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72253. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72254. if (!cams) {
  72255. return;
  72256. }
  72257. for (var i = 0; i < cams.length; i++) {
  72258. var camera = cams[i];
  72259. var cameraName = camera.name;
  72260. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72261. camera.detachPostProcess(postProcess);
  72262. });
  72263. if (this._cameras[cameraName]) {
  72264. //this._indicesForCamera.splice(index, 1);
  72265. this._cameras[cameraName] = null;
  72266. }
  72267. }
  72268. };
  72269. /**
  72270. * Enables the effect on given cameras
  72271. * @param cameras The camera to enable.
  72272. */
  72273. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72274. var _this = this;
  72275. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72276. if (!cams) {
  72277. return;
  72278. }
  72279. for (var i = 0; i < cams.length; i++) {
  72280. var camera = cams[i];
  72281. var cameraName = camera.name;
  72282. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72283. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72284. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72285. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72286. });
  72287. }
  72288. }
  72289. }
  72290. };
  72291. /**
  72292. * Disables the effect on the given cameras
  72293. * @param cameras The camera to disable.
  72294. */
  72295. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72296. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72297. if (!cams) {
  72298. return;
  72299. }
  72300. for (var i = 0; i < cams.length; i++) {
  72301. var camera = cams[i];
  72302. var cameraName = camera.name;
  72303. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72304. camera.detachPostProcess(postProcess);
  72305. });
  72306. }
  72307. };
  72308. /**
  72309. * Gets a list of the post processes contained in the effect.
  72310. * @param camera The camera to get the post processes on.
  72311. * @returns The list of the post processes in the effect.
  72312. */
  72313. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72314. if (this._singleInstance) {
  72315. return this._postProcesses[0];
  72316. }
  72317. else {
  72318. if (!camera) {
  72319. return null;
  72320. }
  72321. return this._postProcesses[camera.name];
  72322. }
  72323. };
  72324. return PostProcessRenderEffect;
  72325. }());
  72326. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72327. })(BABYLON || (BABYLON = {}));
  72328. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72329. var BABYLON;
  72330. (function (BABYLON) {
  72331. var PostProcessRenderPipeline = /** @class */ (function () {
  72332. function PostProcessRenderPipeline(engine, name) {
  72333. this.engine = engine;
  72334. this._name = name;
  72335. this._renderEffects = {};
  72336. this._renderEffectsForIsolatedPass = new Array();
  72337. this._cameras = [];
  72338. }
  72339. PostProcessRenderPipeline.prototype.getClassName = function () {
  72340. return "PostProcessRenderPipeline";
  72341. };
  72342. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72343. get: function () {
  72344. for (var renderEffectName in this._renderEffects) {
  72345. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72346. if (!this._renderEffects[renderEffectName].isSupported) {
  72347. return false;
  72348. }
  72349. }
  72350. }
  72351. return true;
  72352. },
  72353. enumerable: true,
  72354. configurable: true
  72355. });
  72356. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72357. this._renderEffects[renderEffect._name] = renderEffect;
  72358. };
  72359. // private
  72360. PostProcessRenderPipeline.prototype._rebuild = function () {
  72361. };
  72362. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72363. var renderEffects = this._renderEffects[renderEffectName];
  72364. if (!renderEffects) {
  72365. return;
  72366. }
  72367. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72368. };
  72369. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72370. var renderEffects = this._renderEffects[renderEffectName];
  72371. if (!renderEffects) {
  72372. return;
  72373. }
  72374. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72375. };
  72376. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72377. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72378. if (!cams) {
  72379. return;
  72380. }
  72381. var indicesToDelete = [];
  72382. var i;
  72383. for (i = 0; i < cams.length; i++) {
  72384. var camera = cams[i];
  72385. var cameraName = camera.name;
  72386. if (this._cameras.indexOf(camera) === -1) {
  72387. this._cameras[cameraName] = camera;
  72388. }
  72389. else if (unique) {
  72390. indicesToDelete.push(i);
  72391. }
  72392. }
  72393. for (i = 0; i < indicesToDelete.length; i++) {
  72394. cameras.splice(indicesToDelete[i], 1);
  72395. }
  72396. for (var renderEffectName in this._renderEffects) {
  72397. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72398. this._renderEffects[renderEffectName]._attachCameras(cams);
  72399. }
  72400. }
  72401. };
  72402. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72403. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72404. if (!cams) {
  72405. return;
  72406. }
  72407. for (var renderEffectName in this._renderEffects) {
  72408. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72409. this._renderEffects[renderEffectName]._detachCameras(cams);
  72410. }
  72411. }
  72412. for (var i = 0; i < cams.length; i++) {
  72413. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72414. }
  72415. };
  72416. PostProcessRenderPipeline.prototype._update = function () {
  72417. for (var renderEffectName in this._renderEffects) {
  72418. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72419. this._renderEffects[renderEffectName]._update();
  72420. }
  72421. }
  72422. for (var i = 0; i < this._cameras.length; i++) {
  72423. var cameraName = this._cameras[i].name;
  72424. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72425. this._renderEffectsForIsolatedPass[cameraName]._update();
  72426. }
  72427. }
  72428. };
  72429. PostProcessRenderPipeline.prototype._reset = function () {
  72430. this._renderEffects = {};
  72431. this._renderEffectsForIsolatedPass = new Array();
  72432. };
  72433. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72434. // 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)
  72435. var effectKeys = Object.keys(this._renderEffects);
  72436. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72437. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72438. if (postProcesses) {
  72439. postProcesses[0].samples = sampleCount;
  72440. return true;
  72441. }
  72442. }
  72443. return false;
  72444. };
  72445. PostProcessRenderPipeline.prototype.dispose = function () {
  72446. // Must be implemented by children
  72447. };
  72448. __decorate([
  72449. BABYLON.serialize()
  72450. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72451. return PostProcessRenderPipeline;
  72452. }());
  72453. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72454. })(BABYLON || (BABYLON = {}));
  72455. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72456. var BABYLON;
  72457. (function (BABYLON) {
  72458. /**
  72459. * This represents a depth renderer in Babylon.
  72460. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72461. */
  72462. var DepthRenderer = /** @class */ (function () {
  72463. /**
  72464. * Instantiates a depth renderer
  72465. * @param scene The scene the renderer belongs to
  72466. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72467. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72468. */
  72469. function DepthRenderer(scene, type, camera) {
  72470. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72471. if (camera === void 0) { camera = null; }
  72472. var _this = this;
  72473. this._scene = scene;
  72474. this._camera = camera;
  72475. var engine = scene.getEngine();
  72476. // Render target
  72477. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72478. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72479. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72480. this._depthMap.refreshRate = 1;
  72481. this._depthMap.renderParticles = false;
  72482. this._depthMap.renderList = null;
  72483. // Camera to get depth map from to support multiple concurrent cameras
  72484. this._depthMap.activeCamera = this._camera;
  72485. this._depthMap.ignoreCameraViewport = true;
  72486. this._depthMap.useCameraPostProcesses = false;
  72487. // set default depth value to 1.0 (far away)
  72488. this._depthMap.onClearObservable.add(function (engine) {
  72489. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72490. });
  72491. // Custom render function
  72492. var renderSubMesh = function (subMesh) {
  72493. var mesh = subMesh.getRenderingMesh();
  72494. var scene = _this._scene;
  72495. var engine = scene.getEngine();
  72496. var material = subMesh.getMaterial();
  72497. if (!material) {
  72498. return;
  72499. }
  72500. // Culling and reverse (right handed system)
  72501. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72502. // Managing instances
  72503. var batch = mesh._getInstancesRenderList(subMesh._id);
  72504. if (batch.mustReturn) {
  72505. return;
  72506. }
  72507. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72508. var camera = _this._camera || scene.activeCamera;
  72509. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72510. engine.enableEffect(_this._effect);
  72511. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72512. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72513. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72514. // Alpha test
  72515. if (material && material.needAlphaTesting()) {
  72516. var alphaTexture = material.getAlphaTestTexture();
  72517. if (alphaTexture) {
  72518. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72519. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72520. }
  72521. }
  72522. // Bones
  72523. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72524. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72525. }
  72526. // Draw
  72527. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72528. }
  72529. };
  72530. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72531. var index;
  72532. if (depthOnlySubMeshes.length) {
  72533. engine.setColorWrite(false);
  72534. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72535. renderSubMesh(depthOnlySubMeshes.data[index]);
  72536. }
  72537. engine.setColorWrite(true);
  72538. }
  72539. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72540. renderSubMesh(opaqueSubMeshes.data[index]);
  72541. }
  72542. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72543. renderSubMesh(alphaTestSubMeshes.data[index]);
  72544. }
  72545. };
  72546. }
  72547. /**
  72548. * Creates the depth rendering effect and checks if the effect is ready.
  72549. * @param subMesh The submesh to be used to render the depth map of
  72550. * @param useInstances If multiple world instances should be used
  72551. * @returns if the depth renderer is ready to render the depth map
  72552. */
  72553. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72554. var material = subMesh.getMaterial();
  72555. if (material.disableDepthWrite) {
  72556. return false;
  72557. }
  72558. var defines = [];
  72559. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72560. var mesh = subMesh.getMesh();
  72561. // Alpha test
  72562. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72563. defines.push("#define ALPHATEST");
  72564. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72565. attribs.push(BABYLON.VertexBuffer.UVKind);
  72566. defines.push("#define UV1");
  72567. }
  72568. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72569. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72570. defines.push("#define UV2");
  72571. }
  72572. }
  72573. // Bones
  72574. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72575. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72576. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72577. if (mesh.numBoneInfluencers > 4) {
  72578. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72579. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72580. }
  72581. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72582. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72583. }
  72584. else {
  72585. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72586. }
  72587. // Instances
  72588. if (useInstances) {
  72589. defines.push("#define INSTANCES");
  72590. attribs.push("world0");
  72591. attribs.push("world1");
  72592. attribs.push("world2");
  72593. attribs.push("world3");
  72594. }
  72595. // Get correct effect
  72596. var join = defines.join("\n");
  72597. if (this._cachedDefines !== join) {
  72598. this._cachedDefines = join;
  72599. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72600. }
  72601. return this._effect.isReady();
  72602. };
  72603. /**
  72604. * Gets the texture which the depth map will be written to.
  72605. * @returns The depth map texture
  72606. */
  72607. DepthRenderer.prototype.getDepthMap = function () {
  72608. return this._depthMap;
  72609. };
  72610. /**
  72611. * Disposes of the depth renderer.
  72612. */
  72613. DepthRenderer.prototype.dispose = function () {
  72614. this._depthMap.dispose();
  72615. };
  72616. return DepthRenderer;
  72617. }());
  72618. BABYLON.DepthRenderer = DepthRenderer;
  72619. })(BABYLON || (BABYLON = {}));
  72620. //# sourceMappingURL=babylon.depthRenderer.js.map
  72621. var BABYLON;
  72622. (function (BABYLON) {
  72623. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72624. __extends(SSAORenderingPipeline, _super);
  72625. /**
  72626. * @constructor
  72627. * @param {string} name - The rendering pipeline name
  72628. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72629. * @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 }
  72630. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72631. */
  72632. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72633. var _this = _super.call(this, scene.getEngine(), name) || this;
  72634. // Members
  72635. /**
  72636. * The PassPostProcess id in the pipeline that contains the original scene color
  72637. */
  72638. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72639. /**
  72640. * The SSAO PostProcess id in the pipeline
  72641. */
  72642. _this.SSAORenderEffect = "SSAORenderEffect";
  72643. /**
  72644. * The horizontal blur PostProcess id in the pipeline
  72645. */
  72646. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72647. /**
  72648. * The vertical blur PostProcess id in the pipeline
  72649. */
  72650. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72651. /**
  72652. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72653. */
  72654. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72655. /**
  72656. * The output strength of the SSAO post-process. Default value is 1.0.
  72657. */
  72658. _this.totalStrength = 1.0;
  72659. /**
  72660. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72661. */
  72662. _this.radius = 0.0001;
  72663. /**
  72664. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72665. * Must not be equal to fallOff and superior to fallOff.
  72666. * Default value is 0.975
  72667. */
  72668. _this.area = 0.0075;
  72669. /**
  72670. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72671. * Must not be equal to area and inferior to area.
  72672. * Default value is 0.0
  72673. */
  72674. _this.fallOff = 0.000001;
  72675. /**
  72676. * The base color of the SSAO post-process
  72677. * The final result is "base + ssao" between [0, 1]
  72678. */
  72679. _this.base = 0.5;
  72680. _this._firstUpdate = true;
  72681. _this._scene = scene;
  72682. // Set up assets
  72683. _this._createRandomTexture();
  72684. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72685. var ssaoRatio = ratio.ssaoRatio || ratio;
  72686. var combineRatio = ratio.combineRatio || ratio;
  72687. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72688. _this._createSSAOPostProcess(ssaoRatio);
  72689. _this._createBlurPostProcess(ssaoRatio);
  72690. _this._createSSAOCombinePostProcess(combineRatio);
  72691. // Set up pipeline
  72692. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72693. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72694. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72695. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72696. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72697. // Finish
  72698. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72699. if (cameras)
  72700. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72701. return _this;
  72702. }
  72703. // Public Methods
  72704. /**
  72705. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72706. */
  72707. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72708. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72709. for (var i = 0; i < this._scene.cameras.length; i++) {
  72710. var camera = this._scene.cameras[i];
  72711. this._originalColorPostProcess.dispose(camera);
  72712. this._ssaoPostProcess.dispose(camera);
  72713. this._blurHPostProcess.dispose(camera);
  72714. this._blurVPostProcess.dispose(camera);
  72715. this._ssaoCombinePostProcess.dispose(camera);
  72716. }
  72717. this._randomTexture.dispose();
  72718. if (disableDepthRender)
  72719. this._scene.disableDepthRenderer();
  72720. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72721. _super.prototype.dispose.call(this);
  72722. };
  72723. // Private Methods
  72724. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72725. var _this = this;
  72726. var size = 16;
  72727. 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);
  72728. 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);
  72729. this._blurHPostProcess.onActivateObservable.add(function () {
  72730. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72731. _this._blurHPostProcess.kernel = size * dw;
  72732. });
  72733. this._blurVPostProcess.onActivateObservable.add(function () {
  72734. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72735. _this._blurVPostProcess.kernel = size * dw;
  72736. });
  72737. };
  72738. SSAORenderingPipeline.prototype._rebuild = function () {
  72739. this._firstUpdate = true;
  72740. _super.prototype._rebuild.call(this);
  72741. };
  72742. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72743. var _this = this;
  72744. var numSamples = 16;
  72745. var sampleSphere = [
  72746. 0.5381, 0.1856, -0.4319,
  72747. 0.1379, 0.2486, 0.4430,
  72748. 0.3371, 0.5679, -0.0057,
  72749. -0.6999, -0.0451, -0.0019,
  72750. 0.0689, -0.1598, -0.8547,
  72751. 0.0560, 0.0069, -0.1843,
  72752. -0.0146, 0.1402, 0.0762,
  72753. 0.0100, -0.1924, -0.0344,
  72754. -0.3577, -0.5301, -0.4358,
  72755. -0.3169, 0.1063, 0.0158,
  72756. 0.0103, -0.5869, 0.0046,
  72757. -0.0897, -0.4940, 0.3287,
  72758. 0.7119, -0.0154, -0.0918,
  72759. -0.0533, 0.0596, -0.5411,
  72760. 0.0352, -0.0631, 0.5460,
  72761. -0.4776, 0.2847, -0.0271
  72762. ];
  72763. var samplesFactor = 1.0 / numSamples;
  72764. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72765. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72766. "area", "fallOff", "base", "range", "viewport"
  72767. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72768. this._ssaoPostProcess.onApply = function (effect) {
  72769. if (_this._firstUpdate) {
  72770. effect.setArray3("sampleSphere", sampleSphere);
  72771. effect.setFloat("samplesFactor", samplesFactor);
  72772. effect.setFloat("randTextureTiles", 4.0);
  72773. }
  72774. effect.setFloat("totalStrength", _this.totalStrength);
  72775. effect.setFloat("radius", _this.radius);
  72776. effect.setFloat("area", _this.area);
  72777. effect.setFloat("fallOff", _this.fallOff);
  72778. effect.setFloat("base", _this.base);
  72779. effect.setTexture("textureSampler", _this._depthTexture);
  72780. effect.setTexture("randomSampler", _this._randomTexture);
  72781. };
  72782. };
  72783. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72784. var _this = this;
  72785. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72786. this._ssaoCombinePostProcess.onApply = function (effect) {
  72787. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  72788. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72789. };
  72790. };
  72791. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72792. var size = 512;
  72793. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72794. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72795. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72796. var context = this._randomTexture.getContext();
  72797. var rand = function (min, max) {
  72798. return Math.random() * (max - min) + min;
  72799. };
  72800. var randVector = BABYLON.Vector3.Zero();
  72801. for (var x = 0; x < size; x++) {
  72802. for (var y = 0; y < size; y++) {
  72803. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72804. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72805. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72806. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72807. context.fillRect(x, y, 1, 1);
  72808. }
  72809. }
  72810. this._randomTexture.update(false);
  72811. };
  72812. __decorate([
  72813. BABYLON.serialize()
  72814. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72815. __decorate([
  72816. BABYLON.serialize()
  72817. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72818. __decorate([
  72819. BABYLON.serialize()
  72820. ], SSAORenderingPipeline.prototype, "area", void 0);
  72821. __decorate([
  72822. BABYLON.serialize()
  72823. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72824. __decorate([
  72825. BABYLON.serialize()
  72826. ], SSAORenderingPipeline.prototype, "base", void 0);
  72827. return SSAORenderingPipeline;
  72828. }(BABYLON.PostProcessRenderPipeline));
  72829. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72830. })(BABYLON || (BABYLON = {}));
  72831. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72832. var BABYLON;
  72833. (function (BABYLON) {
  72834. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72835. __extends(SSAO2RenderingPipeline, _super);
  72836. /**
  72837. * @constructor
  72838. * @param {string} name - The rendering pipeline name
  72839. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72840. * @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 }
  72841. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72842. */
  72843. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72844. var _this = _super.call(this, scene.getEngine(), name) || this;
  72845. // Members
  72846. /**
  72847. * The PassPostProcess id in the pipeline that contains the original scene color
  72848. */
  72849. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72850. /**
  72851. * The SSAO PostProcess id in the pipeline
  72852. */
  72853. _this.SSAORenderEffect = "SSAORenderEffect";
  72854. /**
  72855. * The horizontal blur PostProcess id in the pipeline
  72856. */
  72857. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72858. /**
  72859. * The vertical blur PostProcess id in the pipeline
  72860. */
  72861. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72862. /**
  72863. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72864. */
  72865. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72866. /**
  72867. * The output strength of the SSAO post-process. Default value is 1.0.
  72868. */
  72869. _this.totalStrength = 1.0;
  72870. /**
  72871. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72872. */
  72873. _this.maxZ = 100.0;
  72874. /**
  72875. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72876. */
  72877. _this.minZAspect = 0.2;
  72878. /**
  72879. * Number of samples used for the SSAO calculations. Default value is 8
  72880. */
  72881. _this._samples = 8;
  72882. /**
  72883. * Are we using bilateral blur ?
  72884. */
  72885. _this._expensiveBlur = true;
  72886. /**
  72887. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72888. */
  72889. _this.radius = 2.0;
  72890. /**
  72891. * The base color of the SSAO post-process
  72892. * The final result is "base + ssao" between [0, 1]
  72893. */
  72894. _this.base = 0.1;
  72895. _this._firstUpdate = true;
  72896. _this._scene = scene;
  72897. _this._ratio = ratio;
  72898. if (!_this.isSupported) {
  72899. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72900. return _this;
  72901. }
  72902. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  72903. var blurRatio = _this._ratio.blurRatio || ratio;
  72904. // Set up assets
  72905. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72906. _this._createRandomTexture();
  72907. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72908. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72909. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72910. _this._createSSAOPostProcess(1.0);
  72911. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72912. _this._createSSAOCombinePostProcess(blurRatio);
  72913. // Set up pipeline
  72914. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72915. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72916. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72917. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72918. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72919. // Finish
  72920. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72921. if (cameras)
  72922. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72923. return _this;
  72924. }
  72925. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72926. get: function () {
  72927. return this._samples;
  72928. },
  72929. set: function (n) {
  72930. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72931. this._samples = n;
  72932. this._sampleSphere = this._generateHemisphere();
  72933. this._firstUpdate = true;
  72934. },
  72935. enumerable: true,
  72936. configurable: true
  72937. });
  72938. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72939. get: function () {
  72940. return this._expensiveBlur;
  72941. },
  72942. set: function (b) {
  72943. 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"]);
  72944. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72945. this._expensiveBlur = b;
  72946. this._firstUpdate = true;
  72947. },
  72948. enumerable: true,
  72949. configurable: true
  72950. });
  72951. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72952. /**
  72953. * Support test.
  72954. */
  72955. get: function () {
  72956. var engine = BABYLON.Engine.LastCreatedEngine;
  72957. if (!engine) {
  72958. return false;
  72959. }
  72960. return engine.getCaps().drawBuffersExtension;
  72961. },
  72962. enumerable: true,
  72963. configurable: true
  72964. });
  72965. // Public Methods
  72966. /**
  72967. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72968. */
  72969. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72970. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72971. for (var i = 0; i < this._scene.cameras.length; i++) {
  72972. var camera = this._scene.cameras[i];
  72973. this._originalColorPostProcess.dispose(camera);
  72974. this._ssaoPostProcess.dispose(camera);
  72975. this._blurHPostProcess.dispose(camera);
  72976. this._blurVPostProcess.dispose(camera);
  72977. this._ssaoCombinePostProcess.dispose(camera);
  72978. }
  72979. this._randomTexture.dispose();
  72980. if (disableGeometryBufferRenderer)
  72981. this._scene.disableGeometryBufferRenderer();
  72982. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72983. _super.prototype.dispose.call(this);
  72984. };
  72985. // Private Methods
  72986. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72987. var _this = this;
  72988. this._samplerOffsets = [];
  72989. var expensive = this.expensiveBlur;
  72990. for (var i = -8; i < 8; i++) {
  72991. this._samplerOffsets.push(i * 2 + 0.5);
  72992. }
  72993. 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");
  72994. this._blurHPostProcess.onApply = function (effect) {
  72995. if (!_this._scene.activeCamera) {
  72996. return;
  72997. }
  72998. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72999. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73000. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73001. effect.setFloat("radius", _this.radius);
  73002. effect.setTexture("depthSampler", _this._depthTexture);
  73003. if (_this._firstUpdate) {
  73004. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73005. }
  73006. };
  73007. 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");
  73008. this._blurVPostProcess.onApply = function (effect) {
  73009. if (!_this._scene.activeCamera) {
  73010. return;
  73011. }
  73012. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73013. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73014. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73015. effect.setFloat("radius", _this.radius);
  73016. effect.setTexture("depthSampler", _this._depthTexture);
  73017. if (_this._firstUpdate) {
  73018. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73019. _this._firstUpdate = false;
  73020. }
  73021. };
  73022. };
  73023. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73024. this._firstUpdate = true;
  73025. _super.prototype._rebuild.call(this);
  73026. };
  73027. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73028. var numSamples = this.samples;
  73029. var result = [];
  73030. var vector, scale;
  73031. var rand = function (min, max) {
  73032. return Math.random() * (max - min) + min;
  73033. };
  73034. var i = 0;
  73035. while (i < numSamples) {
  73036. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73037. vector.normalize();
  73038. scale = i / numSamples;
  73039. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73040. vector.scaleInPlace(scale);
  73041. result.push(vector.x, vector.y, vector.z);
  73042. i++;
  73043. }
  73044. return result;
  73045. };
  73046. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73047. var _this = this;
  73048. var numSamples = this.samples;
  73049. this._sampleSphere = this._generateHemisphere();
  73050. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73051. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73052. "base", "range", "projection", "near", "far", "texelSize",
  73053. "xViewport", "yViewport", "maxZ", "minZAspect"
  73054. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73055. this._ssaoPostProcess.onApply = function (effect) {
  73056. if (_this._firstUpdate) {
  73057. effect.setArray3("sampleSphere", _this._sampleSphere);
  73058. effect.setFloat("randTextureTiles", 4.0);
  73059. }
  73060. if (!_this._scene.activeCamera) {
  73061. return;
  73062. }
  73063. effect.setFloat("samplesFactor", 1 / _this.samples);
  73064. effect.setFloat("totalStrength", _this.totalStrength);
  73065. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73066. effect.setFloat("radius", _this.radius);
  73067. effect.setFloat("maxZ", _this.maxZ);
  73068. effect.setFloat("minZAspect", _this.minZAspect);
  73069. effect.setFloat("base", _this.base);
  73070. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73071. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73072. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73073. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73074. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73075. effect.setTexture("textureSampler", _this._depthTexture);
  73076. effect.setTexture("normalSampler", _this._normalTexture);
  73077. effect.setTexture("randomSampler", _this._randomTexture);
  73078. };
  73079. };
  73080. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73081. var _this = this;
  73082. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73083. this._ssaoCombinePostProcess.onApply = function (effect) {
  73084. var viewport = _this._scene.activeCamera.viewport;
  73085. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73086. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73087. };
  73088. };
  73089. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73090. var size = 512;
  73091. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73092. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73093. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73094. var context = this._randomTexture.getContext();
  73095. var rand = function (min, max) {
  73096. return Math.random() * (max - min) + min;
  73097. };
  73098. var randVector = BABYLON.Vector3.Zero();
  73099. for (var x = 0; x < size; x++) {
  73100. for (var y = 0; y < size; y++) {
  73101. randVector.x = rand(0.0, 1.0);
  73102. randVector.y = rand(0.0, 1.0);
  73103. randVector.z = 0.0;
  73104. randVector.normalize();
  73105. randVector.scaleInPlace(255);
  73106. randVector.x = Math.floor(randVector.x);
  73107. randVector.y = Math.floor(randVector.y);
  73108. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73109. context.fillRect(x, y, 1, 1);
  73110. }
  73111. }
  73112. this._randomTexture.update(false);
  73113. };
  73114. /**
  73115. * Serialize the rendering pipeline (Used when exporting)
  73116. * @returns the serialized object
  73117. */
  73118. SSAO2RenderingPipeline.prototype.serialize = function () {
  73119. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73120. serializationObject.customType = "SSAO2RenderingPipeline";
  73121. return serializationObject;
  73122. };
  73123. /**
  73124. * Parse the serialized pipeline
  73125. * @param source Source pipeline.
  73126. * @param scene The scene to load the pipeline to.
  73127. * @param rootUrl The URL of the serialized pipeline.
  73128. * @returns An instantiated pipeline from the serialized object.
  73129. */
  73130. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73131. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73132. };
  73133. __decorate([
  73134. BABYLON.serialize()
  73135. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73136. __decorate([
  73137. BABYLON.serialize()
  73138. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73139. __decorate([
  73140. BABYLON.serialize()
  73141. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73142. __decorate([
  73143. BABYLON.serialize("samples")
  73144. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73145. __decorate([
  73146. BABYLON.serialize()
  73147. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73148. __decorate([
  73149. BABYLON.serialize("expensiveBlur")
  73150. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73151. __decorate([
  73152. BABYLON.serialize()
  73153. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73154. __decorate([
  73155. BABYLON.serialize()
  73156. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73157. return SSAO2RenderingPipeline;
  73158. }(BABYLON.PostProcessRenderPipeline));
  73159. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73160. })(BABYLON || (BABYLON = {}));
  73161. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73162. // BABYLON.JS Chromatic Aberration GLSL Shader
  73163. // Author: Olivier Guyot
  73164. // Separates very slightly R, G and B colors on the edges of the screen
  73165. // Inspired by Francois Tarlier & Martins Upitis
  73166. var BABYLON;
  73167. (function (BABYLON) {
  73168. var LensRenderingPipeline = /** @class */ (function (_super) {
  73169. __extends(LensRenderingPipeline, _super);
  73170. /**
  73171. * @constructor
  73172. *
  73173. * Effect parameters are as follow:
  73174. * {
  73175. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73176. * edge_blur: number; // from 0 to x (1 for realism)
  73177. * distortion: number; // from 0 to x (1 for realism)
  73178. * grain_amount: number; // from 0 to 1
  73179. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73180. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73181. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73182. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73183. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73184. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73185. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73186. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73187. * }
  73188. * Note: if an effect parameter is unset, effect is disabled
  73189. *
  73190. * @param {string} name - The rendering pipeline name
  73191. * @param {object} parameters - An object containing all parameters (see above)
  73192. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73193. * @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)
  73194. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73195. */
  73196. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73197. if (ratio === void 0) { ratio = 1.0; }
  73198. var _this = _super.call(this, scene.getEngine(), name) || this;
  73199. // Lens effects can be of the following:
  73200. // - chromatic aberration (slight shift of RGB colors)
  73201. // - blur on the edge of the lens
  73202. // - lens distortion
  73203. // - depth-of-field blur & highlights enhancing
  73204. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73205. // - grain effect (noise or custom texture)
  73206. // Two additional texture samplers are needed:
  73207. // - depth map (for depth-of-field)
  73208. // - grain texture
  73209. /**
  73210. * The chromatic aberration PostProcess id in the pipeline
  73211. */
  73212. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73213. /**
  73214. * The highlights enhancing PostProcess id in the pipeline
  73215. */
  73216. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73217. /**
  73218. * The depth-of-field PostProcess id in the pipeline
  73219. */
  73220. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73221. _this._scene = scene;
  73222. // Fetch texture samplers
  73223. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73224. if (parameters.grain_texture) {
  73225. _this._grainTexture = parameters.grain_texture;
  73226. }
  73227. else {
  73228. _this._createGrainTexture();
  73229. }
  73230. // save parameters
  73231. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73232. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73233. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73234. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73235. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73236. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73237. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73238. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73239. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73240. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73241. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73242. // Create effects
  73243. _this._createChromaticAberrationPostProcess(ratio);
  73244. _this._createHighlightsPostProcess(ratio);
  73245. _this._createDepthOfFieldPostProcess(ratio / 4);
  73246. // Set up pipeline
  73247. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73248. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73249. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73250. if (_this._highlightsGain === -1) {
  73251. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73252. }
  73253. // Finish
  73254. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73255. if (cameras) {
  73256. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73257. }
  73258. return _this;
  73259. }
  73260. // public methods (self explanatory)
  73261. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73262. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73263. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73264. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73265. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73266. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73267. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73268. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73269. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73270. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73271. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73272. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73273. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73274. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73275. };
  73276. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73277. this._highlightsPostProcess.updateEffect();
  73278. };
  73279. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73280. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73281. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73282. this._highlightsGain = amount;
  73283. };
  73284. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73285. if (this._highlightsGain === -1) {
  73286. this._highlightsGain = 1.0;
  73287. }
  73288. this._highlightsThreshold = amount;
  73289. };
  73290. LensRenderingPipeline.prototype.disableHighlights = function () {
  73291. this._highlightsGain = -1;
  73292. };
  73293. /**
  73294. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73295. */
  73296. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73297. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73298. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73299. this._chromaticAberrationPostProcess = null;
  73300. this._highlightsPostProcess = null;
  73301. this._depthOfFieldPostProcess = null;
  73302. this._grainTexture.dispose();
  73303. if (disableDepthRender)
  73304. this._scene.disableDepthRenderer();
  73305. };
  73306. // colors shifting and distortion
  73307. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73308. var _this = this;
  73309. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73310. [], // samplers
  73311. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73312. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73313. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73314. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73315. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73316. effect.setFloat('radialIntensity', 1);
  73317. effect.setFloat2('direction', 17, 17);
  73318. effect.setFloat2('centerPosition', 0.5, 0.5);
  73319. };
  73320. };
  73321. // highlights enhancing
  73322. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73323. var _this = this;
  73324. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73325. [], // samplers
  73326. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73327. this._highlightsPostProcess.onApply = function (effect) {
  73328. effect.setFloat('gain', _this._highlightsGain);
  73329. effect.setFloat('threshold', _this._highlightsThreshold);
  73330. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73331. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73332. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73333. };
  73334. };
  73335. // colors shifting and distortion
  73336. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73337. var _this = this;
  73338. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73339. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73340. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73341. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73342. this._depthOfFieldPostProcess.onApply = function (effect) {
  73343. effect.setTexture("depthSampler", _this._depthTexture);
  73344. effect.setTexture("grainSampler", _this._grainTexture);
  73345. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73346. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73347. effect.setFloat('grain_amount', _this._grainAmount);
  73348. effect.setBool('blur_noise', _this._blurNoise);
  73349. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73350. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73351. effect.setFloat('distortion', _this._distortion);
  73352. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73353. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73354. effect.setFloat('aperture', _this._dofAperture);
  73355. effect.setFloat('darken', _this._dofDarken);
  73356. effect.setFloat('edge_blur', _this._edgeBlur);
  73357. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73358. if (_this._scene.activeCamera) {
  73359. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73360. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73361. }
  73362. };
  73363. };
  73364. // creates a black and white random noise texture, 512x512
  73365. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73366. var size = 512;
  73367. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73368. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73369. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73370. var context = this._grainTexture.getContext();
  73371. var rand = function (min, max) {
  73372. return Math.random() * (max - min) + min;
  73373. };
  73374. var value;
  73375. for (var x = 0; x < size; x++) {
  73376. for (var y = 0; y < size; y++) {
  73377. value = Math.floor(rand(0.42, 0.58) * 255);
  73378. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73379. context.fillRect(x, y, 1, 1);
  73380. }
  73381. }
  73382. this._grainTexture.update(false);
  73383. };
  73384. return LensRenderingPipeline;
  73385. }(BABYLON.PostProcessRenderPipeline));
  73386. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73387. })(BABYLON || (BABYLON = {}));
  73388. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73389. var BABYLON;
  73390. (function (BABYLON) {
  73391. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73392. __extends(StandardRenderingPipeline, _super);
  73393. /**
  73394. * @constructor
  73395. * @param {string} name - The rendering pipeline name
  73396. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73397. * @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)
  73398. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73399. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73400. */
  73401. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73402. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73403. var _this = _super.call(this, scene.getEngine(), name) || this;
  73404. _this.downSampleX4PostProcess = null;
  73405. _this.brightPassPostProcess = null;
  73406. _this.blurHPostProcesses = [];
  73407. _this.blurVPostProcesses = [];
  73408. _this.textureAdderPostProcess = null;
  73409. _this.volumetricLightPostProcess = null;
  73410. _this.volumetricLightSmoothXPostProcess = null;
  73411. _this.volumetricLightSmoothYPostProcess = null;
  73412. _this.volumetricLightMergePostProces = null;
  73413. _this.volumetricLightFinalPostProcess = null;
  73414. _this.luminancePostProcess = null;
  73415. _this.luminanceDownSamplePostProcesses = [];
  73416. _this.hdrPostProcess = null;
  73417. _this.textureAdderFinalPostProcess = null;
  73418. _this.lensFlareFinalPostProcess = null;
  73419. _this.hdrFinalPostProcess = null;
  73420. _this.lensFlarePostProcess = null;
  73421. _this.lensFlareComposePostProcess = null;
  73422. _this.motionBlurPostProcess = null;
  73423. _this.depthOfFieldPostProcess = null;
  73424. // Values
  73425. _this.brightThreshold = 1.0;
  73426. _this.blurWidth = 512.0;
  73427. _this.horizontalBlur = false;
  73428. _this.exposure = 1.0;
  73429. _this.lensTexture = null;
  73430. _this.volumetricLightCoefficient = 0.2;
  73431. _this.volumetricLightPower = 4.0;
  73432. _this.volumetricLightBlurScale = 64.0;
  73433. _this.sourceLight = null;
  73434. _this.hdrMinimumLuminance = 1.0;
  73435. _this.hdrDecreaseRate = 0.5;
  73436. _this.hdrIncreaseRate = 0.5;
  73437. _this.lensColorTexture = null;
  73438. _this.lensFlareStrength = 20.0;
  73439. _this.lensFlareGhostDispersal = 1.4;
  73440. _this.lensFlareHaloWidth = 0.7;
  73441. _this.lensFlareDistortionStrength = 16.0;
  73442. _this.lensStarTexture = null;
  73443. _this.lensFlareDirtTexture = null;
  73444. _this.depthOfFieldDistance = 10.0;
  73445. _this.depthOfFieldBlurWidth = 64.0;
  73446. _this.motionStrength = 1.0;
  73447. // IAnimatable
  73448. _this.animations = [];
  73449. _this._currentDepthOfFieldSource = null;
  73450. _this._hdrCurrentLuminance = 1.0;
  73451. // Getters and setters
  73452. _this._bloomEnabled = true;
  73453. _this._depthOfFieldEnabled = false;
  73454. _this._vlsEnabled = false;
  73455. _this._lensFlareEnabled = false;
  73456. _this._hdrEnabled = false;
  73457. _this._motionBlurEnabled = false;
  73458. _this._motionBlurSamples = 64.0;
  73459. _this._volumetricLightStepsCount = 50.0;
  73460. _this._cameras = cameras || [];
  73461. // Initialize
  73462. _this._scene = scene;
  73463. _this._basePostProcess = originalPostProcess;
  73464. _this._ratio = ratio;
  73465. // Misc
  73466. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73467. // Finish
  73468. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73469. _this._buildPipeline();
  73470. return _this;
  73471. }
  73472. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73473. get: function () {
  73474. return this._bloomEnabled;
  73475. },
  73476. set: function (enabled) {
  73477. if (this._bloomEnabled === enabled) {
  73478. return;
  73479. }
  73480. this._bloomEnabled = enabled;
  73481. this._buildPipeline();
  73482. },
  73483. enumerable: true,
  73484. configurable: true
  73485. });
  73486. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73487. get: function () {
  73488. return this._depthOfFieldEnabled;
  73489. },
  73490. set: function (enabled) {
  73491. if (this._depthOfFieldEnabled === enabled) {
  73492. return;
  73493. }
  73494. this._depthOfFieldEnabled = enabled;
  73495. this._buildPipeline();
  73496. },
  73497. enumerable: true,
  73498. configurable: true
  73499. });
  73500. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73501. get: function () {
  73502. return this._lensFlareEnabled;
  73503. },
  73504. set: function (enabled) {
  73505. if (this._lensFlareEnabled === enabled) {
  73506. return;
  73507. }
  73508. this._lensFlareEnabled = enabled;
  73509. this._buildPipeline();
  73510. },
  73511. enumerable: true,
  73512. configurable: true
  73513. });
  73514. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73515. get: function () {
  73516. return this._hdrEnabled;
  73517. },
  73518. set: function (enabled) {
  73519. if (this._hdrEnabled === enabled) {
  73520. return;
  73521. }
  73522. this._hdrEnabled = enabled;
  73523. this._buildPipeline();
  73524. },
  73525. enumerable: true,
  73526. configurable: true
  73527. });
  73528. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73529. get: function () {
  73530. return this._vlsEnabled;
  73531. },
  73532. set: function (enabled) {
  73533. if (this._vlsEnabled === enabled) {
  73534. return;
  73535. }
  73536. if (enabled) {
  73537. var geometry = this._scene.enableGeometryBufferRenderer();
  73538. if (!geometry) {
  73539. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73540. return;
  73541. }
  73542. }
  73543. this._vlsEnabled = enabled;
  73544. this._buildPipeline();
  73545. },
  73546. enumerable: true,
  73547. configurable: true
  73548. });
  73549. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73550. get: function () {
  73551. return this._motionBlurEnabled;
  73552. },
  73553. set: function (enabled) {
  73554. if (this._motionBlurEnabled === enabled) {
  73555. return;
  73556. }
  73557. this._motionBlurEnabled = enabled;
  73558. this._buildPipeline();
  73559. },
  73560. enumerable: true,
  73561. configurable: true
  73562. });
  73563. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73564. get: function () {
  73565. return this._volumetricLightStepsCount;
  73566. },
  73567. set: function (count) {
  73568. if (this.volumetricLightPostProcess) {
  73569. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73570. }
  73571. this._volumetricLightStepsCount = count;
  73572. },
  73573. enumerable: true,
  73574. configurable: true
  73575. });
  73576. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73577. get: function () {
  73578. return this._motionBlurSamples;
  73579. },
  73580. set: function (samples) {
  73581. if (this.motionBlurPostProcess) {
  73582. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73583. }
  73584. this._motionBlurSamples = samples;
  73585. },
  73586. enumerable: true,
  73587. configurable: true
  73588. });
  73589. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73590. var _this = this;
  73591. var ratio = this._ratio;
  73592. var scene = this._scene;
  73593. this._disposePostProcesses();
  73594. this._reset();
  73595. // Create pass post-process
  73596. if (!this._basePostProcess) {
  73597. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73598. this.originalPostProcess.onApply = function (effect) {
  73599. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73600. };
  73601. }
  73602. else {
  73603. this.originalPostProcess = this._basePostProcess;
  73604. }
  73605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73606. this._currentDepthOfFieldSource = this.originalPostProcess;
  73607. if (this._bloomEnabled) {
  73608. // Create down sample X4 post-process
  73609. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73610. // Create bright pass post-process
  73611. this._createBrightPassPostProcess(scene, ratio / 2);
  73612. // Create gaussian blur post-processes (down sampling blurs)
  73613. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73614. // Create texture adder post-process
  73615. this._createTextureAdderPostProcess(scene, ratio);
  73616. // Create depth-of-field source post-process
  73617. 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);
  73618. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73619. }
  73620. if (this._vlsEnabled) {
  73621. // Create volumetric light
  73622. this._createVolumetricLightPostProcess(scene, ratio);
  73623. // Create volumetric light final post-process
  73624. 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);
  73625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73626. }
  73627. if (this._lensFlareEnabled) {
  73628. // Create lens flare post-process
  73629. this._createLensFlarePostProcess(scene, ratio);
  73630. // Create depth-of-field source post-process post lens-flare and disable it now
  73631. 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);
  73632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73633. }
  73634. if (this._hdrEnabled) {
  73635. // Create luminance
  73636. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73637. // Create HDR
  73638. this._createHdrPostProcess(scene, ratio);
  73639. // Create depth-of-field source post-process post hdr and disable it now
  73640. 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);
  73641. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73642. }
  73643. if (this._depthOfFieldEnabled) {
  73644. // Create gaussian blur used by depth-of-field
  73645. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73646. // Create depth-of-field post-process
  73647. this._createDepthOfFieldPostProcess(scene, ratio);
  73648. }
  73649. if (this._motionBlurEnabled) {
  73650. // Create motion blur post-process
  73651. this._createMotionBlurPostProcess(scene, ratio);
  73652. }
  73653. if (this._cameras !== null) {
  73654. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73655. }
  73656. };
  73657. // Down Sample X4 Post-Processs
  73658. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73659. var _this = this;
  73660. var downSampleX4Offsets = new Array(32);
  73661. 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);
  73662. this.downSampleX4PostProcess.onApply = function (effect) {
  73663. var id = 0;
  73664. var width = _this.downSampleX4PostProcess.width;
  73665. var height = _this.downSampleX4PostProcess.height;
  73666. for (var i = -2; i < 2; i++) {
  73667. for (var j = -2; j < 2; j++) {
  73668. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73669. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73670. id += 2;
  73671. }
  73672. }
  73673. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73674. };
  73675. // Add to pipeline
  73676. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73677. };
  73678. // Brightpass Post-Process
  73679. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73680. var _this = this;
  73681. var brightOffsets = new Array(8);
  73682. 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);
  73683. this.brightPassPostProcess.onApply = function (effect) {
  73684. var sU = (1.0 / _this.brightPassPostProcess.width);
  73685. var sV = (1.0 / _this.brightPassPostProcess.height);
  73686. brightOffsets[0] = -0.5 * sU;
  73687. brightOffsets[1] = 0.5 * sV;
  73688. brightOffsets[2] = 0.5 * sU;
  73689. brightOffsets[3] = 0.5 * sV;
  73690. brightOffsets[4] = -0.5 * sU;
  73691. brightOffsets[5] = -0.5 * sV;
  73692. brightOffsets[6] = 0.5 * sU;
  73693. brightOffsets[7] = -0.5 * sV;
  73694. effect.setArray2("dsOffsets", brightOffsets);
  73695. effect.setFloat("brightThreshold", _this.brightThreshold);
  73696. };
  73697. // Add to pipeline
  73698. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73699. };
  73700. // Create blur H&V post-processes
  73701. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73702. var _this = this;
  73703. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73704. var engine = scene.getEngine();
  73705. 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);
  73706. 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);
  73707. blurX.onActivateObservable.add(function () {
  73708. var dw = blurX.width / engine.getRenderWidth();
  73709. blurX.kernel = _this[blurWidthKey] * dw;
  73710. });
  73711. blurY.onActivateObservable.add(function () {
  73712. var dw = blurY.height / engine.getRenderHeight();
  73713. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73714. });
  73715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73717. this.blurHPostProcesses.push(blurX);
  73718. this.blurVPostProcesses.push(blurY);
  73719. };
  73720. // Create texture adder post-process
  73721. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73722. var _this = this;
  73723. 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);
  73724. this.textureAdderPostProcess.onApply = function (effect) {
  73725. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73726. effect.setTexture("lensSampler", _this.lensTexture);
  73727. effect.setFloat("exposure", _this.exposure);
  73728. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73729. };
  73730. // Add to pipeline
  73731. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73732. };
  73733. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73734. var _this = this;
  73735. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73736. geometryRenderer.enablePosition = true;
  73737. var geometry = geometryRenderer.getGBuffer();
  73738. // Base post-process
  73739. 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));
  73740. var depthValues = BABYLON.Vector2.Zero();
  73741. this.volumetricLightPostProcess.onApply = function (effect) {
  73742. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73743. var generator = _this.sourceLight.getShadowGenerator();
  73744. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73745. effect.setTexture("positionSampler", geometry.textures[2]);
  73746. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73747. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73748. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73749. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73750. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73751. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73752. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73753. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73754. effect.setVector2("depthValues", depthValues);
  73755. }
  73756. };
  73757. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73758. // Smooth
  73759. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73760. // Merge
  73761. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73762. this.volumetricLightMergePostProces.onApply = function (effect) {
  73763. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  73764. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73765. };
  73766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73767. };
  73768. // Create luminance
  73769. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73770. var _this = this;
  73771. // Create luminance
  73772. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73773. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73774. var offsets = [];
  73775. this.luminancePostProcess.onApply = function (effect) {
  73776. var sU = (1.0 / _this.luminancePostProcess.width);
  73777. var sV = (1.0 / _this.luminancePostProcess.height);
  73778. offsets[0] = -0.5 * sU;
  73779. offsets[1] = 0.5 * sV;
  73780. offsets[2] = 0.5 * sU;
  73781. offsets[3] = 0.5 * sV;
  73782. offsets[4] = -0.5 * sU;
  73783. offsets[5] = -0.5 * sV;
  73784. offsets[6] = 0.5 * sU;
  73785. offsets[7] = -0.5 * sV;
  73786. effect.setArray2("lumOffsets", offsets);
  73787. };
  73788. // Add to pipeline
  73789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73790. // Create down sample luminance
  73791. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73792. var size = Math.pow(3, i);
  73793. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73794. if (i === 0) {
  73795. defines += "#define FINAL_DOWN_SAMPLER";
  73796. }
  73797. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73798. this.luminanceDownSamplePostProcesses.push(postProcess);
  73799. }
  73800. // Create callbacks and add effects
  73801. var lastLuminance = this.luminancePostProcess;
  73802. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73803. var downSampleOffsets = new Array(18);
  73804. pp.onApply = function (effect) {
  73805. if (!lastLuminance) {
  73806. return;
  73807. }
  73808. var id = 0;
  73809. for (var x = -1; x < 2; x++) {
  73810. for (var y = -1; y < 2; y++) {
  73811. downSampleOffsets[id] = x / lastLuminance.width;
  73812. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73813. id += 2;
  73814. }
  73815. }
  73816. effect.setArray2("dsOffsets", downSampleOffsets);
  73817. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73818. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73819. lastLuminance = _this.luminancePostProcess;
  73820. }
  73821. else {
  73822. lastLuminance = pp;
  73823. }
  73824. };
  73825. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73826. pp.onAfterRender = function (effect) {
  73827. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73828. 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);
  73829. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73830. };
  73831. }
  73832. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73833. });
  73834. };
  73835. // Create HDR post-process
  73836. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73837. var _this = this;
  73838. 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);
  73839. var outputLiminance = 1;
  73840. var time = 0;
  73841. var lastTime = 0;
  73842. this.hdrPostProcess.onApply = function (effect) {
  73843. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73844. time += scene.getEngine().getDeltaTime();
  73845. if (outputLiminance < 0) {
  73846. outputLiminance = _this._hdrCurrentLuminance;
  73847. }
  73848. else {
  73849. var dt = (lastTime - time) / 1000.0;
  73850. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73851. outputLiminance += _this.hdrDecreaseRate * dt;
  73852. }
  73853. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73854. outputLiminance -= _this.hdrIncreaseRate * dt;
  73855. }
  73856. else {
  73857. outputLiminance = _this._hdrCurrentLuminance;
  73858. }
  73859. }
  73860. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73861. effect.setFloat("averageLuminance", outputLiminance);
  73862. lastTime = time;
  73863. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73864. };
  73865. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73866. };
  73867. // Create lens flare post-process
  73868. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73869. var _this = this;
  73870. 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);
  73871. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73872. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73873. 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);
  73874. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73875. var resolution = new BABYLON.Vector2(0, 0);
  73876. // Lens flare
  73877. this.lensFlarePostProcess.onApply = function (effect) {
  73878. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73879. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73880. effect.setFloat("strength", _this.lensFlareStrength);
  73881. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73882. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73883. // Shift
  73884. resolution.x = _this.lensFlarePostProcess.width;
  73885. resolution.y = _this.lensFlarePostProcess.height;
  73886. effect.setVector2("resolution", resolution);
  73887. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73888. };
  73889. // Compose
  73890. 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);
  73891. 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);
  73892. this.lensFlareComposePostProcess.onApply = function (effect) {
  73893. if (!_this._scene.activeCamera) {
  73894. return;
  73895. }
  73896. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73897. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73898. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73899. // Lens start rotation matrix
  73900. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73901. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73902. 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));
  73903. camRot *= 4.0;
  73904. 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);
  73905. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73906. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73907. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73908. };
  73909. };
  73910. // Create depth-of-field post-process
  73911. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73912. var _this = this;
  73913. 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);
  73914. this.depthOfFieldPostProcess.onApply = function (effect) {
  73915. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73916. effect.setTexture("depthSampler", _this._getDepthTexture());
  73917. effect.setFloat("distance", _this.depthOfFieldDistance);
  73918. };
  73919. // Add to pipeline
  73920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73921. };
  73922. // Create motion blur post-process
  73923. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73924. var _this = this;
  73925. 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);
  73926. var motionScale = 0;
  73927. var prevViewProjection = BABYLON.Matrix.Identity();
  73928. var invViewProjection = BABYLON.Matrix.Identity();
  73929. var viewProjection = BABYLON.Matrix.Identity();
  73930. var screenSize = BABYLON.Vector2.Zero();
  73931. this.motionBlurPostProcess.onApply = function (effect) {
  73932. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73933. viewProjection.invertToRef(invViewProjection);
  73934. effect.setMatrix("inverseViewProjection", invViewProjection);
  73935. effect.setMatrix("prevViewProjection", prevViewProjection);
  73936. prevViewProjection = viewProjection;
  73937. screenSize.x = _this.motionBlurPostProcess.width;
  73938. screenSize.y = _this.motionBlurPostProcess.height;
  73939. effect.setVector2("screenSize", screenSize);
  73940. motionScale = scene.getEngine().getFps() / 60.0;
  73941. effect.setFloat("motionScale", motionScale);
  73942. effect.setFloat("motionStrength", _this.motionStrength);
  73943. effect.setTexture("depthSampler", _this._getDepthTexture());
  73944. };
  73945. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73946. };
  73947. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73948. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73949. var renderer = this._scene.enableGeometryBufferRenderer();
  73950. return renderer.getGBuffer().textures[0];
  73951. }
  73952. return this._scene.enableDepthRenderer().getDepthMap();
  73953. };
  73954. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73955. for (var i = 0; i < this._cameras.length; i++) {
  73956. var camera = this._cameras[i];
  73957. if (this.originalPostProcess) {
  73958. this.originalPostProcess.dispose(camera);
  73959. }
  73960. if (this.downSampleX4PostProcess) {
  73961. this.downSampleX4PostProcess.dispose(camera);
  73962. }
  73963. if (this.brightPassPostProcess) {
  73964. this.brightPassPostProcess.dispose(camera);
  73965. }
  73966. if (this.textureAdderPostProcess) {
  73967. this.textureAdderPostProcess.dispose(camera);
  73968. }
  73969. if (this.textureAdderFinalPostProcess) {
  73970. this.textureAdderFinalPostProcess.dispose(camera);
  73971. }
  73972. if (this.volumetricLightPostProcess) {
  73973. this.volumetricLightPostProcess.dispose(camera);
  73974. }
  73975. if (this.volumetricLightSmoothXPostProcess) {
  73976. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73977. }
  73978. if (this.volumetricLightSmoothYPostProcess) {
  73979. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73980. }
  73981. if (this.volumetricLightMergePostProces) {
  73982. this.volumetricLightMergePostProces.dispose(camera);
  73983. }
  73984. if (this.volumetricLightFinalPostProcess) {
  73985. this.volumetricLightFinalPostProcess.dispose(camera);
  73986. }
  73987. if (this.lensFlarePostProcess) {
  73988. this.lensFlarePostProcess.dispose(camera);
  73989. }
  73990. if (this.lensFlareComposePostProcess) {
  73991. this.lensFlareComposePostProcess.dispose(camera);
  73992. }
  73993. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73994. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73995. }
  73996. if (this.luminancePostProcess) {
  73997. this.luminancePostProcess.dispose(camera);
  73998. }
  73999. if (this.hdrPostProcess) {
  74000. this.hdrPostProcess.dispose(camera);
  74001. }
  74002. if (this.hdrFinalPostProcess) {
  74003. this.hdrFinalPostProcess.dispose(camera);
  74004. }
  74005. if (this.depthOfFieldPostProcess) {
  74006. this.depthOfFieldPostProcess.dispose(camera);
  74007. }
  74008. if (this.motionBlurPostProcess) {
  74009. this.motionBlurPostProcess.dispose(camera);
  74010. }
  74011. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74012. this.blurHPostProcesses[j].dispose(camera);
  74013. }
  74014. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74015. this.blurVPostProcesses[j].dispose(camera);
  74016. }
  74017. }
  74018. this.originalPostProcess = null;
  74019. this.downSampleX4PostProcess = null;
  74020. this.brightPassPostProcess = null;
  74021. this.textureAdderPostProcess = null;
  74022. this.textureAdderFinalPostProcess = null;
  74023. this.volumetricLightPostProcess = null;
  74024. this.volumetricLightSmoothXPostProcess = null;
  74025. this.volumetricLightSmoothYPostProcess = null;
  74026. this.volumetricLightMergePostProces = null;
  74027. this.volumetricLightFinalPostProcess = null;
  74028. this.lensFlarePostProcess = null;
  74029. this.lensFlareComposePostProcess = null;
  74030. this.luminancePostProcess = null;
  74031. this.hdrPostProcess = null;
  74032. this.hdrFinalPostProcess = null;
  74033. this.depthOfFieldPostProcess = null;
  74034. this.motionBlurPostProcess = null;
  74035. this.luminanceDownSamplePostProcesses = [];
  74036. this.blurHPostProcesses = [];
  74037. this.blurVPostProcesses = [];
  74038. };
  74039. /**
  74040. * Dispose of the pipeline and stop all post processes
  74041. */
  74042. StandardRenderingPipeline.prototype.dispose = function () {
  74043. this._disposePostProcesses();
  74044. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74045. _super.prototype.dispose.call(this);
  74046. };
  74047. /**
  74048. * Serialize the rendering pipeline (Used when exporting)
  74049. * @returns the serialized object
  74050. */
  74051. StandardRenderingPipeline.prototype.serialize = function () {
  74052. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74053. if (this.sourceLight) {
  74054. serializationObject.sourceLightId = this.sourceLight.id;
  74055. }
  74056. serializationObject.customType = "StandardRenderingPipeline";
  74057. return serializationObject;
  74058. };
  74059. /**
  74060. * Parse the serialized pipeline
  74061. * @param source Source pipeline.
  74062. * @param scene The scene to load the pipeline to.
  74063. * @param rootUrl The URL of the serialized pipeline.
  74064. * @returns An instantiated pipeline from the serialized object.
  74065. */
  74066. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74067. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74068. if (source.sourceLightId) {
  74069. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74070. }
  74071. return p;
  74072. };
  74073. // Luminance steps
  74074. StandardRenderingPipeline.LuminanceSteps = 6;
  74075. __decorate([
  74076. BABYLON.serialize()
  74077. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74078. __decorate([
  74079. BABYLON.serialize()
  74080. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74081. __decorate([
  74082. BABYLON.serialize()
  74083. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74084. __decorate([
  74085. BABYLON.serialize()
  74086. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74087. __decorate([
  74088. BABYLON.serializeAsTexture("lensTexture")
  74089. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74090. __decorate([
  74091. BABYLON.serialize()
  74092. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74093. __decorate([
  74094. BABYLON.serialize()
  74095. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74096. __decorate([
  74097. BABYLON.serialize()
  74098. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74099. __decorate([
  74100. BABYLON.serialize()
  74101. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74102. __decorate([
  74103. BABYLON.serialize()
  74104. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74105. __decorate([
  74106. BABYLON.serialize()
  74107. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74108. __decorate([
  74109. BABYLON.serializeAsTexture("lensColorTexture")
  74110. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74111. __decorate([
  74112. BABYLON.serialize()
  74113. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74114. __decorate([
  74115. BABYLON.serialize()
  74116. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74117. __decorate([
  74118. BABYLON.serialize()
  74119. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74120. __decorate([
  74121. BABYLON.serialize()
  74122. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74123. __decorate([
  74124. BABYLON.serializeAsTexture("lensStarTexture")
  74125. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74126. __decorate([
  74127. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74128. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74129. __decorate([
  74130. BABYLON.serialize()
  74131. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74132. __decorate([
  74133. BABYLON.serialize()
  74134. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74135. __decorate([
  74136. BABYLON.serialize()
  74137. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74138. __decorate([
  74139. BABYLON.serialize()
  74140. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74141. __decorate([
  74142. BABYLON.serialize()
  74143. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74144. __decorate([
  74145. BABYLON.serialize()
  74146. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74147. __decorate([
  74148. BABYLON.serialize()
  74149. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74150. __decorate([
  74151. BABYLON.serialize()
  74152. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74153. __decorate([
  74154. BABYLON.serialize()
  74155. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74156. __decorate([
  74157. BABYLON.serialize()
  74158. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74159. __decorate([
  74160. BABYLON.serialize()
  74161. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74162. __decorate([
  74163. BABYLON.serialize()
  74164. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74165. return StandardRenderingPipeline;
  74166. }(BABYLON.PostProcessRenderPipeline));
  74167. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74168. })(BABYLON || (BABYLON = {}));
  74169. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74170. var BABYLON;
  74171. (function (BABYLON) {
  74172. var FxaaPostProcess = /** @class */ (function (_super) {
  74173. __extends(FxaaPostProcess, _super);
  74174. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74175. if (camera === void 0) { camera = null; }
  74176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74177. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74178. var defines = _this._getDefines();
  74179. _this.updateEffect(defines);
  74180. _this.onApplyObservable.add(function (effect) {
  74181. var texelSize = _this.texelSize;
  74182. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74183. });
  74184. return _this;
  74185. }
  74186. FxaaPostProcess.prototype._getDefines = function () {
  74187. var engine = this.getEngine();
  74188. if (!engine) {
  74189. return null;
  74190. }
  74191. var glInfo = engine.getGlInfo();
  74192. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74193. return "#define MALI 1\n";
  74194. }
  74195. return null;
  74196. };
  74197. return FxaaPostProcess;
  74198. }(BABYLON.PostProcess));
  74199. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74200. })(BABYLON || (BABYLON = {}));
  74201. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74202. var BABYLON;
  74203. (function (BABYLON) {
  74204. /**
  74205. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74206. */
  74207. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74208. __extends(ChromaticAberrationPostProcess, _super);
  74209. /**
  74210. * Creates a new instance ChromaticAberrationPostProcess
  74211. * @param name The name of the effect.
  74212. * @param screenWidth The width of the screen to apply the effect on.
  74213. * @param screenHeight The height of the screen to apply the effect on.
  74214. * @param options The required width/height ratio to downsize to before computing the render pass.
  74215. * @param camera The camera to apply the render pass to.
  74216. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74217. * @param engine The engine which the post process will be applied. (default: current engine)
  74218. * @param reusable If the post process can be reused on the same frame. (default: false)
  74219. * @param textureType Type of textures used when performing the post process. (default: 0)
  74220. * @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)
  74221. */
  74222. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74223. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74224. if (blockCompilation === void 0) { blockCompilation = false; }
  74225. 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;
  74226. /**
  74227. * The amount of seperation of rgb channels (default: 30)
  74228. */
  74229. _this.aberrationAmount = 30;
  74230. /**
  74231. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74232. */
  74233. _this.radialIntensity = 0;
  74234. /**
  74235. * 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))
  74236. */
  74237. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74238. /**
  74239. * 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))
  74240. */
  74241. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74242. _this.onApplyObservable.add(function (effect) {
  74243. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74244. effect.setFloat('screen_width', screenWidth);
  74245. effect.setFloat('screen_height', screenHeight);
  74246. effect.setFloat('radialIntensity', _this.radialIntensity);
  74247. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74248. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74249. });
  74250. return _this;
  74251. }
  74252. return ChromaticAberrationPostProcess;
  74253. }(BABYLON.PostProcess));
  74254. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74255. })(BABYLON || (BABYLON = {}));
  74256. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74257. var BABYLON;
  74258. (function (BABYLON) {
  74259. /**
  74260. * The GrainPostProcess adds noise to the image at mid luminance levels
  74261. */
  74262. var GrainPostProcess = /** @class */ (function (_super) {
  74263. __extends(GrainPostProcess, _super);
  74264. /**
  74265. * Creates a new instance of @see GrainPostProcess
  74266. * @param name The name of the effect.
  74267. * @param options The required width/height ratio to downsize to before computing the render pass.
  74268. * @param camera The camera to apply the render pass to.
  74269. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74270. * @param engine The engine which the post process will be applied. (default: current engine)
  74271. * @param reusable If the post process can be reused on the same frame. (default: false)
  74272. * @param textureType Type of textures used when performing the post process. (default: 0)
  74273. * @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)
  74274. */
  74275. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74276. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74277. if (blockCompilation === void 0) { blockCompilation = false; }
  74278. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74279. /**
  74280. * The intensity of the grain added (default: 30)
  74281. */
  74282. _this.intensity = 30;
  74283. /**
  74284. * If the grain should be randomized on every frame
  74285. */
  74286. _this.animated = false;
  74287. _this.onApplyObservable.add(function (effect) {
  74288. effect.setFloat('intensity', _this.intensity);
  74289. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74290. });
  74291. return _this;
  74292. }
  74293. return GrainPostProcess;
  74294. }(BABYLON.PostProcess));
  74295. BABYLON.GrainPostProcess = GrainPostProcess;
  74296. })(BABYLON || (BABYLON = {}));
  74297. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74298. var BABYLON;
  74299. (function (BABYLON) {
  74300. /**
  74301. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74302. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74303. */
  74304. var SharpenPostProcess = /** @class */ (function (_super) {
  74305. __extends(SharpenPostProcess, _super);
  74306. /**
  74307. * Creates a new instance ConvolutionPostProcess
  74308. * @param name The name of the effect.
  74309. * @param options The required width/height ratio to downsize to before computing the render pass.
  74310. * @param camera The camera to apply the render pass to.
  74311. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74312. * @param engine The engine which the post process will be applied. (default: current engine)
  74313. * @param reusable If the post process can be reused on the same frame. (default: false)
  74314. * @param textureType Type of textures used when performing the post process. (default: 0)
  74315. * @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)
  74316. */
  74317. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74318. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74319. if (blockCompilation === void 0) { blockCompilation = false; }
  74320. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74321. /**
  74322. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74323. */
  74324. _this.colorAmount = 1.0;
  74325. /**
  74326. * How much sharpness should be applied (default: 0.3)
  74327. */
  74328. _this.edgeAmount = 0.3;
  74329. _this.onApply = function (effect) {
  74330. effect.setFloat2("screenSize", _this.width, _this.height);
  74331. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74332. };
  74333. return _this;
  74334. }
  74335. return SharpenPostProcess;
  74336. }(BABYLON.PostProcess));
  74337. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74338. })(BABYLON || (BABYLON = {}));
  74339. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74340. var BABYLON;
  74341. (function (BABYLON) {
  74342. /**
  74343. * The Blur Post Process which blurs an image based on a kernel and direction.
  74344. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74345. */
  74346. var BlurPostProcess = /** @class */ (function (_super) {
  74347. __extends(BlurPostProcess, _super);
  74348. /**
  74349. * Creates a new instance BlurPostProcess
  74350. * @param name The name of the effect.
  74351. * @param direction The direction in which to blur the image.
  74352. * @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.
  74353. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74354. * @param camera The camera to apply the render pass to.
  74355. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74356. * @param engine The engine which the post process will be applied. (default: current engine)
  74357. * @param reusable If the post process can be reused on the same frame. (default: false)
  74358. * @param textureType Type of textures used when performing the post process. (default: 0)
  74359. * @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)
  74360. */
  74361. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74364. if (defines === void 0) { defines = ""; }
  74365. if (blockCompilation === void 0) { blockCompilation = false; }
  74366. 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;
  74367. _this.direction = direction;
  74368. _this.blockCompilation = blockCompilation;
  74369. _this._packedFloat = false;
  74370. _this._staticDefines = "";
  74371. _this._staticDefines = defines;
  74372. _this.onApplyObservable.add(function (effect) {
  74373. if (_this._outputTexture) {
  74374. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74375. }
  74376. else {
  74377. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74378. }
  74379. });
  74380. _this.kernel = kernel;
  74381. return _this;
  74382. }
  74383. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74384. /**
  74385. * Gets the length in pixels of the blur sample region
  74386. */
  74387. get: function () {
  74388. return this._idealKernel;
  74389. },
  74390. /**
  74391. * Sets the length in pixels of the blur sample region
  74392. */
  74393. set: function (v) {
  74394. if (this._idealKernel === v) {
  74395. return;
  74396. }
  74397. v = Math.max(v, 1);
  74398. this._idealKernel = v;
  74399. this._kernel = this._nearestBestKernel(v);
  74400. if (!this.blockCompilation) {
  74401. this._updateParameters();
  74402. }
  74403. },
  74404. enumerable: true,
  74405. configurable: true
  74406. });
  74407. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74408. /**
  74409. * Gets wether or not the blur is unpacking/repacking floats
  74410. */
  74411. get: function () {
  74412. return this._packedFloat;
  74413. },
  74414. /**
  74415. * Sets wether or not the blur needs to unpack/repack floats
  74416. */
  74417. set: function (v) {
  74418. if (this._packedFloat === v) {
  74419. return;
  74420. }
  74421. this._packedFloat = v;
  74422. if (!this.blockCompilation) {
  74423. this._updateParameters();
  74424. }
  74425. },
  74426. enumerable: true,
  74427. configurable: true
  74428. });
  74429. /**
  74430. * Updates the effect with the current post process compile time values and recompiles the shader.
  74431. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74432. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74433. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74434. * @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
  74435. * @param onCompiled Called when the shader has been compiled.
  74436. * @param onError Called if there is an error when compiling a shader.
  74437. */
  74438. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74439. if (defines === void 0) { defines = null; }
  74440. if (uniforms === void 0) { uniforms = null; }
  74441. if (samplers === void 0) { samplers = null; }
  74442. this._updateParameters(onCompiled, onError);
  74443. };
  74444. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74445. // Generate sampling offsets and weights
  74446. var N = this._kernel;
  74447. var centerIndex = (N - 1) / 2;
  74448. // Generate Gaussian sampling weights over kernel
  74449. var offsets = [];
  74450. var weights = [];
  74451. var totalWeight = 0;
  74452. for (var i = 0; i < N; i++) {
  74453. var u = i / (N - 1);
  74454. var w = this._gaussianWeight(u * 2.0 - 1);
  74455. offsets[i] = (i - centerIndex);
  74456. weights[i] = w;
  74457. totalWeight += w;
  74458. }
  74459. // Normalize weights
  74460. for (var i = 0; i < weights.length; i++) {
  74461. weights[i] /= totalWeight;
  74462. }
  74463. // Optimize: combine samples to take advantage of hardware linear sampling
  74464. // Walk from left to center, combining pairs (symmetrically)
  74465. var linearSamplingWeights = [];
  74466. var linearSamplingOffsets = [];
  74467. var linearSamplingMap = [];
  74468. for (var i = 0; i <= centerIndex; i += 2) {
  74469. var j = Math.min(i + 1, Math.floor(centerIndex));
  74470. var singleCenterSample = i === j;
  74471. if (singleCenterSample) {
  74472. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74473. }
  74474. else {
  74475. var sharedCell = j === centerIndex;
  74476. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74477. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74478. if (offsetLinear === 0) {
  74479. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74480. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74481. }
  74482. else {
  74483. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74484. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74485. }
  74486. }
  74487. }
  74488. for (var i = 0; i < linearSamplingMap.length; i++) {
  74489. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74490. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74491. }
  74492. // Replace with optimized
  74493. offsets = linearSamplingOffsets;
  74494. weights = linearSamplingWeights;
  74495. // Generate shaders
  74496. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74497. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74498. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74499. var defines = "";
  74500. defines += this._staticDefines;
  74501. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74502. if (this._staticDefines.indexOf("DOF") != -1) {
  74503. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74504. varyingCount--;
  74505. }
  74506. for (var i = 0; i < varyingCount; i++) {
  74507. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74508. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74509. }
  74510. var depCount = 0;
  74511. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74512. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74513. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74514. depCount++;
  74515. }
  74516. if (this.packedFloat) {
  74517. defines += "#define PACKEDFLOAT 1";
  74518. }
  74519. this.blockCompilation = false;
  74520. _super.prototype.updateEffect.call(this, defines, null, null, {
  74521. varyingCount: varyingCount,
  74522. depCount: depCount
  74523. }, onCompiled, onError);
  74524. };
  74525. /**
  74526. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74527. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74528. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74529. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74530. * The gaps between physical kernels are compensated for in the weighting of the samples
  74531. * @param idealKernel Ideal blur kernel.
  74532. * @return Nearest best kernel.
  74533. */
  74534. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74535. var v = Math.round(idealKernel);
  74536. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74537. var k = _a[_i];
  74538. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74539. return Math.max(k, 3);
  74540. }
  74541. }
  74542. return Math.max(v, 3);
  74543. };
  74544. /**
  74545. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74546. * @param x The point on the Gaussian distribution to sample.
  74547. * @return the value of the Gaussian function at x.
  74548. */
  74549. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74550. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74551. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74552. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74553. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74554. // truncated at around 1.3% of peak strength.
  74555. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74556. var sigma = (1 / 3);
  74557. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74558. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74559. var weight = (1.0 / denominator) * Math.exp(exponent);
  74560. return weight;
  74561. };
  74562. /**
  74563. * Generates a string that can be used as a floating point number in GLSL.
  74564. * @param x Value to print.
  74565. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74566. * @return GLSL float string.
  74567. */
  74568. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74569. if (decimalFigures === void 0) { decimalFigures = 8; }
  74570. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74571. };
  74572. return BlurPostProcess;
  74573. }(BABYLON.PostProcess));
  74574. BABYLON.BlurPostProcess = BlurPostProcess;
  74575. })(BABYLON || (BABYLON = {}));
  74576. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74577. var BABYLON;
  74578. (function (BABYLON) {
  74579. /**
  74580. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74581. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74582. * based on samples that have a large difference in distance than the center pixel.
  74583. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74584. */
  74585. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74586. __extends(DepthOfFieldBlurPostProcess, _super);
  74587. /**
  74588. * Creates a new instance CircleOfConfusionPostProcess
  74589. * @param name The name of the effect.
  74590. * @param scene The scene the effect belongs to.
  74591. * @param direction The direction the blur should be applied.
  74592. * @param kernel The size of the kernel used to blur.
  74593. * @param options The required width/height ratio to downsize to before computing the render pass.
  74594. * @param camera The camera to apply the render pass to.
  74595. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74596. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74597. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74598. * @param engine The engine which the post process will be applied. (default: current engine)
  74599. * @param reusable If the post process can be reused on the same frame. (default: false)
  74600. * @param textureType Type of textures used when performing the post process. (default: 0)
  74601. * @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)
  74602. */
  74603. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74604. if (imageToBlur === void 0) { imageToBlur = null; }
  74605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  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, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  74609. _this.direction = direction;
  74610. _this.onApplyObservable.add(function (effect) {
  74611. if (imageToBlur != null) {
  74612. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74613. }
  74614. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74615. if (scene.activeCamera) {
  74616. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74617. }
  74618. });
  74619. return _this;
  74620. }
  74621. return DepthOfFieldBlurPostProcess;
  74622. }(BABYLON.BlurPostProcess));
  74623. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74624. })(BABYLON || (BABYLON = {}));
  74625. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74626. var BABYLON;
  74627. (function (BABYLON) {
  74628. /**
  74629. * Options to be set when merging outputs from the default pipeline.
  74630. */
  74631. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74632. function DepthOfFieldMergePostProcessOptions() {
  74633. }
  74634. return DepthOfFieldMergePostProcessOptions;
  74635. }());
  74636. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74637. /**
  74638. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74639. */
  74640. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74641. __extends(DepthOfFieldMergePostProcess, _super);
  74642. /**
  74643. * Creates a new instance of DepthOfFieldMergePostProcess
  74644. * @param name The name of the effect.
  74645. * @param originalFromInput Post process which's input will be used for the merge.
  74646. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74647. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74648. * @param options The required width/height ratio to downsize to before computing the render pass.
  74649. * @param camera The camera to apply the render pass to.
  74650. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74651. * @param engine The engine which the post process will be applied. (default: current engine)
  74652. * @param reusable If the post process can be reused on the same frame. (default: false)
  74653. * @param textureType Type of textures used when performing the post process. (default: 0)
  74654. * @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)
  74655. */
  74656. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74657. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74658. if (blockCompilation === void 0) { blockCompilation = false; }
  74659. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74660. _this.blurSteps = blurSteps;
  74661. _this.onApplyObservable.add(function (effect) {
  74662. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74663. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74664. blurSteps.forEach(function (step, index) {
  74665. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74666. });
  74667. });
  74668. if (!blockCompilation) {
  74669. _this.updateEffect();
  74670. }
  74671. return _this;
  74672. }
  74673. /**
  74674. * Updates the effect with the current post process compile time values and recompiles the shader.
  74675. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74676. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74677. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74678. * @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
  74679. * @param onCompiled Called when the shader has been compiled.
  74680. * @param onError Called if there is an error when compiling a shader.
  74681. */
  74682. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74683. if (defines === void 0) { defines = null; }
  74684. if (uniforms === void 0) { uniforms = null; }
  74685. if (samplers === void 0) { samplers = null; }
  74686. if (!defines) {
  74687. defines = "";
  74688. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74689. }
  74690. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74691. };
  74692. return DepthOfFieldMergePostProcess;
  74693. }(BABYLON.PostProcess));
  74694. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74695. })(BABYLON || (BABYLON = {}));
  74696. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74697. var BABYLON;
  74698. (function (BABYLON) {
  74699. /**
  74700. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74701. */
  74702. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74703. __extends(CircleOfConfusionPostProcess, _super);
  74704. /**
  74705. * Creates a new instance CircleOfConfusionPostProcess
  74706. * @param name The name of the effect.
  74707. * @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.
  74708. * @param options The required width/height ratio to downsize to before computing the render pass.
  74709. * @param camera The camera to apply the render pass to.
  74710. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74711. * @param engine The engine which the post process will be applied. (default: current engine)
  74712. * @param reusable If the post process can be reused on the same frame. (default: false)
  74713. * @param textureType Type of textures used when performing the post process. (default: 0)
  74714. * @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)
  74715. */
  74716. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74717. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74718. if (blockCompilation === void 0) { blockCompilation = false; }
  74719. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74720. /**
  74721. * 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.
  74722. */
  74723. _this.lensSize = 50;
  74724. /**
  74725. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74726. */
  74727. _this.fStop = 1.4;
  74728. /**
  74729. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74730. */
  74731. _this.focusDistance = 2000;
  74732. /**
  74733. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74734. */
  74735. _this.focalLength = 50;
  74736. _this._depthTexture = null;
  74737. _this._depthTexture = depthTexture;
  74738. _this.onApplyObservable.add(function (effect) {
  74739. if (!_this._depthTexture) {
  74740. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74741. return;
  74742. }
  74743. effect.setTexture("depthSampler", _this._depthTexture);
  74744. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74745. var aperture = _this.lensSize / _this.fStop;
  74746. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74747. effect.setFloat('focusDistance', _this.focusDistance);
  74748. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74749. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74750. });
  74751. return _this;
  74752. }
  74753. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74754. /**
  74755. * 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.
  74756. */
  74757. set: function (value) {
  74758. this._depthTexture = value;
  74759. },
  74760. enumerable: true,
  74761. configurable: true
  74762. });
  74763. return CircleOfConfusionPostProcess;
  74764. }(BABYLON.PostProcess));
  74765. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74766. })(BABYLON || (BABYLON = {}));
  74767. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74768. var BABYLON;
  74769. (function (BABYLON) {
  74770. /**
  74771. * Specifies the level of max blur that should be applied when using the depth of field effect
  74772. */
  74773. var DepthOfFieldEffectBlurLevel;
  74774. (function (DepthOfFieldEffectBlurLevel) {
  74775. /**
  74776. * Subtle blur
  74777. */
  74778. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74779. /**
  74780. * Medium blur
  74781. */
  74782. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74783. /**
  74784. * Large blur
  74785. */
  74786. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74787. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74788. ;
  74789. /**
  74790. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74791. */
  74792. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74793. __extends(DepthOfFieldEffect, _super);
  74794. /**
  74795. * Creates a new instance DepthOfFieldEffect
  74796. * @param scene The scene the effect belongs to.
  74797. * @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.
  74798. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74799. * @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)
  74800. */
  74801. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74802. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74803. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74804. if (blockCompilation === void 0) { blockCompilation = false; }
  74805. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74806. return _this._effects;
  74807. }, true) || this;
  74808. /**
  74809. * Internal post processes in depth of field effect
  74810. */
  74811. _this._effects = [];
  74812. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74813. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74814. // 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)
  74815. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74816. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74817. _this._depthOfFieldBlurY = [];
  74818. _this._depthOfFieldBlurX = [];
  74819. var blurCount = 1;
  74820. var kernelSize = 15;
  74821. switch (blurLevel) {
  74822. case DepthOfFieldEffectBlurLevel.High: {
  74823. blurCount = 3;
  74824. kernelSize = 51;
  74825. break;
  74826. }
  74827. case DepthOfFieldEffectBlurLevel.Medium: {
  74828. blurCount = 2;
  74829. kernelSize = 31;
  74830. break;
  74831. }
  74832. default: {
  74833. kernelSize = 15;
  74834. blurCount = 1;
  74835. break;
  74836. }
  74837. }
  74838. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74839. var ratio = 1.0;
  74840. for (var i = 0; i < blurCount; i++) {
  74841. 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);
  74842. blurY.autoClear = false;
  74843. ratio = 0.75 / Math.pow(2, i);
  74844. 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);
  74845. blurX.autoClear = false;
  74846. _this._depthOfFieldBlurY.push(blurY);
  74847. _this._depthOfFieldBlurX.push(blurX);
  74848. }
  74849. // Set all post processes on the effect.
  74850. _this._effects = [_this._circleOfConfusion];
  74851. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74852. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74853. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74854. }
  74855. // Merge blurred images with original image based on circleOfConfusion
  74856. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74857. _this._dofMerge.autoClear = false;
  74858. _this._effects.push(_this._dofMerge);
  74859. return _this;
  74860. }
  74861. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74862. get: function () {
  74863. return this._circleOfConfusion.focalLength;
  74864. },
  74865. /**
  74866. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74867. */
  74868. set: function (value) {
  74869. this._circleOfConfusion.focalLength = value;
  74870. },
  74871. enumerable: true,
  74872. configurable: true
  74873. });
  74874. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74875. get: function () {
  74876. return this._circleOfConfusion.fStop;
  74877. },
  74878. /**
  74879. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74880. */
  74881. set: function (value) {
  74882. this._circleOfConfusion.fStop = value;
  74883. },
  74884. enumerable: true,
  74885. configurable: true
  74886. });
  74887. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74888. get: function () {
  74889. return this._circleOfConfusion.focusDistance;
  74890. },
  74891. /**
  74892. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74893. */
  74894. set: function (value) {
  74895. this._circleOfConfusion.focusDistance = value;
  74896. },
  74897. enumerable: true,
  74898. configurable: true
  74899. });
  74900. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74901. get: function () {
  74902. return this._circleOfConfusion.lensSize;
  74903. },
  74904. /**
  74905. * 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.
  74906. */
  74907. set: function (value) {
  74908. this._circleOfConfusion.lensSize = value;
  74909. },
  74910. enumerable: true,
  74911. configurable: true
  74912. });
  74913. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74914. /**
  74915. * 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.
  74916. */
  74917. set: function (value) {
  74918. this._circleOfConfusion.depthTexture = value;
  74919. },
  74920. enumerable: true,
  74921. configurable: true
  74922. });
  74923. /**
  74924. * Disposes each of the internal effects for a given camera.
  74925. * @param camera The camera to dispose the effect on.
  74926. */
  74927. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74928. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74929. this._effects[effectIndex].dispose(camera);
  74930. }
  74931. };
  74932. /**
  74933. * Internal
  74934. */
  74935. DepthOfFieldEffect.prototype._updateEffects = function () {
  74936. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74937. this._effects[effectIndex].updateEffect();
  74938. }
  74939. };
  74940. /**
  74941. * Internal
  74942. * @returns if all the contained post processes are ready.
  74943. */
  74944. DepthOfFieldEffect.prototype._isReady = function () {
  74945. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74946. if (!this._effects[effectIndex].isReady()) {
  74947. return false;
  74948. }
  74949. }
  74950. return true;
  74951. };
  74952. return DepthOfFieldEffect;
  74953. }(BABYLON.PostProcessRenderEffect));
  74954. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74955. })(BABYLON || (BABYLON = {}));
  74956. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74957. var BABYLON;
  74958. (function (BABYLON) {
  74959. /**
  74960. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74961. */
  74962. var BloomMergePostProcess = /** @class */ (function (_super) {
  74963. __extends(BloomMergePostProcess, _super);
  74964. /**
  74965. * Creates a new instance of @see BloomMergePostProcess
  74966. * @param name The name of the effect.
  74967. * @param originalFromInput Post process which's input will be used for the merge.
  74968. * @param blurred Blurred highlights post process which's output will be used.
  74969. * @param weight Weight of the bloom to be added to the original input.
  74970. * @param options The required width/height ratio to downsize to before computing the render pass.
  74971. * @param camera The camera to apply the render pass to.
  74972. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74973. * @param engine The engine which the post process will be applied. (default: current engine)
  74974. * @param reusable If the post process can be reused on the same frame. (default: false)
  74975. * @param textureType Type of textures used when performing the post process. (default: 0)
  74976. * @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)
  74977. */
  74978. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74979. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74980. if (blockCompilation === void 0) { blockCompilation = false; }
  74981. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74982. _this.weight = weight;
  74983. _this.onApplyObservable.add(function (effect) {
  74984. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74985. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74986. effect.setFloat("bloomWeight", _this.weight);
  74987. });
  74988. if (!blockCompilation) {
  74989. _this.updateEffect();
  74990. }
  74991. return _this;
  74992. }
  74993. return BloomMergePostProcess;
  74994. }(BABYLON.PostProcess));
  74995. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74996. })(BABYLON || (BABYLON = {}));
  74997. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74998. var BABYLON;
  74999. (function (BABYLON) {
  75000. /**
  75001. * 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.
  75002. */
  75003. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75004. __extends(ExtractHighlightsPostProcess, _super);
  75005. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75006. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75007. if (blockCompilation === void 0) { blockCompilation = false; }
  75008. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75009. /**
  75010. * The luminance threshold, pixels below this value will be set to black.
  75011. */
  75012. _this.threshold = 0.9;
  75013. /**
  75014. * Internal
  75015. */
  75016. _this._exposure = 1;
  75017. /**
  75018. * Post process which has the input texture to be used when performing highlight extraction
  75019. */
  75020. _this._inputPostProcess = null;
  75021. _this.onApplyObservable.add(function (effect) {
  75022. if (_this._inputPostProcess) {
  75023. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75024. }
  75025. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75026. effect.setFloat('exposure', _this._exposure);
  75027. });
  75028. return _this;
  75029. }
  75030. return ExtractHighlightsPostProcess;
  75031. }(BABYLON.PostProcess));
  75032. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75033. })(BABYLON || (BABYLON = {}));
  75034. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75035. var BABYLON;
  75036. (function (BABYLON) {
  75037. /**
  75038. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75039. */
  75040. var BloomEffect = /** @class */ (function (_super) {
  75041. __extends(BloomEffect, _super);
  75042. /**
  75043. * Creates a new instance of @see BloomEffect
  75044. * @param scene The scene the effect belongs to.
  75045. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75046. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75047. * @param bloomWeight The the strength of bloom.
  75048. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75049. * @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)
  75050. */
  75051. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75052. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75053. if (blockCompilation === void 0) { blockCompilation = false; }
  75054. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75055. return _this._effects;
  75056. }, true) || this;
  75057. _this.bloomScale = bloomScale;
  75058. /**
  75059. * Internal
  75060. */
  75061. _this._effects = [];
  75062. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75063. _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);
  75064. _this._blurX.alwaysForcePOT = true;
  75065. _this._blurX.autoClear = false;
  75066. _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);
  75067. _this._blurY.alwaysForcePOT = true;
  75068. _this._blurY.autoClear = false;
  75069. _this.kernel = bloomKernel;
  75070. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75071. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75072. _this._merge.autoClear = false;
  75073. _this._effects.push(_this._merge);
  75074. return _this;
  75075. }
  75076. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75077. /**
  75078. * The luminance threshold to find bright areas of the image to bloom.
  75079. */
  75080. get: function () {
  75081. return this._downscale.threshold;
  75082. },
  75083. set: function (value) {
  75084. this._downscale.threshold = value;
  75085. },
  75086. enumerable: true,
  75087. configurable: true
  75088. });
  75089. Object.defineProperty(BloomEffect.prototype, "weight", {
  75090. /**
  75091. * The strength of the bloom.
  75092. */
  75093. get: function () {
  75094. return this._merge.weight;
  75095. },
  75096. set: function (value) {
  75097. this._merge.weight = value;
  75098. },
  75099. enumerable: true,
  75100. configurable: true
  75101. });
  75102. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75103. /**
  75104. * Specifies the size of the bloom blur kernel, relative to the final output size
  75105. */
  75106. get: function () {
  75107. return this._blurX.kernel / this.bloomScale;
  75108. },
  75109. set: function (value) {
  75110. this._blurX.kernel = value * this.bloomScale;
  75111. this._blurY.kernel = value * this.bloomScale;
  75112. },
  75113. enumerable: true,
  75114. configurable: true
  75115. });
  75116. /**
  75117. * Disposes each of the internal effects for a given camera.
  75118. * @param camera The camera to dispose the effect on.
  75119. */
  75120. BloomEffect.prototype.disposeEffects = function (camera) {
  75121. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75122. this._effects[effectIndex].dispose(camera);
  75123. }
  75124. };
  75125. /**
  75126. * Internal
  75127. */
  75128. BloomEffect.prototype._updateEffects = function () {
  75129. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75130. this._effects[effectIndex].updateEffect();
  75131. }
  75132. };
  75133. /**
  75134. * Internal
  75135. * @returns if all the contained post processes are ready.
  75136. */
  75137. BloomEffect.prototype._isReady = function () {
  75138. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75139. if (!this._effects[effectIndex].isReady()) {
  75140. return false;
  75141. }
  75142. }
  75143. return true;
  75144. };
  75145. return BloomEffect;
  75146. }(BABYLON.PostProcessRenderEffect));
  75147. BABYLON.BloomEffect = BloomEffect;
  75148. })(BABYLON || (BABYLON = {}));
  75149. //# sourceMappingURL=babylon.bloomEffect.js.map
  75150. var BABYLON;
  75151. (function (BABYLON) {
  75152. /**
  75153. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75154. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75155. */
  75156. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75157. __extends(DefaultRenderingPipeline, _super);
  75158. /**
  75159. * @constructor
  75160. * @param {string} name - The rendering pipeline name (default: "")
  75161. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75162. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75163. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75164. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75165. */
  75166. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75167. if (name === void 0) { name = ""; }
  75168. if (hdr === void 0) { hdr = true; }
  75169. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75170. if (automaticBuild === void 0) { automaticBuild = true; }
  75171. var _this = _super.call(this, scene.getEngine(), name) || this;
  75172. _this._originalCameras = [];
  75173. /**
  75174. * ID of the sharpen post process,
  75175. */
  75176. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75177. /**
  75178. * ID of the image processing post process;
  75179. */
  75180. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75181. /**
  75182. * ID of the Fast Approximate Anti-Aliasing post process;
  75183. */
  75184. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75185. /**
  75186. * ID of the chromatic aberration post process,
  75187. */
  75188. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75189. /**
  75190. * ID of the grain post process
  75191. */
  75192. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75193. /**
  75194. * Glow post process which adds a glow to emmisive areas of the image
  75195. */
  75196. _this._glowLayer = null;
  75197. /**
  75198. * Animations which can be used to tweak settings over a period of time
  75199. */
  75200. _this.animations = [];
  75201. _this._imageProcessingConfigurationObserver = null;
  75202. // Values
  75203. _this._sharpenEnabled = false;
  75204. _this._bloomEnabled = false;
  75205. _this._depthOfFieldEnabled = false;
  75206. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75207. _this._fxaaEnabled = false;
  75208. _this._imageProcessingEnabled = true;
  75209. _this._bloomScale = 0.5;
  75210. _this._chromaticAberrationEnabled = false;
  75211. _this._grainEnabled = false;
  75212. _this._buildAllowed = true;
  75213. _this._resizeObserver = null;
  75214. _this._hardwareScaleLevel = 1.0;
  75215. _this._bloomKernel = 64;
  75216. /**
  75217. * Specifies the weight of the bloom in the final rendering
  75218. */
  75219. _this._bloomWeight = 0.15;
  75220. /**
  75221. * Specifies the luma threshold for the area that will be blurred by the bloom
  75222. */
  75223. _this._bloomThreshold = 0.9;
  75224. _this._samples = 1;
  75225. _this._hasCleared = false;
  75226. _this._prevPostProcess = null;
  75227. _this._prevPrevPostProcess = null;
  75228. _this._cameras = cameras || scene.cameras;
  75229. _this._originalCameras = _this._cameras.slice();
  75230. _this._buildAllowed = automaticBuild;
  75231. // Initialize
  75232. _this._scene = scene;
  75233. var caps = _this._scene.getEngine().getCaps();
  75234. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75235. // Misc
  75236. if (_this._hdr) {
  75237. if (caps.textureHalfFloatRender) {
  75238. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75239. }
  75240. else if (caps.textureFloatRender) {
  75241. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75242. }
  75243. }
  75244. else {
  75245. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75246. }
  75247. // Attach
  75248. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75249. var engine = _this._scene.getEngine();
  75250. // Create post processes before hand so they can be modified before enabled.
  75251. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75252. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75253. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75254. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75255. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75256. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75257. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75258. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75259. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75260. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75261. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75262. _this.bloomKernel = _this.bloomKernel;
  75263. });
  75264. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75265. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75266. });
  75267. _this._buildPipeline();
  75268. return _this;
  75269. }
  75270. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75271. get: function () {
  75272. return this._sharpenEnabled;
  75273. },
  75274. /**
  75275. * Enable or disable the sharpen process from the pipeline
  75276. */
  75277. set: function (enabled) {
  75278. if (this._sharpenEnabled === enabled) {
  75279. return;
  75280. }
  75281. this._sharpenEnabled = enabled;
  75282. this._buildPipeline();
  75283. },
  75284. enumerable: true,
  75285. configurable: true
  75286. });
  75287. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75288. /**
  75289. * Specifies the size of the bloom blur kernel, relative to the final output size
  75290. */
  75291. get: function () {
  75292. return this._bloomKernel;
  75293. },
  75294. set: function (value) {
  75295. this._bloomKernel = value;
  75296. this.bloom.kernel = value / this._hardwareScaleLevel;
  75297. },
  75298. enumerable: true,
  75299. configurable: true
  75300. });
  75301. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75302. get: function () {
  75303. return this._bloomWeight;
  75304. },
  75305. /**
  75306. * The strength of the bloom.
  75307. */
  75308. set: function (value) {
  75309. if (this._bloomWeight === value) {
  75310. return;
  75311. }
  75312. this.bloom.weight = value;
  75313. this._bloomWeight = value;
  75314. },
  75315. enumerable: true,
  75316. configurable: true
  75317. });
  75318. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75319. get: function () {
  75320. return this._bloomThreshold;
  75321. },
  75322. /**
  75323. * The strength of the bloom.
  75324. */
  75325. set: function (value) {
  75326. if (this._bloomThreshold === value) {
  75327. return;
  75328. }
  75329. this.bloom.threshold = value;
  75330. this._bloomThreshold = value;
  75331. },
  75332. enumerable: true,
  75333. configurable: true
  75334. });
  75335. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75336. get: function () {
  75337. return this._bloomScale;
  75338. },
  75339. /**
  75340. * The scale of the bloom, lower value will provide better performance.
  75341. */
  75342. set: function (value) {
  75343. if (this._bloomScale === value) {
  75344. return;
  75345. }
  75346. this._bloomScale = value;
  75347. // recreate bloom and dispose old as this setting is not dynamic
  75348. this._rebuildBloom();
  75349. this._buildPipeline();
  75350. },
  75351. enumerable: true,
  75352. configurable: true
  75353. });
  75354. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75355. get: function () {
  75356. return this._bloomEnabled;
  75357. },
  75358. /**
  75359. * Enable or disable the bloom from the pipeline
  75360. */
  75361. set: function (enabled) {
  75362. if (this._bloomEnabled === enabled) {
  75363. return;
  75364. }
  75365. this._bloomEnabled = enabled;
  75366. this._buildPipeline();
  75367. },
  75368. enumerable: true,
  75369. configurable: true
  75370. });
  75371. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75372. // recreate bloom and dispose old as this setting is not dynamic
  75373. var oldBloom = this.bloom;
  75374. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75375. this.bloom.threshold = oldBloom.threshold;
  75376. for (var i = 0; i < this._cameras.length; i++) {
  75377. oldBloom.disposeEffects(this._cameras[i]);
  75378. }
  75379. };
  75380. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75381. /**
  75382. * If the depth of field is enabled.
  75383. */
  75384. get: function () {
  75385. return this._depthOfFieldEnabled;
  75386. },
  75387. set: function (enabled) {
  75388. if (this._depthOfFieldEnabled === enabled) {
  75389. return;
  75390. }
  75391. this._depthOfFieldEnabled = enabled;
  75392. this._buildPipeline();
  75393. },
  75394. enumerable: true,
  75395. configurable: true
  75396. });
  75397. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75398. /**
  75399. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75400. */
  75401. get: function () {
  75402. return this._depthOfFieldBlurLevel;
  75403. },
  75404. set: function (value) {
  75405. if (this._depthOfFieldBlurLevel === value) {
  75406. return;
  75407. }
  75408. this._depthOfFieldBlurLevel = value;
  75409. // recreate dof and dispose old as this setting is not dynamic
  75410. var oldDof = this.depthOfField;
  75411. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75412. this.depthOfField.focalLength = oldDof.focalLength;
  75413. this.depthOfField.focusDistance = oldDof.focusDistance;
  75414. this.depthOfField.fStop = oldDof.fStop;
  75415. this.depthOfField.lensSize = oldDof.lensSize;
  75416. for (var i = 0; i < this._cameras.length; i++) {
  75417. oldDof.disposeEffects(this._cameras[i]);
  75418. }
  75419. this._buildPipeline();
  75420. },
  75421. enumerable: true,
  75422. configurable: true
  75423. });
  75424. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75425. get: function () {
  75426. return this._fxaaEnabled;
  75427. },
  75428. /**
  75429. * If the anti aliasing is enabled.
  75430. */
  75431. set: function (enabled) {
  75432. if (this._fxaaEnabled === enabled) {
  75433. return;
  75434. }
  75435. this._fxaaEnabled = enabled;
  75436. this._buildPipeline();
  75437. },
  75438. enumerable: true,
  75439. configurable: true
  75440. });
  75441. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75442. get: function () {
  75443. return this._samples;
  75444. },
  75445. /**
  75446. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75447. */
  75448. set: function (sampleCount) {
  75449. if (this._samples === sampleCount) {
  75450. return;
  75451. }
  75452. this._samples = sampleCount;
  75453. this._buildPipeline();
  75454. },
  75455. enumerable: true,
  75456. configurable: true
  75457. });
  75458. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75459. get: function () {
  75460. return this._imageProcessingEnabled;
  75461. },
  75462. /**
  75463. * If image processing is enabled.
  75464. */
  75465. set: function (enabled) {
  75466. if (this._imageProcessingEnabled === enabled) {
  75467. return;
  75468. }
  75469. this._imageProcessingEnabled = enabled;
  75470. this._buildPipeline();
  75471. },
  75472. enumerable: true,
  75473. configurable: true
  75474. });
  75475. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  75476. get: function () {
  75477. return this._glowLayer == null;
  75478. },
  75479. /**
  75480. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  75481. */
  75482. set: function (enabled) {
  75483. if (enabled && !this._glowLayer) {
  75484. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  75485. }
  75486. else if (!enabled && this._glowLayer) {
  75487. this._glowLayer.dispose();
  75488. this._glowLayer = null;
  75489. }
  75490. },
  75491. enumerable: true,
  75492. configurable: true
  75493. });
  75494. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75495. get: function () {
  75496. return this._chromaticAberrationEnabled;
  75497. },
  75498. /**
  75499. * Enable or disable the chromaticAberration process from the pipeline
  75500. */
  75501. set: function (enabled) {
  75502. if (this._chromaticAberrationEnabled === enabled) {
  75503. return;
  75504. }
  75505. this._chromaticAberrationEnabled = enabled;
  75506. this._buildPipeline();
  75507. },
  75508. enumerable: true,
  75509. configurable: true
  75510. });
  75511. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75512. get: function () {
  75513. return this._grainEnabled;
  75514. },
  75515. /**
  75516. * Enable or disable the grain process from the pipeline
  75517. */
  75518. set: function (enabled) {
  75519. if (this._grainEnabled === enabled) {
  75520. return;
  75521. }
  75522. this._grainEnabled = enabled;
  75523. this._buildPipeline();
  75524. },
  75525. enumerable: true,
  75526. configurable: true
  75527. });
  75528. /**
  75529. * Force the compilation of the entire pipeline.
  75530. */
  75531. DefaultRenderingPipeline.prototype.prepare = function () {
  75532. var previousState = this._buildAllowed;
  75533. this._buildAllowed = true;
  75534. this._buildPipeline();
  75535. this._buildAllowed = previousState;
  75536. };
  75537. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75538. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75539. if (this._hasCleared) {
  75540. postProcess.autoClear = false;
  75541. }
  75542. else {
  75543. postProcess.autoClear = true;
  75544. this._scene.autoClear = false;
  75545. this._hasCleared = true;
  75546. }
  75547. if (!skipTextureSharing) {
  75548. if (this._prevPrevPostProcess) {
  75549. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75550. }
  75551. else {
  75552. postProcess.useOwnOutput();
  75553. }
  75554. if (this._prevPostProcess) {
  75555. this._prevPrevPostProcess = this._prevPostProcess;
  75556. }
  75557. this._prevPostProcess = postProcess;
  75558. }
  75559. };
  75560. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75561. var _this = this;
  75562. if (!this._buildAllowed) {
  75563. return;
  75564. }
  75565. this._scene.autoClear = true;
  75566. var engine = this._scene.getEngine();
  75567. this._disposePostProcesses();
  75568. if (this._cameras !== null) {
  75569. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75570. // get back cameras to be used to reattach pipeline
  75571. this._cameras = this._originalCameras.slice();
  75572. }
  75573. this._reset();
  75574. this._prevPostProcess = null;
  75575. this._prevPrevPostProcess = null;
  75576. this._hasCleared = false;
  75577. if (this.depthOfFieldEnabled) {
  75578. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75579. this.depthOfField.depthTexture = depthTexture;
  75580. if (!this.depthOfField._isReady()) {
  75581. this.depthOfField._updateEffects();
  75582. }
  75583. this.addEffect(this.depthOfField);
  75584. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75585. }
  75586. if (this.bloomEnabled) {
  75587. if (!this.bloom._isReady()) {
  75588. this.bloom._updateEffects();
  75589. }
  75590. this.addEffect(this.bloom);
  75591. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75592. }
  75593. if (this._imageProcessingEnabled) {
  75594. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75595. if (this._hdr) {
  75596. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75597. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75598. }
  75599. else {
  75600. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75601. }
  75602. }
  75603. if (this.sharpenEnabled) {
  75604. if (!this.sharpen.isReady()) {
  75605. this.sharpen.updateEffect();
  75606. }
  75607. this.addEffect(this._sharpenEffect);
  75608. this._setAutoClearAndTextureSharing(this.sharpen);
  75609. }
  75610. if (this.grainEnabled) {
  75611. if (!this.grain.isReady()) {
  75612. this.grain.updateEffect();
  75613. }
  75614. this.addEffect(this._grainEffect);
  75615. this._setAutoClearAndTextureSharing(this.grain);
  75616. }
  75617. if (this.chromaticAberrationEnabled) {
  75618. if (!this.chromaticAberration.isReady()) {
  75619. this.chromaticAberration.updateEffect();
  75620. }
  75621. this.addEffect(this._chromaticAberrationEffect);
  75622. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75623. }
  75624. if (this.fxaaEnabled) {
  75625. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75626. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75627. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75628. }
  75629. if (this._cameras !== null) {
  75630. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75631. }
  75632. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75633. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75634. }
  75635. };
  75636. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75637. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75638. for (var i = 0; i < this._cameras.length; i++) {
  75639. var camera = this._cameras[i];
  75640. if (this.imageProcessing) {
  75641. this.imageProcessing.dispose(camera);
  75642. }
  75643. if (this.fxaa) {
  75644. this.fxaa.dispose(camera);
  75645. }
  75646. // These are created in the constructor and should not be disposed on every pipeline change
  75647. if (disposeNonRecreated) {
  75648. if (this.sharpen) {
  75649. this.sharpen.dispose(camera);
  75650. }
  75651. if (this.depthOfField) {
  75652. this.depthOfField.disposeEffects(camera);
  75653. }
  75654. if (this.bloom) {
  75655. this.bloom.disposeEffects(camera);
  75656. }
  75657. if (this.chromaticAberration) {
  75658. this.chromaticAberration.dispose(camera);
  75659. }
  75660. if (this.grain) {
  75661. this.grain.dispose(camera);
  75662. }
  75663. if (this._glowLayer) {
  75664. this._glowLayer.dispose();
  75665. }
  75666. }
  75667. }
  75668. this.imageProcessing = null;
  75669. this.fxaa = null;
  75670. if (disposeNonRecreated) {
  75671. this.sharpen = null;
  75672. this._sharpenEffect = null;
  75673. this.depthOfField = null;
  75674. this.bloom = null;
  75675. this.chromaticAberration = null;
  75676. this._chromaticAberrationEffect = null;
  75677. this.grain = null;
  75678. this._grainEffect = null;
  75679. this._glowLayer = null;
  75680. }
  75681. };
  75682. /**
  75683. * Dispose of the pipeline and stop all post processes
  75684. */
  75685. DefaultRenderingPipeline.prototype.dispose = function () {
  75686. this._disposePostProcesses(true);
  75687. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75688. this._scene.autoClear = true;
  75689. if (this._resizeObserver) {
  75690. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75691. this._resizeObserver = null;
  75692. }
  75693. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75694. _super.prototype.dispose.call(this);
  75695. };
  75696. /**
  75697. * Serialize the rendering pipeline (Used when exporting)
  75698. * @returns the serialized object
  75699. */
  75700. DefaultRenderingPipeline.prototype.serialize = function () {
  75701. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75702. serializationObject.customType = "DefaultRenderingPipeline";
  75703. return serializationObject;
  75704. };
  75705. /**
  75706. * Parse the serialized pipeline
  75707. * @param source Source pipeline.
  75708. * @param scene The scene to load the pipeline to.
  75709. * @param rootUrl The URL of the serialized pipeline.
  75710. * @returns An instantiated pipeline from the serialized object.
  75711. */
  75712. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75713. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75714. };
  75715. __decorate([
  75716. BABYLON.serialize()
  75717. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75718. __decorate([
  75719. BABYLON.serialize()
  75720. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75721. __decorate([
  75722. BABYLON.serialize()
  75723. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75724. __decorate([
  75725. BABYLON.serialize()
  75726. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75727. __decorate([
  75728. BABYLON.serialize()
  75729. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75730. __decorate([
  75731. BABYLON.serialize()
  75732. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75733. __decorate([
  75734. BABYLON.serialize()
  75735. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75736. __decorate([
  75737. BABYLON.serialize()
  75738. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75739. __decorate([
  75740. BABYLON.serialize()
  75741. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75742. __decorate([
  75743. BABYLON.serialize()
  75744. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75745. __decorate([
  75746. BABYLON.serialize()
  75747. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75748. __decorate([
  75749. BABYLON.serialize()
  75750. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75751. __decorate([
  75752. BABYLON.serialize()
  75753. ], DefaultRenderingPipeline.prototype, "samples", null);
  75754. __decorate([
  75755. BABYLON.serialize()
  75756. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75757. __decorate([
  75758. BABYLON.serialize()
  75759. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  75760. __decorate([
  75761. BABYLON.serialize()
  75762. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75763. __decorate([
  75764. BABYLON.serialize()
  75765. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75766. return DefaultRenderingPipeline;
  75767. }(BABYLON.PostProcessRenderPipeline));
  75768. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75769. })(BABYLON || (BABYLON = {}));
  75770. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75771. var BABYLON;
  75772. (function (BABYLON) {
  75773. /**
  75774. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75775. */
  75776. var GeometryBufferRenderer = /** @class */ (function () {
  75777. /**
  75778. * Creates a new G Buffer for the scene
  75779. * @param scene The scene the buffer belongs to
  75780. * @param ratio How big is the buffer related to the main canvas.
  75781. */
  75782. function GeometryBufferRenderer(scene, ratio) {
  75783. if (ratio === void 0) { ratio = 1; }
  75784. this._enablePosition = false;
  75785. this._scene = scene;
  75786. this._ratio = ratio;
  75787. // Render target
  75788. this._createRenderTargets();
  75789. }
  75790. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75791. /**
  75792. * Set the render list (meshes to be rendered) used in the G buffer.
  75793. */
  75794. set: function (meshes) {
  75795. this._multiRenderTarget.renderList = meshes;
  75796. },
  75797. enumerable: true,
  75798. configurable: true
  75799. });
  75800. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75801. /**
  75802. * Gets wether or not G buffer are supported by the running hardware.
  75803. * This requires draw buffer supports
  75804. */
  75805. get: function () {
  75806. return this._multiRenderTarget.isSupported;
  75807. },
  75808. enumerable: true,
  75809. configurable: true
  75810. });
  75811. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75812. /**
  75813. * Gets wether or not position are enabled for the G buffer.
  75814. */
  75815. get: function () {
  75816. return this._enablePosition;
  75817. },
  75818. /**
  75819. * Sets wether or not position are enabled for the G buffer.
  75820. */
  75821. set: function (enable) {
  75822. this._enablePosition = enable;
  75823. this.dispose();
  75824. this._createRenderTargets();
  75825. },
  75826. enumerable: true,
  75827. configurable: true
  75828. });
  75829. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75830. /**
  75831. * Gets the scene associated with the buffer.
  75832. */
  75833. get: function () {
  75834. return this._scene;
  75835. },
  75836. enumerable: true,
  75837. configurable: true
  75838. });
  75839. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75840. /**
  75841. * Gets the ratio used by the buffer during its creation.
  75842. * How big is the buffer related to the main canvas.
  75843. */
  75844. get: function () {
  75845. return this._ratio;
  75846. },
  75847. enumerable: true,
  75848. configurable: true
  75849. });
  75850. /**
  75851. * Checks wether everything is ready to render a submesh to the G buffer.
  75852. * @param subMesh the submesh to check readiness for
  75853. * @param useInstances is the mesh drawn using instance or not
  75854. * @returns true if ready otherwise false
  75855. */
  75856. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75857. var material = subMesh.getMaterial();
  75858. if (material && material.disableDepthWrite) {
  75859. return false;
  75860. }
  75861. var defines = [];
  75862. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75863. var mesh = subMesh.getMesh();
  75864. // Alpha test
  75865. if (material && material.needAlphaTesting()) {
  75866. defines.push("#define ALPHATEST");
  75867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75868. attribs.push(BABYLON.VertexBuffer.UVKind);
  75869. defines.push("#define UV1");
  75870. }
  75871. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75872. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75873. defines.push("#define UV2");
  75874. }
  75875. }
  75876. // Buffers
  75877. if (this._enablePosition) {
  75878. defines.push("#define POSITION");
  75879. }
  75880. // Bones
  75881. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75882. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75883. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75884. if (mesh.numBoneInfluencers > 4) {
  75885. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75886. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75887. }
  75888. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75889. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75890. }
  75891. else {
  75892. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75893. }
  75894. // Instances
  75895. if (useInstances) {
  75896. defines.push("#define INSTANCES");
  75897. attribs.push("world0");
  75898. attribs.push("world1");
  75899. attribs.push("world2");
  75900. attribs.push("world3");
  75901. }
  75902. // Get correct effect
  75903. var join = defines.join("\n");
  75904. if (this._cachedDefines !== join) {
  75905. this._cachedDefines = join;
  75906. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75907. }
  75908. return this._effect.isReady();
  75909. };
  75910. /**
  75911. * Gets the current underlying G Buffer.
  75912. * @returns the buffer
  75913. */
  75914. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75915. return this._multiRenderTarget;
  75916. };
  75917. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75918. /**
  75919. * Gets the number of samples used to render the buffer (anti aliasing).
  75920. */
  75921. get: function () {
  75922. return this._multiRenderTarget.samples;
  75923. },
  75924. /**
  75925. * Sets the number of samples used to render the buffer (anti aliasing).
  75926. */
  75927. set: function (value) {
  75928. this._multiRenderTarget.samples = value;
  75929. },
  75930. enumerable: true,
  75931. configurable: true
  75932. });
  75933. /**
  75934. * Disposes the renderer and frees up associated resources.
  75935. */
  75936. GeometryBufferRenderer.prototype.dispose = function () {
  75937. this.getGBuffer().dispose();
  75938. };
  75939. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75940. var _this = this;
  75941. var engine = this._scene.getEngine();
  75942. var count = this._enablePosition ? 3 : 2;
  75943. 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 });
  75944. if (!this.isSupported) {
  75945. return;
  75946. }
  75947. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75948. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75949. this._multiRenderTarget.refreshRate = 1;
  75950. this._multiRenderTarget.renderParticles = false;
  75951. this._multiRenderTarget.renderList = null;
  75952. // set default depth value to 1.0 (far away)
  75953. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75954. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75955. });
  75956. // Custom render function
  75957. var renderSubMesh = function (subMesh) {
  75958. var mesh = subMesh.getRenderingMesh();
  75959. var scene = _this._scene;
  75960. var engine = scene.getEngine();
  75961. var material = subMesh.getMaterial();
  75962. if (!material) {
  75963. return;
  75964. }
  75965. // Culling
  75966. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75967. // Managing instances
  75968. var batch = mesh._getInstancesRenderList(subMesh._id);
  75969. if (batch.mustReturn) {
  75970. return;
  75971. }
  75972. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75973. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75974. engine.enableEffect(_this._effect);
  75975. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75976. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75977. _this._effect.setMatrix("view", scene.getViewMatrix());
  75978. // Alpha test
  75979. if (material && material.needAlphaTesting()) {
  75980. var alphaTexture = material.getAlphaTestTexture();
  75981. if (alphaTexture) {
  75982. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75983. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75984. }
  75985. }
  75986. // Bones
  75987. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75988. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75989. }
  75990. // Draw
  75991. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75992. }
  75993. };
  75994. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75995. var index;
  75996. if (depthOnlySubMeshes.length) {
  75997. engine.setColorWrite(false);
  75998. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75999. renderSubMesh(depthOnlySubMeshes.data[index]);
  76000. }
  76001. engine.setColorWrite(true);
  76002. }
  76003. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76004. renderSubMesh(opaqueSubMeshes.data[index]);
  76005. }
  76006. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76007. renderSubMesh(alphaTestSubMeshes.data[index]);
  76008. }
  76009. };
  76010. };
  76011. return GeometryBufferRenderer;
  76012. }());
  76013. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76014. })(BABYLON || (BABYLON = {}));
  76015. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76016. var BABYLON;
  76017. (function (BABYLON) {
  76018. /**
  76019. * This groups together the common properties used for image processing either in direct forward pass
  76020. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76021. * or not.
  76022. */
  76023. var ImageProcessingConfiguration = /** @class */ (function () {
  76024. function ImageProcessingConfiguration() {
  76025. /**
  76026. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76027. */
  76028. this.colorCurves = new BABYLON.ColorCurves();
  76029. this._colorCurvesEnabled = false;
  76030. this._colorGradingEnabled = false;
  76031. this._colorGradingWithGreenDepth = true;
  76032. this._colorGradingBGR = true;
  76033. this._exposure = 1.0;
  76034. this._toneMappingEnabled = false;
  76035. this._contrast = 1.0;
  76036. /**
  76037. * Vignette stretch size.
  76038. */
  76039. this.vignetteStretch = 0;
  76040. /**
  76041. * Vignette centre X Offset.
  76042. */
  76043. this.vignetteCentreX = 0;
  76044. /**
  76045. * Vignette centre Y Offset.
  76046. */
  76047. this.vignetteCentreY = 0;
  76048. /**
  76049. * Vignette weight or intensity of the vignette effect.
  76050. */
  76051. this.vignetteWeight = 1.5;
  76052. /**
  76053. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76054. * if vignetteEnabled is set to true.
  76055. */
  76056. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76057. /**
  76058. * Camera field of view used by the Vignette effect.
  76059. */
  76060. this.vignetteCameraFov = 0.5;
  76061. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76062. this._vignetteEnabled = false;
  76063. this._applyByPostProcess = false;
  76064. this._isEnabled = true;
  76065. /**
  76066. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76067. */
  76068. this.onUpdateParameters = new BABYLON.Observable();
  76069. }
  76070. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76071. /**
  76072. * Gets wether the color curves effect is enabled.
  76073. */
  76074. get: function () {
  76075. return this._colorCurvesEnabled;
  76076. },
  76077. /**
  76078. * Sets wether the color curves effect is enabled.
  76079. */
  76080. set: function (value) {
  76081. if (this._colorCurvesEnabled === value) {
  76082. return;
  76083. }
  76084. this._colorCurvesEnabled = value;
  76085. this._updateParameters();
  76086. },
  76087. enumerable: true,
  76088. configurable: true
  76089. });
  76090. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76091. /**
  76092. * Gets wether the color grading effect is enabled.
  76093. */
  76094. get: function () {
  76095. return this._colorGradingEnabled;
  76096. },
  76097. /**
  76098. * Sets wether the color grading effect is enabled.
  76099. */
  76100. set: function (value) {
  76101. if (this._colorGradingEnabled === value) {
  76102. return;
  76103. }
  76104. this._colorGradingEnabled = value;
  76105. this._updateParameters();
  76106. },
  76107. enumerable: true,
  76108. configurable: true
  76109. });
  76110. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76111. /**
  76112. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76113. */
  76114. get: function () {
  76115. return this._colorGradingWithGreenDepth;
  76116. },
  76117. /**
  76118. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76119. */
  76120. set: function (value) {
  76121. if (this._colorGradingWithGreenDepth === value) {
  76122. return;
  76123. }
  76124. this._colorGradingWithGreenDepth = value;
  76125. this._updateParameters();
  76126. },
  76127. enumerable: true,
  76128. configurable: true
  76129. });
  76130. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76131. /**
  76132. * Gets wether the color grading texture contains BGR values.
  76133. */
  76134. get: function () {
  76135. return this._colorGradingBGR;
  76136. },
  76137. /**
  76138. * Sets wether the color grading texture contains BGR values.
  76139. */
  76140. set: function (value) {
  76141. if (this._colorGradingBGR === value) {
  76142. return;
  76143. }
  76144. this._colorGradingBGR = value;
  76145. this._updateParameters();
  76146. },
  76147. enumerable: true,
  76148. configurable: true
  76149. });
  76150. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76151. /**
  76152. * Gets the Exposure used in the effect.
  76153. */
  76154. get: function () {
  76155. return this._exposure;
  76156. },
  76157. /**
  76158. * Sets the Exposure used in the effect.
  76159. */
  76160. set: function (value) {
  76161. if (this._exposure === value) {
  76162. return;
  76163. }
  76164. this._exposure = value;
  76165. this._updateParameters();
  76166. },
  76167. enumerable: true,
  76168. configurable: true
  76169. });
  76170. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76171. /**
  76172. * Gets wether the tone mapping effect is enabled.
  76173. */
  76174. get: function () {
  76175. return this._toneMappingEnabled;
  76176. },
  76177. /**
  76178. * Sets wether the tone mapping effect is enabled.
  76179. */
  76180. set: function (value) {
  76181. if (this._toneMappingEnabled === value) {
  76182. return;
  76183. }
  76184. this._toneMappingEnabled = value;
  76185. this._updateParameters();
  76186. },
  76187. enumerable: true,
  76188. configurable: true
  76189. });
  76190. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76191. /**
  76192. * Gets the contrast used in the effect.
  76193. */
  76194. get: function () {
  76195. return this._contrast;
  76196. },
  76197. /**
  76198. * Sets the contrast used in the effect.
  76199. */
  76200. set: function (value) {
  76201. if (this._contrast === value) {
  76202. return;
  76203. }
  76204. this._contrast = value;
  76205. this._updateParameters();
  76206. },
  76207. enumerable: true,
  76208. configurable: true
  76209. });
  76210. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76211. /**
  76212. * Gets the vignette blend mode allowing different kind of effect.
  76213. */
  76214. get: function () {
  76215. return this._vignetteBlendMode;
  76216. },
  76217. /**
  76218. * Sets the vignette blend mode allowing different kind of effect.
  76219. */
  76220. set: function (value) {
  76221. if (this._vignetteBlendMode === value) {
  76222. return;
  76223. }
  76224. this._vignetteBlendMode = value;
  76225. this._updateParameters();
  76226. },
  76227. enumerable: true,
  76228. configurable: true
  76229. });
  76230. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76231. /**
  76232. * Gets wether the vignette effect is enabled.
  76233. */
  76234. get: function () {
  76235. return this._vignetteEnabled;
  76236. },
  76237. /**
  76238. * Sets wether the vignette effect is enabled.
  76239. */
  76240. set: function (value) {
  76241. if (this._vignetteEnabled === value) {
  76242. return;
  76243. }
  76244. this._vignetteEnabled = value;
  76245. this._updateParameters();
  76246. },
  76247. enumerable: true,
  76248. configurable: true
  76249. });
  76250. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76251. /**
  76252. * Gets wether the image processing is applied through a post process or not.
  76253. */
  76254. get: function () {
  76255. return this._applyByPostProcess;
  76256. },
  76257. /**
  76258. * Sets wether the image processing is applied through a post process or not.
  76259. */
  76260. set: function (value) {
  76261. if (this._applyByPostProcess === value) {
  76262. return;
  76263. }
  76264. this._applyByPostProcess = value;
  76265. this._updateParameters();
  76266. },
  76267. enumerable: true,
  76268. configurable: true
  76269. });
  76270. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76271. /**
  76272. * Gets wether the image processing is enabled or not.
  76273. */
  76274. get: function () {
  76275. return this._isEnabled;
  76276. },
  76277. /**
  76278. * Sets wether the image processing is enabled or not.
  76279. */
  76280. set: function (value) {
  76281. if (this._isEnabled === value) {
  76282. return;
  76283. }
  76284. this._isEnabled = value;
  76285. this._updateParameters();
  76286. },
  76287. enumerable: true,
  76288. configurable: true
  76289. });
  76290. /**
  76291. * Method called each time the image processing information changes requires to recompile the effect.
  76292. */
  76293. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76294. this.onUpdateParameters.notifyObservers(this);
  76295. };
  76296. ImageProcessingConfiguration.prototype.getClassName = function () {
  76297. return "ImageProcessingConfiguration";
  76298. };
  76299. /**
  76300. * Prepare the list of uniforms associated with the Image Processing effects.
  76301. * @param uniformsList The list of uniforms used in the effect
  76302. * @param defines the list of defines currently in use
  76303. */
  76304. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76305. if (defines.EXPOSURE) {
  76306. uniforms.push("exposureLinear");
  76307. }
  76308. if (defines.CONTRAST) {
  76309. uniforms.push("contrast");
  76310. }
  76311. if (defines.COLORGRADING) {
  76312. uniforms.push("colorTransformSettings");
  76313. }
  76314. if (defines.VIGNETTE) {
  76315. uniforms.push("vInverseScreenSize");
  76316. uniforms.push("vignetteSettings1");
  76317. uniforms.push("vignetteSettings2");
  76318. }
  76319. if (defines.COLORCURVES) {
  76320. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  76321. }
  76322. };
  76323. /**
  76324. * Prepare the list of samplers associated with the Image Processing effects.
  76325. * @param uniformsList The list of uniforms used in the effect
  76326. * @param defines the list of defines currently in use
  76327. */
  76328. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  76329. if (defines.COLORGRADING) {
  76330. samplersList.push("txColorTransform");
  76331. }
  76332. };
  76333. /**
  76334. * Prepare the list of defines associated to the shader.
  76335. * @param defines the list of defines to complete
  76336. */
  76337. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  76338. if (forPostProcess === void 0) { forPostProcess = false; }
  76339. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  76340. defines.VIGNETTE = false;
  76341. defines.TONEMAPPING = false;
  76342. defines.CONTRAST = false;
  76343. defines.EXPOSURE = false;
  76344. defines.COLORCURVES = false;
  76345. defines.COLORGRADING = false;
  76346. defines.COLORGRADING3D = false;
  76347. defines.IMAGEPROCESSING = false;
  76348. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  76349. return;
  76350. }
  76351. defines.VIGNETTE = this.vignetteEnabled;
  76352. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  76353. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  76354. defines.TONEMAPPING = this.toneMappingEnabled;
  76355. defines.CONTRAST = (this.contrast !== 1.0);
  76356. defines.EXPOSURE = (this.exposure !== 1.0);
  76357. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  76358. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  76359. if (defines.COLORGRADING) {
  76360. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  76361. }
  76362. else {
  76363. defines.COLORGRADING3D = false;
  76364. }
  76365. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  76366. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  76367. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  76368. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  76369. };
  76370. /**
  76371. * Returns true if all the image processing information are ready.
  76372. */
  76373. ImageProcessingConfiguration.prototype.isReady = function () {
  76374. // Color Grading texure can not be none blocking.
  76375. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  76376. };
  76377. /**
  76378. * Binds the image processing to the shader.
  76379. * @param effect The effect to bind to
  76380. */
  76381. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  76382. if (aspectRatio === void 0) { aspectRatio = 1; }
  76383. // Color Curves
  76384. if (this._colorCurvesEnabled && this.colorCurves) {
  76385. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  76386. }
  76387. // Vignette
  76388. if (this._vignetteEnabled) {
  76389. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  76390. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  76391. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  76392. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  76393. var vignetteScaleX = vignetteScaleY * aspectRatio;
  76394. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  76395. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  76396. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  76397. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  76398. var vignettePower = -2.0 * this.vignetteWeight;
  76399. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  76400. }
  76401. // Exposure
  76402. effect.setFloat("exposureLinear", this.exposure);
  76403. // Contrast
  76404. effect.setFloat("contrast", this.contrast);
  76405. // Color transform settings
  76406. if (this.colorGradingTexture) {
  76407. effect.setTexture("txColorTransform", this.colorGradingTexture);
  76408. var textureSize = this.colorGradingTexture.getSize().height;
  76409. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  76410. 0.5 / textureSize, // textureOffset
  76411. textureSize, // textureSize
  76412. this.colorGradingTexture.level // weight
  76413. );
  76414. }
  76415. };
  76416. /**
  76417. * Clones the current image processing instance.
  76418. * @return The cloned image processing
  76419. */
  76420. ImageProcessingConfiguration.prototype.clone = function () {
  76421. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  76422. };
  76423. /**
  76424. * Serializes the current image processing instance to a json representation.
  76425. * @return a JSON representation
  76426. */
  76427. ImageProcessingConfiguration.prototype.serialize = function () {
  76428. return BABYLON.SerializationHelper.Serialize(this);
  76429. };
  76430. /**
  76431. * Parses the image processing from a json representation.
  76432. * @param source the JSON source to parse
  76433. * @return The parsed image processing
  76434. */
  76435. ImageProcessingConfiguration.Parse = function (source) {
  76436. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  76437. };
  76438. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  76439. /**
  76440. * Used to apply the vignette as a mix with the pixel color.
  76441. */
  76442. get: function () {
  76443. return this._VIGNETTEMODE_MULTIPLY;
  76444. },
  76445. enumerable: true,
  76446. configurable: true
  76447. });
  76448. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  76449. /**
  76450. * Used to apply the vignette as a replacement of the pixel color.
  76451. */
  76452. get: function () {
  76453. return this._VIGNETTEMODE_OPAQUE;
  76454. },
  76455. enumerable: true,
  76456. configurable: true
  76457. });
  76458. // Static constants associated to the image processing.
  76459. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  76460. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  76461. __decorate([
  76462. BABYLON.serializeAsColorCurves()
  76463. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  76464. __decorate([
  76465. BABYLON.serialize()
  76466. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  76467. __decorate([
  76468. BABYLON.serializeAsTexture()
  76469. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  76470. __decorate([
  76471. BABYLON.serialize()
  76472. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  76473. __decorate([
  76474. BABYLON.serialize()
  76475. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  76476. __decorate([
  76477. BABYLON.serialize()
  76478. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  76479. __decorate([
  76480. BABYLON.serialize()
  76481. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  76482. __decorate([
  76483. BABYLON.serialize()
  76484. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  76485. __decorate([
  76486. BABYLON.serialize()
  76487. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  76488. __decorate([
  76489. BABYLON.serialize()
  76490. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  76491. __decorate([
  76492. BABYLON.serialize()
  76493. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  76494. __decorate([
  76495. BABYLON.serialize()
  76496. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  76497. __decorate([
  76498. BABYLON.serialize()
  76499. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  76500. __decorate([
  76501. BABYLON.serializeAsColor4()
  76502. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  76503. __decorate([
  76504. BABYLON.serialize()
  76505. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  76506. __decorate([
  76507. BABYLON.serialize()
  76508. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  76509. __decorate([
  76510. BABYLON.serialize()
  76511. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  76512. __decorate([
  76513. BABYLON.serialize()
  76514. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  76515. __decorate([
  76516. BABYLON.serialize()
  76517. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  76518. return ImageProcessingConfiguration;
  76519. }());
  76520. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  76521. })(BABYLON || (BABYLON = {}));
  76522. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  76523. var BABYLON;
  76524. (function (BABYLON) {
  76525. /**
  76526. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  76527. * It can help converting any input color in a desired output one. This can then be used to create effects
  76528. * from sepia, black and white to sixties or futuristic rendering...
  76529. *
  76530. * The only supported format is currently 3dl.
  76531. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  76532. */
  76533. var ColorGradingTexture = /** @class */ (function (_super) {
  76534. __extends(ColorGradingTexture, _super);
  76535. /**
  76536. * Instantiates a ColorGradingTexture from the following parameters.
  76537. *
  76538. * @param url The location of the color gradind data (currently only supporting 3dl)
  76539. * @param scene The scene the texture will be used in
  76540. */
  76541. function ColorGradingTexture(url, scene) {
  76542. var _this = _super.call(this, scene) || this;
  76543. if (!url) {
  76544. return _this;
  76545. }
  76546. _this._engine = scene.getEngine();
  76547. _this._textureMatrix = BABYLON.Matrix.Identity();
  76548. _this.name = url;
  76549. _this.url = url;
  76550. _this.hasAlpha = false;
  76551. _this.isCube = false;
  76552. _this.is3D = _this._engine.webGLVersion > 1;
  76553. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76554. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76555. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76556. _this.anisotropicFilteringLevel = 1;
  76557. _this._texture = _this._getFromCache(url, true);
  76558. if (!_this._texture) {
  76559. if (!scene.useDelayedTextureLoading) {
  76560. _this.loadTexture();
  76561. }
  76562. else {
  76563. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  76564. }
  76565. }
  76566. return _this;
  76567. }
  76568. /**
  76569. * Returns the texture matrix used in most of the material.
  76570. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  76571. */
  76572. ColorGradingTexture.prototype.getTextureMatrix = function () {
  76573. return this._textureMatrix;
  76574. };
  76575. /**
  76576. * Occurs when the file being loaded is a .3dl LUT file.
  76577. */
  76578. ColorGradingTexture.prototype.load3dlTexture = function () {
  76579. var engine = this._engine;
  76580. var texture;
  76581. if (engine.webGLVersion === 1) {
  76582. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76583. }
  76584. else {
  76585. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76586. }
  76587. this._texture = texture;
  76588. var callback = function (text) {
  76589. if (typeof text !== "string") {
  76590. return;
  76591. }
  76592. var data = null;
  76593. var tempData = null;
  76594. var line;
  76595. var lines = text.split('\n');
  76596. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  76597. var maxColor = 0;
  76598. for (var i = 0; i < lines.length; i++) {
  76599. line = lines[i];
  76600. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  76601. continue;
  76602. if (line.indexOf('#') === 0)
  76603. continue;
  76604. var words = line.split(" ");
  76605. if (size === 0) {
  76606. // Number of space + one
  76607. size = words.length;
  76608. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  76609. tempData = new Float32Array(size * size * size * 4);
  76610. continue;
  76611. }
  76612. if (size != 0) {
  76613. var r = Math.max(parseInt(words[0]), 0);
  76614. var g = Math.max(parseInt(words[1]), 0);
  76615. var b = Math.max(parseInt(words[2]), 0);
  76616. maxColor = Math.max(r, maxColor);
  76617. maxColor = Math.max(g, maxColor);
  76618. maxColor = Math.max(b, maxColor);
  76619. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  76620. if (tempData) {
  76621. tempData[pixelStorageIndex + 0] = r;
  76622. tempData[pixelStorageIndex + 1] = g;
  76623. tempData[pixelStorageIndex + 2] = b;
  76624. }
  76625. pixelIndexSlice++;
  76626. if (pixelIndexSlice % size == 0) {
  76627. pixelIndexH++;
  76628. pixelIndexSlice = 0;
  76629. if (pixelIndexH % size == 0) {
  76630. pixelIndexW++;
  76631. pixelIndexH = 0;
  76632. }
  76633. }
  76634. }
  76635. }
  76636. if (tempData && data) {
  76637. for (var i = 0; i < tempData.length; i++) {
  76638. if (i > 0 && (i + 1) % 4 === 0) {
  76639. data[i] = 255;
  76640. }
  76641. else {
  76642. var value = tempData[i];
  76643. data[i] = (value / maxColor * 255);
  76644. }
  76645. }
  76646. }
  76647. if (texture.is3D) {
  76648. texture.updateSize(size, size, size);
  76649. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76650. }
  76651. else {
  76652. texture.updateSize(size * size, size);
  76653. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  76654. }
  76655. };
  76656. var scene = this.getScene();
  76657. if (scene) {
  76658. scene._loadFile(this.url, callback);
  76659. }
  76660. else {
  76661. this._engine._loadFile(this.url, callback);
  76662. }
  76663. return this._texture;
  76664. };
  76665. /**
  76666. * Starts the loading process of the texture.
  76667. */
  76668. ColorGradingTexture.prototype.loadTexture = function () {
  76669. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  76670. this.load3dlTexture();
  76671. }
  76672. };
  76673. /**
  76674. * Clones the color gradind texture.
  76675. */
  76676. ColorGradingTexture.prototype.clone = function () {
  76677. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  76678. // Base texture
  76679. newTexture.level = this.level;
  76680. return newTexture;
  76681. };
  76682. /**
  76683. * Called during delayed load for textures.
  76684. */
  76685. ColorGradingTexture.prototype.delayLoad = function () {
  76686. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  76687. return;
  76688. }
  76689. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  76690. this._texture = this._getFromCache(this.url, true);
  76691. if (!this._texture) {
  76692. this.loadTexture();
  76693. }
  76694. };
  76695. /**
  76696. * Parses a color grading texture serialized by Babylon.
  76697. * @param parsedTexture The texture information being parsedTexture
  76698. * @param scene The scene to load the texture in
  76699. * @param rootUrl The root url of the data assets to load
  76700. * @return A color gradind texture
  76701. */
  76702. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  76703. var texture = null;
  76704. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  76705. texture = new ColorGradingTexture(parsedTexture.name, scene);
  76706. texture.name = parsedTexture.name;
  76707. texture.level = parsedTexture.level;
  76708. }
  76709. return texture;
  76710. };
  76711. /**
  76712. * Serializes the LUT texture to json format.
  76713. */
  76714. ColorGradingTexture.prototype.serialize = function () {
  76715. if (!this.name) {
  76716. return null;
  76717. }
  76718. var serializationObject = {};
  76719. serializationObject.name = this.name;
  76720. serializationObject.level = this.level;
  76721. serializationObject.customType = "BABYLON.ColorGradingTexture";
  76722. return serializationObject;
  76723. };
  76724. /**
  76725. * Empty line regex stored for GC.
  76726. */
  76727. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  76728. return ColorGradingTexture;
  76729. }(BABYLON.BaseTexture));
  76730. BABYLON.ColorGradingTexture = ColorGradingTexture;
  76731. })(BABYLON || (BABYLON = {}));
  76732. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  76733. var BABYLON;
  76734. (function (BABYLON) {
  76735. /**
  76736. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76737. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76738. * 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;
  76739. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76740. */
  76741. var ColorCurves = /** @class */ (function () {
  76742. function ColorCurves() {
  76743. this._dirty = true;
  76744. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  76745. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  76746. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  76747. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  76748. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  76749. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  76750. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  76751. this._globalHue = 30;
  76752. this._globalDensity = 0;
  76753. this._globalSaturation = 0;
  76754. this._globalExposure = 0;
  76755. this._highlightsHue = 30;
  76756. this._highlightsDensity = 0;
  76757. this._highlightsSaturation = 0;
  76758. this._highlightsExposure = 0;
  76759. this._midtonesHue = 30;
  76760. this._midtonesDensity = 0;
  76761. this._midtonesSaturation = 0;
  76762. this._midtonesExposure = 0;
  76763. this._shadowsHue = 30;
  76764. this._shadowsDensity = 0;
  76765. this._shadowsSaturation = 0;
  76766. this._shadowsExposure = 0;
  76767. }
  76768. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  76769. /**
  76770. * Gets the global Hue value.
  76771. * 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).
  76772. */
  76773. get: function () {
  76774. return this._globalHue;
  76775. },
  76776. /**
  76777. * Sets the global Hue value.
  76778. * 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).
  76779. */
  76780. set: function (value) {
  76781. this._globalHue = value;
  76782. this._dirty = true;
  76783. },
  76784. enumerable: true,
  76785. configurable: true
  76786. });
  76787. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  76788. /**
  76789. * Gets the global Density value.
  76790. * 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.
  76791. * Values less than zero provide a filter of opposite hue.
  76792. */
  76793. get: function () {
  76794. return this._globalDensity;
  76795. },
  76796. /**
  76797. * Sets the global Density value.
  76798. * 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.
  76799. * Values less than zero provide a filter of opposite hue.
  76800. */
  76801. set: function (value) {
  76802. this._globalDensity = value;
  76803. this._dirty = true;
  76804. },
  76805. enumerable: true,
  76806. configurable: true
  76807. });
  76808. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  76809. /**
  76810. * Gets the global Saturation value.
  76811. * 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.
  76812. */
  76813. get: function () {
  76814. return this._globalSaturation;
  76815. },
  76816. /**
  76817. * Sets the global Saturation value.
  76818. * 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.
  76819. */
  76820. set: function (value) {
  76821. this._globalSaturation = value;
  76822. this._dirty = true;
  76823. },
  76824. enumerable: true,
  76825. configurable: true
  76826. });
  76827. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  76828. /**
  76829. * Gets the global Exposure value.
  76830. * 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.
  76831. */
  76832. get: function () {
  76833. return this._globalExposure;
  76834. },
  76835. /**
  76836. * Sets the global Exposure value.
  76837. * 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.
  76838. */
  76839. set: function (value) {
  76840. this._globalExposure = value;
  76841. this._dirty = true;
  76842. },
  76843. enumerable: true,
  76844. configurable: true
  76845. });
  76846. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  76847. /**
  76848. * Gets the highlights Hue value.
  76849. * 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).
  76850. */
  76851. get: function () {
  76852. return this._highlightsHue;
  76853. },
  76854. /**
  76855. * Sets the highlights Hue value.
  76856. * 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).
  76857. */
  76858. set: function (value) {
  76859. this._highlightsHue = value;
  76860. this._dirty = true;
  76861. },
  76862. enumerable: true,
  76863. configurable: true
  76864. });
  76865. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  76866. /**
  76867. * Gets the highlights Density value.
  76868. * 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.
  76869. * Values less than zero provide a filter of opposite hue.
  76870. */
  76871. get: function () {
  76872. return this._highlightsDensity;
  76873. },
  76874. /**
  76875. * Sets the highlights Density value.
  76876. * 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.
  76877. * Values less than zero provide a filter of opposite hue.
  76878. */
  76879. set: function (value) {
  76880. this._highlightsDensity = value;
  76881. this._dirty = true;
  76882. },
  76883. enumerable: true,
  76884. configurable: true
  76885. });
  76886. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  76887. /**
  76888. * Gets the highlights Saturation value.
  76889. * 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.
  76890. */
  76891. get: function () {
  76892. return this._highlightsSaturation;
  76893. },
  76894. /**
  76895. * Sets the highlights Saturation value.
  76896. * 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.
  76897. */
  76898. set: function (value) {
  76899. this._highlightsSaturation = value;
  76900. this._dirty = true;
  76901. },
  76902. enumerable: true,
  76903. configurable: true
  76904. });
  76905. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  76906. /**
  76907. * Gets the highlights Exposure value.
  76908. * 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.
  76909. */
  76910. get: function () {
  76911. return this._highlightsExposure;
  76912. },
  76913. /**
  76914. * Sets the highlights Exposure value.
  76915. * 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.
  76916. */
  76917. set: function (value) {
  76918. this._highlightsExposure = value;
  76919. this._dirty = true;
  76920. },
  76921. enumerable: true,
  76922. configurable: true
  76923. });
  76924. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  76925. /**
  76926. * Gets the midtones Hue value.
  76927. * 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).
  76928. */
  76929. get: function () {
  76930. return this._midtonesHue;
  76931. },
  76932. /**
  76933. * Sets the midtones Hue value.
  76934. * 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).
  76935. */
  76936. set: function (value) {
  76937. this._midtonesHue = value;
  76938. this._dirty = true;
  76939. },
  76940. enumerable: true,
  76941. configurable: true
  76942. });
  76943. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  76944. /**
  76945. * Gets the midtones Density value.
  76946. * 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.
  76947. * Values less than zero provide a filter of opposite hue.
  76948. */
  76949. get: function () {
  76950. return this._midtonesDensity;
  76951. },
  76952. /**
  76953. * Sets the midtones Density value.
  76954. * 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.
  76955. * Values less than zero provide a filter of opposite hue.
  76956. */
  76957. set: function (value) {
  76958. this._midtonesDensity = value;
  76959. this._dirty = true;
  76960. },
  76961. enumerable: true,
  76962. configurable: true
  76963. });
  76964. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  76965. /**
  76966. * Gets the midtones Saturation value.
  76967. * 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.
  76968. */
  76969. get: function () {
  76970. return this._midtonesSaturation;
  76971. },
  76972. /**
  76973. * Sets the midtones Saturation value.
  76974. * 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.
  76975. */
  76976. set: function (value) {
  76977. this._midtonesSaturation = value;
  76978. this._dirty = true;
  76979. },
  76980. enumerable: true,
  76981. configurable: true
  76982. });
  76983. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  76984. /**
  76985. * Gets the midtones Exposure value.
  76986. * 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.
  76987. */
  76988. get: function () {
  76989. return this._midtonesExposure;
  76990. },
  76991. /**
  76992. * Sets the midtones Exposure value.
  76993. * 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.
  76994. */
  76995. set: function (value) {
  76996. this._midtonesExposure = value;
  76997. this._dirty = true;
  76998. },
  76999. enumerable: true,
  77000. configurable: true
  77001. });
  77002. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77003. /**
  77004. * Gets the shadows Hue value.
  77005. * 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).
  77006. */
  77007. get: function () {
  77008. return this._shadowsHue;
  77009. },
  77010. /**
  77011. * Sets the shadows Hue value.
  77012. * 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).
  77013. */
  77014. set: function (value) {
  77015. this._shadowsHue = value;
  77016. this._dirty = true;
  77017. },
  77018. enumerable: true,
  77019. configurable: true
  77020. });
  77021. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77022. /**
  77023. * Gets the shadows Density value.
  77024. * 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.
  77025. * Values less than zero provide a filter of opposite hue.
  77026. */
  77027. get: function () {
  77028. return this._shadowsDensity;
  77029. },
  77030. /**
  77031. * Sets the shadows Density value.
  77032. * 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.
  77033. * Values less than zero provide a filter of opposite hue.
  77034. */
  77035. set: function (value) {
  77036. this._shadowsDensity = value;
  77037. this._dirty = true;
  77038. },
  77039. enumerable: true,
  77040. configurable: true
  77041. });
  77042. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77043. /**
  77044. * Gets the shadows Saturation value.
  77045. * 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.
  77046. */
  77047. get: function () {
  77048. return this._shadowsSaturation;
  77049. },
  77050. /**
  77051. * Sets the shadows Saturation value.
  77052. * 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.
  77053. */
  77054. set: function (value) {
  77055. this._shadowsSaturation = value;
  77056. this._dirty = true;
  77057. },
  77058. enumerable: true,
  77059. configurable: true
  77060. });
  77061. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77062. /**
  77063. * Gets the shadows Exposure value.
  77064. * 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.
  77065. */
  77066. get: function () {
  77067. return this._shadowsExposure;
  77068. },
  77069. /**
  77070. * Sets the shadows Exposure value.
  77071. * 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.
  77072. */
  77073. set: function (value) {
  77074. this._shadowsExposure = value;
  77075. this._dirty = true;
  77076. },
  77077. enumerable: true,
  77078. configurable: true
  77079. });
  77080. ColorCurves.prototype.getClassName = function () {
  77081. return "ColorCurves";
  77082. };
  77083. /**
  77084. * Binds the color curves to the shader.
  77085. * @param colorCurves The color curve to bind
  77086. * @param effect The effect to bind to
  77087. */
  77088. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77089. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77090. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77091. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77092. if (colorCurves._dirty) {
  77093. colorCurves._dirty = false;
  77094. // Fill in global info.
  77095. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77096. // Compute highlights info.
  77097. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77098. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77099. // Compute midtones info.
  77100. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77101. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77102. // Compute shadows info.
  77103. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77104. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77105. // Compute deltas (neutral is midtones).
  77106. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77107. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77108. }
  77109. if (effect) {
  77110. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77111. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77112. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77113. }
  77114. };
  77115. /**
  77116. * Prepare the list of uniforms associated with the ColorCurves effects.
  77117. * @param uniformsList The list of uniforms used in the effect
  77118. */
  77119. ColorCurves.PrepareUniforms = function (uniformsList) {
  77120. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77121. };
  77122. /**
  77123. * Returns color grading data based on a hue, density, saturation and exposure value.
  77124. * @param filterHue The hue of the color filter.
  77125. * @param filterDensity The density of the color filter.
  77126. * @param saturation The saturation.
  77127. * @param exposure The exposure.
  77128. * @param result The result data container.
  77129. */
  77130. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77131. if (hue == null) {
  77132. return;
  77133. }
  77134. hue = ColorCurves.clamp(hue, 0, 360);
  77135. density = ColorCurves.clamp(density, -100, 100);
  77136. saturation = ColorCurves.clamp(saturation, -100, 100);
  77137. exposure = ColorCurves.clamp(exposure, -100, 100);
  77138. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77139. // so that the maximum filter density is only 50% control. This provides fine control
  77140. // for small values and reasonable range.
  77141. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77142. density *= 0.5;
  77143. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77144. if (density < 0) {
  77145. density *= -1;
  77146. hue = (hue + 180) % 360;
  77147. }
  77148. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77149. result.scaleToRef(2, result);
  77150. result.a = 1 + 0.01 * saturation;
  77151. };
  77152. /**
  77153. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77154. * @param value The input slider value in range [-100,100].
  77155. * @returns Adjusted value.
  77156. */
  77157. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77158. value /= 100;
  77159. var x = Math.abs(value);
  77160. x = Math.pow(x, 2);
  77161. if (value < 0) {
  77162. x *= -1;
  77163. }
  77164. x *= 100;
  77165. return x;
  77166. };
  77167. /**
  77168. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77169. * @param hue The hue (H) input.
  77170. * @param saturation The saturation (S) input.
  77171. * @param brightness The brightness (B) input.
  77172. * @result An RGBA color represented as Vector4.
  77173. */
  77174. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77175. var h = ColorCurves.clamp(hue, 0, 360);
  77176. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77177. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77178. if (s === 0) {
  77179. result.r = v;
  77180. result.g = v;
  77181. result.b = v;
  77182. }
  77183. else {
  77184. // sector 0 to 5
  77185. h /= 60;
  77186. var i = Math.floor(h);
  77187. // fractional part of h
  77188. var f = h - i;
  77189. var p = v * (1 - s);
  77190. var q = v * (1 - s * f);
  77191. var t = v * (1 - s * (1 - f));
  77192. switch (i) {
  77193. case 0:
  77194. result.r = v;
  77195. result.g = t;
  77196. result.b = p;
  77197. break;
  77198. case 1:
  77199. result.r = q;
  77200. result.g = v;
  77201. result.b = p;
  77202. break;
  77203. case 2:
  77204. result.r = p;
  77205. result.g = v;
  77206. result.b = t;
  77207. break;
  77208. case 3:
  77209. result.r = p;
  77210. result.g = q;
  77211. result.b = v;
  77212. break;
  77213. case 4:
  77214. result.r = t;
  77215. result.g = p;
  77216. result.b = v;
  77217. break;
  77218. default: // case 5:
  77219. result.r = v;
  77220. result.g = p;
  77221. result.b = q;
  77222. break;
  77223. }
  77224. }
  77225. result.a = 1;
  77226. };
  77227. /**
  77228. * Returns a value clamped between min and max
  77229. * @param value The value to clamp
  77230. * @param min The minimum of value
  77231. * @param max The maximum of value
  77232. * @returns The clamped value.
  77233. */
  77234. ColorCurves.clamp = function (value, min, max) {
  77235. return Math.min(Math.max(value, min), max);
  77236. };
  77237. /**
  77238. * Clones the current color curve instance.
  77239. * @return The cloned curves
  77240. */
  77241. ColorCurves.prototype.clone = function () {
  77242. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77243. };
  77244. /**
  77245. * Serializes the current color curve instance to a json representation.
  77246. * @return a JSON representation
  77247. */
  77248. ColorCurves.prototype.serialize = function () {
  77249. return BABYLON.SerializationHelper.Serialize(this);
  77250. };
  77251. /**
  77252. * Parses the color curve from a json representation.
  77253. * @param source the JSON source to parse
  77254. * @return The parsed curves
  77255. */
  77256. ColorCurves.Parse = function (source) {
  77257. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77258. };
  77259. __decorate([
  77260. BABYLON.serialize()
  77261. ], ColorCurves.prototype, "_globalHue", void 0);
  77262. __decorate([
  77263. BABYLON.serialize()
  77264. ], ColorCurves.prototype, "_globalDensity", void 0);
  77265. __decorate([
  77266. BABYLON.serialize()
  77267. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77268. __decorate([
  77269. BABYLON.serialize()
  77270. ], ColorCurves.prototype, "_globalExposure", void 0);
  77271. __decorate([
  77272. BABYLON.serialize()
  77273. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77274. __decorate([
  77275. BABYLON.serialize()
  77276. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77277. __decorate([
  77278. BABYLON.serialize()
  77279. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77280. __decorate([
  77281. BABYLON.serialize()
  77282. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77283. __decorate([
  77284. BABYLON.serialize()
  77285. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77286. __decorate([
  77287. BABYLON.serialize()
  77288. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77289. __decorate([
  77290. BABYLON.serialize()
  77291. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77292. __decorate([
  77293. BABYLON.serialize()
  77294. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77295. return ColorCurves;
  77296. }());
  77297. BABYLON.ColorCurves = ColorCurves;
  77298. })(BABYLON || (BABYLON = {}));
  77299. //# sourceMappingURL=babylon.colorCurves.js.map
  77300. var BABYLON;
  77301. (function (BABYLON) {
  77302. var RefractionPostProcess = /** @class */ (function (_super) {
  77303. __extends(RefractionPostProcess, _super);
  77304. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77305. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77306. _this.color = color;
  77307. _this.depth = depth;
  77308. _this.colorLevel = colorLevel;
  77309. _this._ownRefractionTexture = true;
  77310. _this.onActivateObservable.add(function (cam) {
  77311. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77312. });
  77313. _this.onApplyObservable.add(function (effect) {
  77314. effect.setColor3("baseColor", _this.color);
  77315. effect.setFloat("depth", _this.depth);
  77316. effect.setFloat("colorLevel", _this.colorLevel);
  77317. effect.setTexture("refractionSampler", _this._refTexture);
  77318. });
  77319. return _this;
  77320. }
  77321. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77322. /**
  77323. * Gets or sets the refraction texture
  77324. * Please note that you are responsible for disposing the texture if you set it manually
  77325. */
  77326. get: function () {
  77327. return this._refTexture;
  77328. },
  77329. set: function (value) {
  77330. if (this._refTexture && this._ownRefractionTexture) {
  77331. this._refTexture.dispose();
  77332. }
  77333. this._refTexture = value;
  77334. this._ownRefractionTexture = false;
  77335. },
  77336. enumerable: true,
  77337. configurable: true
  77338. });
  77339. // Methods
  77340. RefractionPostProcess.prototype.dispose = function (camera) {
  77341. if (this._refTexture && this._ownRefractionTexture) {
  77342. this._refTexture.dispose();
  77343. this._refTexture = null;
  77344. }
  77345. _super.prototype.dispose.call(this, camera);
  77346. };
  77347. return RefractionPostProcess;
  77348. }(BABYLON.PostProcess));
  77349. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77350. })(BABYLON || (BABYLON = {}));
  77351. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77352. var BABYLON;
  77353. (function (BABYLON) {
  77354. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77355. __extends(BlackAndWhitePostProcess, _super);
  77356. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77357. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77358. _this.degree = 1;
  77359. _this.onApplyObservable.add(function (effect) {
  77360. effect.setFloat("degree", _this.degree);
  77361. });
  77362. return _this;
  77363. }
  77364. return BlackAndWhitePostProcess;
  77365. }(BABYLON.PostProcess));
  77366. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77367. })(BABYLON || (BABYLON = {}));
  77368. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77369. var BABYLON;
  77370. (function (BABYLON) {
  77371. /**
  77372. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77373. * input texture to perform effects such as edge detection or sharpening
  77374. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77375. */
  77376. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77377. __extends(ConvolutionPostProcess, _super);
  77378. /**
  77379. * Creates a new instance ConvolutionPostProcess
  77380. * @param name The name of the effect.
  77381. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77382. * @param options The required width/height ratio to downsize to before computing the render pass.
  77383. * @param camera The camera to apply the render pass to.
  77384. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77385. * @param engine The engine which the post process will be applied. (default: current engine)
  77386. * @param reusable If the post process can be reused on the same frame. (default: false)
  77387. * @param textureType Type of textures used when performing the post process. (default: 0)
  77388. */
  77389. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77390. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77391. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77392. _this.kernel = kernel;
  77393. _this.onApply = function (effect) {
  77394. effect.setFloat2("screenSize", _this.width, _this.height);
  77395. effect.setArray("kernel", _this.kernel);
  77396. };
  77397. return _this;
  77398. }
  77399. // Statics
  77400. /**
  77401. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77402. */
  77403. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77404. /**
  77405. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77406. */
  77407. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77408. /**
  77409. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77410. */
  77411. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77412. /**
  77413. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77414. */
  77415. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77416. /**
  77417. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77418. */
  77419. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77420. /**
  77421. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77422. */
  77423. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77424. return ConvolutionPostProcess;
  77425. }(BABYLON.PostProcess));
  77426. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77427. })(BABYLON || (BABYLON = {}));
  77428. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77429. var BABYLON;
  77430. (function (BABYLON) {
  77431. var FilterPostProcess = /** @class */ (function (_super) {
  77432. __extends(FilterPostProcess, _super);
  77433. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77434. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77435. _this.kernelMatrix = kernelMatrix;
  77436. _this.onApply = function (effect) {
  77437. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77438. };
  77439. return _this;
  77440. }
  77441. return FilterPostProcess;
  77442. }(BABYLON.PostProcess));
  77443. BABYLON.FilterPostProcess = FilterPostProcess;
  77444. })(BABYLON || (BABYLON = {}));
  77445. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77446. var BABYLON;
  77447. (function (BABYLON) {
  77448. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77449. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77450. __extends(VolumetricLightScatteringPostProcess, _super);
  77451. /**
  77452. * @constructor
  77453. * @param {string} name - The post-process name
  77454. * @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)
  77455. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77456. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77457. * @param {number} samples - The post-process quality, default 100
  77458. * @param {number} samplingMode - The post-process filtering mode
  77459. * @param {BABYLON.Engine} engine - The babylon engine
  77460. * @param {boolean} reusable - If the post-process is reusable
  77461. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77462. */
  77463. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77464. if (samples === void 0) { samples = 100; }
  77465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77466. 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;
  77467. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77468. /**
  77469. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77470. */
  77471. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77472. /**
  77473. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77474. */
  77475. _this.useCustomMeshPosition = false;
  77476. /**
  77477. * If the post-process should inverse the light scattering direction
  77478. */
  77479. _this.invert = true;
  77480. /**
  77481. * Array containing the excluded meshes not rendered in the internal pass
  77482. */
  77483. _this.excludedMeshes = new Array();
  77484. /**
  77485. * Controls the overall intensity of the post-process
  77486. */
  77487. _this.exposure = 0.3;
  77488. /**
  77489. * Dissipates each sample's contribution in range [0, 1]
  77490. */
  77491. _this.decay = 0.96815;
  77492. /**
  77493. * Controls the overall intensity of each sample
  77494. */
  77495. _this.weight = 0.58767;
  77496. /**
  77497. * Controls the density of each sample
  77498. */
  77499. _this.density = 0.926;
  77500. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77501. engine = scene.getEngine();
  77502. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77503. // Configure mesh
  77504. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77505. // Configure
  77506. _this._createPass(scene, ratio.passRatio || ratio);
  77507. _this.onActivate = function (camera) {
  77508. if (!_this.isSupported) {
  77509. _this.dispose(camera);
  77510. }
  77511. _this.onActivate = null;
  77512. };
  77513. _this.onApplyObservable.add(function (effect) {
  77514. _this._updateMeshScreenCoordinates(scene);
  77515. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77516. effect.setFloat("exposure", _this.exposure);
  77517. effect.setFloat("decay", _this.decay);
  77518. effect.setFloat("weight", _this.weight);
  77519. effect.setFloat("density", _this.density);
  77520. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77521. });
  77522. return _this;
  77523. }
  77524. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77525. get: function () {
  77526. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77527. return false;
  77528. },
  77529. set: function (useDiffuseColor) {
  77530. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77531. },
  77532. enumerable: true,
  77533. configurable: true
  77534. });
  77535. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77536. return "VolumetricLightScatteringPostProcess";
  77537. };
  77538. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77539. var mesh = subMesh.getMesh();
  77540. // Render this.mesh as default
  77541. if (mesh === this.mesh && mesh.material) {
  77542. return mesh.material.isReady(mesh);
  77543. }
  77544. var defines = [];
  77545. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77546. var material = subMesh.getMaterial();
  77547. // Alpha test
  77548. if (material) {
  77549. if (material.needAlphaTesting()) {
  77550. defines.push("#define ALPHATEST");
  77551. }
  77552. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77553. attribs.push(BABYLON.VertexBuffer.UVKind);
  77554. defines.push("#define UV1");
  77555. }
  77556. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77557. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77558. defines.push("#define UV2");
  77559. }
  77560. }
  77561. // Bones
  77562. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77563. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77564. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77565. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77566. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77567. }
  77568. else {
  77569. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77570. }
  77571. // Instances
  77572. if (useInstances) {
  77573. defines.push("#define INSTANCES");
  77574. attribs.push("world0");
  77575. attribs.push("world1");
  77576. attribs.push("world2");
  77577. attribs.push("world3");
  77578. }
  77579. // Get correct effect
  77580. var join = defines.join("\n");
  77581. if (this._cachedDefines !== join) {
  77582. this._cachedDefines = join;
  77583. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77584. }
  77585. return this._volumetricLightScatteringPass.isReady();
  77586. };
  77587. /**
  77588. * Sets the new light position for light scattering effect
  77589. * @param {BABYLON.Vector3} The new custom light position
  77590. */
  77591. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77592. this.customMeshPosition = position;
  77593. };
  77594. /**
  77595. * Returns the light position for light scattering effect
  77596. * @return {BABYLON.Vector3} The custom light position
  77597. */
  77598. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77599. return this.customMeshPosition;
  77600. };
  77601. /**
  77602. * Disposes the internal assets and detaches the post-process from the camera
  77603. */
  77604. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77605. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77606. if (rttIndex !== -1) {
  77607. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77608. }
  77609. this._volumetricLightScatteringRTT.dispose();
  77610. _super.prototype.dispose.call(this, camera);
  77611. };
  77612. /**
  77613. * Returns the render target texture used by the post-process
  77614. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77615. */
  77616. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77617. return this._volumetricLightScatteringRTT;
  77618. };
  77619. // Private methods
  77620. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77621. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77622. return true;
  77623. }
  77624. return false;
  77625. };
  77626. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77627. var _this = this;
  77628. var engine = scene.getEngine();
  77629. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77630. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77631. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77632. this._volumetricLightScatteringRTT.renderList = null;
  77633. this._volumetricLightScatteringRTT.renderParticles = false;
  77634. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77635. var camera = this.getCamera();
  77636. if (camera) {
  77637. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77638. }
  77639. else {
  77640. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77641. }
  77642. // Custom render function for submeshes
  77643. var renderSubMesh = function (subMesh) {
  77644. var mesh = subMesh.getRenderingMesh();
  77645. if (_this._meshExcluded(mesh)) {
  77646. return;
  77647. }
  77648. var material = subMesh.getMaterial();
  77649. if (!material) {
  77650. return;
  77651. }
  77652. var scene = mesh.getScene();
  77653. var engine = scene.getEngine();
  77654. // Culling
  77655. engine.setState(material.backFaceCulling);
  77656. // Managing instances
  77657. var batch = mesh._getInstancesRenderList(subMesh._id);
  77658. if (batch.mustReturn) {
  77659. return;
  77660. }
  77661. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77662. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77663. var effect = _this._volumetricLightScatteringPass;
  77664. if (mesh === _this.mesh) {
  77665. if (subMesh.effect) {
  77666. effect = subMesh.effect;
  77667. }
  77668. else {
  77669. effect = material.getEffect();
  77670. }
  77671. }
  77672. engine.enableEffect(effect);
  77673. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77674. if (mesh === _this.mesh) {
  77675. material.bind(mesh.getWorldMatrix(), mesh);
  77676. }
  77677. else {
  77678. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77679. // Alpha test
  77680. if (material && material.needAlphaTesting()) {
  77681. var alphaTexture = material.getAlphaTestTexture();
  77682. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77683. if (alphaTexture) {
  77684. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77685. }
  77686. }
  77687. // Bones
  77688. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77689. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77690. }
  77691. }
  77692. // Draw
  77693. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77694. }
  77695. };
  77696. // Render target texture callbacks
  77697. var savedSceneClearColor;
  77698. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77699. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77700. savedSceneClearColor = scene.clearColor;
  77701. scene.clearColor = sceneClearColor;
  77702. });
  77703. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77704. scene.clearColor = savedSceneClearColor;
  77705. });
  77706. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77707. var engine = scene.getEngine();
  77708. var index;
  77709. if (depthOnlySubMeshes.length) {
  77710. engine.setColorWrite(false);
  77711. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77712. renderSubMesh(depthOnlySubMeshes.data[index]);
  77713. }
  77714. engine.setColorWrite(true);
  77715. }
  77716. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77717. renderSubMesh(opaqueSubMeshes.data[index]);
  77718. }
  77719. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77720. renderSubMesh(alphaTestSubMeshes.data[index]);
  77721. }
  77722. if (transparentSubMeshes.length) {
  77723. // Sort sub meshes
  77724. for (index = 0; index < transparentSubMeshes.length; index++) {
  77725. var submesh = transparentSubMeshes.data[index];
  77726. var boundingInfo = submesh.getBoundingInfo();
  77727. if (boundingInfo && scene.activeCamera) {
  77728. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77729. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77730. }
  77731. }
  77732. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77733. sortedArray.sort(function (a, b) {
  77734. // Alpha index first
  77735. if (a._alphaIndex > b._alphaIndex) {
  77736. return 1;
  77737. }
  77738. if (a._alphaIndex < b._alphaIndex) {
  77739. return -1;
  77740. }
  77741. // Then distance to camera
  77742. if (a._distanceToCamera < b._distanceToCamera) {
  77743. return 1;
  77744. }
  77745. if (a._distanceToCamera > b._distanceToCamera) {
  77746. return -1;
  77747. }
  77748. return 0;
  77749. });
  77750. // Render sub meshes
  77751. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77752. for (index = 0; index < sortedArray.length; index++) {
  77753. renderSubMesh(sortedArray[index]);
  77754. }
  77755. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77756. }
  77757. };
  77758. };
  77759. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77760. var transform = scene.getTransformMatrix();
  77761. var meshPosition;
  77762. if (this.useCustomMeshPosition) {
  77763. meshPosition = this.customMeshPosition;
  77764. }
  77765. else if (this.attachedNode) {
  77766. meshPosition = this.attachedNode.position;
  77767. }
  77768. else {
  77769. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77770. }
  77771. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77772. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77773. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77774. if (this.invert)
  77775. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77776. };
  77777. // Static methods
  77778. /**
  77779. * Creates a default mesh for the Volumeric Light Scattering post-process
  77780. * @param {string} The mesh name
  77781. * @param {BABYLON.Scene} The scene where to create the mesh
  77782. * @return {BABYLON.Mesh} the default mesh
  77783. */
  77784. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77785. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77786. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77787. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77788. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77789. mesh.material = material;
  77790. return mesh;
  77791. };
  77792. __decorate([
  77793. BABYLON.serializeAsVector3()
  77794. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77795. __decorate([
  77796. BABYLON.serialize()
  77797. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77798. __decorate([
  77799. BABYLON.serialize()
  77800. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77801. __decorate([
  77802. BABYLON.serializeAsMeshReference()
  77803. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77804. __decorate([
  77805. BABYLON.serialize()
  77806. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77807. __decorate([
  77808. BABYLON.serialize()
  77809. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77810. __decorate([
  77811. BABYLON.serialize()
  77812. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77813. __decorate([
  77814. BABYLON.serialize()
  77815. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77816. __decorate([
  77817. BABYLON.serialize()
  77818. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77819. return VolumetricLightScatteringPostProcess;
  77820. }(BABYLON.PostProcess));
  77821. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77822. })(BABYLON || (BABYLON = {}));
  77823. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77824. //
  77825. // This post-process allows the modification of rendered colors by using
  77826. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77827. //
  77828. // The object needs to be provided an url to a texture containing the color
  77829. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77830. // Use an image editing software to tweak the LUT to match your needs.
  77831. //
  77832. // For an example of a color LUT, see here:
  77833. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77834. // For explanations on color grading, see here:
  77835. // http://udn.epicgames.com/Three/ColorGrading.html
  77836. //
  77837. var BABYLON;
  77838. (function (BABYLON) {
  77839. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77840. __extends(ColorCorrectionPostProcess, _super);
  77841. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77842. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77843. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77844. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77845. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77846. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77847. _this.onApply = function (effect) {
  77848. effect.setTexture("colorTable", _this._colorTableTexture);
  77849. };
  77850. return _this;
  77851. }
  77852. return ColorCorrectionPostProcess;
  77853. }(BABYLON.PostProcess));
  77854. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77855. })(BABYLON || (BABYLON = {}));
  77856. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77857. var BABYLON;
  77858. (function (BABYLON) {
  77859. /** Defines operator used for tonemapping */
  77860. var TonemappingOperator;
  77861. (function (TonemappingOperator) {
  77862. /** Hable */
  77863. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77864. /** Reinhard */
  77865. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77866. /** HejiDawson */
  77867. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77868. /** Photographic */
  77869. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77870. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77871. ;
  77872. /**
  77873. * Defines a post process to apply tone mapping
  77874. */
  77875. var TonemapPostProcess = /** @class */ (function (_super) {
  77876. __extends(TonemapPostProcess, _super);
  77877. /**
  77878. * Creates a new TonemapPostProcess
  77879. * @param name defines the name of the postprocess
  77880. * @param _operator defines the operator to use
  77881. * @param exposureAdjustment defines the required exposure adjustement
  77882. * @param camera defines the camera to use (can be null)
  77883. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77884. * @param engine defines the hosting engine (can be ignore if camera is set)
  77885. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77886. */
  77887. function TonemapPostProcess(name, _operator,
  77888. /** Defines the required exposure adjustement */
  77889. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77890. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77891. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77892. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77893. _this._operator = _operator;
  77894. _this.exposureAdjustment = exposureAdjustment;
  77895. var defines = "#define ";
  77896. if (_this._operator === TonemappingOperator.Hable)
  77897. defines += "HABLE_TONEMAPPING";
  77898. else if (_this._operator === TonemappingOperator.Reinhard)
  77899. defines += "REINHARD_TONEMAPPING";
  77900. else if (_this._operator === TonemappingOperator.HejiDawson)
  77901. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77902. else if (_this._operator === TonemappingOperator.Photographic)
  77903. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77904. //sadly a second call to create the effect.
  77905. _this.updateEffect(defines);
  77906. _this.onApply = function (effect) {
  77907. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77908. };
  77909. return _this;
  77910. }
  77911. return TonemapPostProcess;
  77912. }(BABYLON.PostProcess));
  77913. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77914. })(BABYLON || (BABYLON = {}));
  77915. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77916. var BABYLON;
  77917. (function (BABYLON) {
  77918. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77919. __extends(DisplayPassPostProcess, _super);
  77920. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77921. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77922. }
  77923. return DisplayPassPostProcess;
  77924. }(BABYLON.PostProcess));
  77925. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77926. })(BABYLON || (BABYLON = {}));
  77927. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77928. var BABYLON;
  77929. (function (BABYLON) {
  77930. var HighlightsPostProcess = /** @class */ (function (_super) {
  77931. __extends(HighlightsPostProcess, _super);
  77932. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77933. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77934. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77935. }
  77936. return HighlightsPostProcess;
  77937. }(BABYLON.PostProcess));
  77938. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77939. })(BABYLON || (BABYLON = {}));
  77940. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77941. var BABYLON;
  77942. (function (BABYLON) {
  77943. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77944. __extends(ImageProcessingPostProcess, _super);
  77945. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77946. if (camera === void 0) { camera = null; }
  77947. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77948. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77949. _this._fromLinearSpace = true;
  77950. /**
  77951. * Defines cache preventing GC.
  77952. */
  77953. _this._defines = {
  77954. IMAGEPROCESSING: false,
  77955. VIGNETTE: false,
  77956. VIGNETTEBLENDMODEMULTIPLY: false,
  77957. VIGNETTEBLENDMODEOPAQUE: false,
  77958. TONEMAPPING: false,
  77959. CONTRAST: false,
  77960. COLORCURVES: false,
  77961. COLORGRADING: false,
  77962. COLORGRADING3D: false,
  77963. FROMLINEARSPACE: false,
  77964. SAMPLER3DGREENDEPTH: false,
  77965. SAMPLER3DBGRMAP: false,
  77966. IMAGEPROCESSINGPOSTPROCESS: false,
  77967. EXPOSURE: false,
  77968. };
  77969. // Setup the configuration as forced by the constructor. This would then not force the
  77970. // scene materials output in linear space and let untouched the default forward pass.
  77971. if (imageProcessingConfiguration) {
  77972. imageProcessingConfiguration.applyByPostProcess = true;
  77973. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77974. // This will cause the shader to be compiled
  77975. _this.fromLinearSpace = false;
  77976. }
  77977. // Setup the default processing configuration to the scene.
  77978. else {
  77979. _this._attachImageProcessingConfiguration(null, true);
  77980. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77981. }
  77982. _this.onApply = function (effect) {
  77983. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77984. };
  77985. return _this;
  77986. }
  77987. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77988. /**
  77989. * Gets the image processing configuration used either in this material.
  77990. */
  77991. get: function () {
  77992. return this._imageProcessingConfiguration;
  77993. },
  77994. /**
  77995. * Sets the Default image processing configuration used either in the this material.
  77996. *
  77997. * If sets to null, the scene one is in use.
  77998. */
  77999. set: function (value) {
  78000. this._attachImageProcessingConfiguration(value);
  78001. },
  78002. enumerable: true,
  78003. configurable: true
  78004. });
  78005. /**
  78006. * Attaches a new image processing configuration to the PBR Material.
  78007. * @param configuration
  78008. */
  78009. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78010. var _this = this;
  78011. if (doNotBuild === void 0) { doNotBuild = false; }
  78012. if (configuration === this._imageProcessingConfiguration) {
  78013. return;
  78014. }
  78015. // Detaches observer.
  78016. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78017. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78018. }
  78019. // Pick the scene configuration if needed.
  78020. if (!configuration) {
  78021. var scene = null;
  78022. var engine = this.getEngine();
  78023. var camera = this.getCamera();
  78024. if (camera) {
  78025. scene = camera.getScene();
  78026. }
  78027. else if (engine && engine.scenes) {
  78028. var scenes = engine.scenes;
  78029. scene = scenes[scenes.length - 1];
  78030. }
  78031. else {
  78032. scene = BABYLON.Engine.LastCreatedScene;
  78033. }
  78034. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78035. }
  78036. else {
  78037. this._imageProcessingConfiguration = configuration;
  78038. }
  78039. // Attaches observer.
  78040. if (this._imageProcessingConfiguration) {
  78041. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78042. _this._updateParameters();
  78043. });
  78044. }
  78045. // Ensure the effect will be rebuilt.
  78046. if (!doNotBuild) {
  78047. this._updateParameters();
  78048. }
  78049. };
  78050. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78051. /**
  78052. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78053. */
  78054. get: function () {
  78055. return this.imageProcessingConfiguration.colorCurves;
  78056. },
  78057. /**
  78058. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78059. */
  78060. set: function (value) {
  78061. this.imageProcessingConfiguration.colorCurves = value;
  78062. },
  78063. enumerable: true,
  78064. configurable: true
  78065. });
  78066. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78067. /**
  78068. * Gets wether the color curves effect is enabled.
  78069. */
  78070. get: function () {
  78071. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78072. },
  78073. /**
  78074. * Sets wether the color curves effect is enabled.
  78075. */
  78076. set: function (value) {
  78077. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78078. },
  78079. enumerable: true,
  78080. configurable: true
  78081. });
  78082. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78083. /**
  78084. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78085. */
  78086. get: function () {
  78087. return this.imageProcessingConfiguration.colorGradingTexture;
  78088. },
  78089. /**
  78090. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78091. */
  78092. set: function (value) {
  78093. this.imageProcessingConfiguration.colorGradingTexture = value;
  78094. },
  78095. enumerable: true,
  78096. configurable: true
  78097. });
  78098. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78099. /**
  78100. * Gets wether the color grading effect is enabled.
  78101. */
  78102. get: function () {
  78103. return this.imageProcessingConfiguration.colorGradingEnabled;
  78104. },
  78105. /**
  78106. * Gets wether the color grading effect is enabled.
  78107. */
  78108. set: function (value) {
  78109. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78110. },
  78111. enumerable: true,
  78112. configurable: true
  78113. });
  78114. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78115. /**
  78116. * Gets exposure used in the effect.
  78117. */
  78118. get: function () {
  78119. return this.imageProcessingConfiguration.exposure;
  78120. },
  78121. /**
  78122. * Sets exposure used in the effect.
  78123. */
  78124. set: function (value) {
  78125. this.imageProcessingConfiguration.exposure = value;
  78126. },
  78127. enumerable: true,
  78128. configurable: true
  78129. });
  78130. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78131. /**
  78132. * Gets wether tonemapping is enabled or not.
  78133. */
  78134. get: function () {
  78135. return this._imageProcessingConfiguration.toneMappingEnabled;
  78136. },
  78137. /**
  78138. * Sets wether tonemapping is enabled or not
  78139. */
  78140. set: function (value) {
  78141. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78142. },
  78143. enumerable: true,
  78144. configurable: true
  78145. });
  78146. ;
  78147. ;
  78148. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78149. /**
  78150. * Gets contrast used in the effect.
  78151. */
  78152. get: function () {
  78153. return this.imageProcessingConfiguration.contrast;
  78154. },
  78155. /**
  78156. * Sets contrast used in the effect.
  78157. */
  78158. set: function (value) {
  78159. this.imageProcessingConfiguration.contrast = value;
  78160. },
  78161. enumerable: true,
  78162. configurable: true
  78163. });
  78164. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78165. /**
  78166. * Gets Vignette stretch size.
  78167. */
  78168. get: function () {
  78169. return this.imageProcessingConfiguration.vignetteStretch;
  78170. },
  78171. /**
  78172. * Sets Vignette stretch size.
  78173. */
  78174. set: function (value) {
  78175. this.imageProcessingConfiguration.vignetteStretch = value;
  78176. },
  78177. enumerable: true,
  78178. configurable: true
  78179. });
  78180. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78181. /**
  78182. * Gets Vignette centre X Offset.
  78183. */
  78184. get: function () {
  78185. return this.imageProcessingConfiguration.vignetteCentreX;
  78186. },
  78187. /**
  78188. * Sets Vignette centre X Offset.
  78189. */
  78190. set: function (value) {
  78191. this.imageProcessingConfiguration.vignetteCentreX = value;
  78192. },
  78193. enumerable: true,
  78194. configurable: true
  78195. });
  78196. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78197. /**
  78198. * Gets Vignette centre Y Offset.
  78199. */
  78200. get: function () {
  78201. return this.imageProcessingConfiguration.vignetteCentreY;
  78202. },
  78203. /**
  78204. * Sets Vignette centre Y Offset.
  78205. */
  78206. set: function (value) {
  78207. this.imageProcessingConfiguration.vignetteCentreY = value;
  78208. },
  78209. enumerable: true,
  78210. configurable: true
  78211. });
  78212. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78213. /**
  78214. * Gets Vignette weight or intensity of the vignette effect.
  78215. */
  78216. get: function () {
  78217. return this.imageProcessingConfiguration.vignetteWeight;
  78218. },
  78219. /**
  78220. * Sets Vignette weight or intensity of the vignette effect.
  78221. */
  78222. set: function (value) {
  78223. this.imageProcessingConfiguration.vignetteWeight = value;
  78224. },
  78225. enumerable: true,
  78226. configurable: true
  78227. });
  78228. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78229. /**
  78230. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78231. * if vignetteEnabled is set to true.
  78232. */
  78233. get: function () {
  78234. return this.imageProcessingConfiguration.vignetteColor;
  78235. },
  78236. /**
  78237. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78238. * if vignetteEnabled is set to true.
  78239. */
  78240. set: function (value) {
  78241. this.imageProcessingConfiguration.vignetteColor = value;
  78242. },
  78243. enumerable: true,
  78244. configurable: true
  78245. });
  78246. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78247. /**
  78248. * Gets Camera field of view used by the Vignette effect.
  78249. */
  78250. get: function () {
  78251. return this.imageProcessingConfiguration.vignetteCameraFov;
  78252. },
  78253. /**
  78254. * Sets Camera field of view used by the Vignette effect.
  78255. */
  78256. set: function (value) {
  78257. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78258. },
  78259. enumerable: true,
  78260. configurable: true
  78261. });
  78262. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78263. /**
  78264. * Gets the vignette blend mode allowing different kind of effect.
  78265. */
  78266. get: function () {
  78267. return this.imageProcessingConfiguration.vignetteBlendMode;
  78268. },
  78269. /**
  78270. * Sets the vignette blend mode allowing different kind of effect.
  78271. */
  78272. set: function (value) {
  78273. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78274. },
  78275. enumerable: true,
  78276. configurable: true
  78277. });
  78278. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78279. /**
  78280. * Gets wether the vignette effect is enabled.
  78281. */
  78282. get: function () {
  78283. return this.imageProcessingConfiguration.vignetteEnabled;
  78284. },
  78285. /**
  78286. * Sets wether the vignette effect is enabled.
  78287. */
  78288. set: function (value) {
  78289. this.imageProcessingConfiguration.vignetteEnabled = value;
  78290. },
  78291. enumerable: true,
  78292. configurable: true
  78293. });
  78294. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78295. /**
  78296. * Gets wether the input of the processing is in Gamma or Linear Space.
  78297. */
  78298. get: function () {
  78299. return this._fromLinearSpace;
  78300. },
  78301. /**
  78302. * Sets wether the input of the processing is in Gamma or Linear Space.
  78303. */
  78304. set: function (value) {
  78305. if (this._fromLinearSpace === value) {
  78306. return;
  78307. }
  78308. this._fromLinearSpace = value;
  78309. this._updateParameters();
  78310. },
  78311. enumerable: true,
  78312. configurable: true
  78313. });
  78314. ImageProcessingPostProcess.prototype.getClassName = function () {
  78315. return "ImageProcessingPostProcess";
  78316. };
  78317. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78318. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78319. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78320. var defines = "";
  78321. for (var define in this._defines) {
  78322. if (this._defines[define]) {
  78323. defines += "#define " + define + ";\r\n";
  78324. }
  78325. }
  78326. var samplers = ["textureSampler"];
  78327. var uniforms = ["scale"];
  78328. if (BABYLON.ImageProcessingConfiguration) {
  78329. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78330. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78331. }
  78332. this.updateEffect(defines, uniforms, samplers);
  78333. };
  78334. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78335. _super.prototype.dispose.call(this, camera);
  78336. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78337. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78338. }
  78339. if (this._imageProcessingConfiguration) {
  78340. this.imageProcessingConfiguration.applyByPostProcess = false;
  78341. }
  78342. };
  78343. __decorate([
  78344. BABYLON.serialize()
  78345. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78346. return ImageProcessingPostProcess;
  78347. }(BABYLON.PostProcess));
  78348. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78349. })(BABYLON || (BABYLON = {}));
  78350. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78351. var BABYLON;
  78352. (function (BABYLON) {
  78353. /**
  78354. * Class used to store bone information
  78355. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78356. */
  78357. var Bone = /** @class */ (function (_super) {
  78358. __extends(Bone, _super);
  78359. /**
  78360. * Create a new bone
  78361. * @param name defines the bone name
  78362. * @param skeleton defines the parent skeleton
  78363. * @param parentBone defines the parent (can be null if the bone is the root)
  78364. * @param localMatrix defines the local matrix
  78365. * @param restPose defines the rest pose matrix
  78366. * @param baseMatrix defines the base matrix
  78367. * @param index defines index of the bone in the hiearchy
  78368. */
  78369. function Bone(
  78370. /**
  78371. * defines the bone name
  78372. */
  78373. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78374. if (parentBone === void 0) { parentBone = null; }
  78375. if (localMatrix === void 0) { localMatrix = null; }
  78376. if (restPose === void 0) { restPose = null; }
  78377. if (baseMatrix === void 0) { baseMatrix = null; }
  78378. if (index === void 0) { index = null; }
  78379. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78380. _this.name = name;
  78381. /**
  78382. * Gets the list of child bones
  78383. */
  78384. _this.children = new Array();
  78385. /** Gets the animations associated with this bone */
  78386. _this.animations = new Array();
  78387. /**
  78388. * @hidden Internal only
  78389. * Set this value to map this bone to a different index in the transform matrices
  78390. * Set this value to -1 to exclude the bone from the transform matrices
  78391. */
  78392. _this._index = null;
  78393. _this._absoluteTransform = new BABYLON.Matrix();
  78394. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78395. _this._scalingDeterminant = 1;
  78396. _this._worldTransform = new BABYLON.Matrix();
  78397. _this._needToDecompose = true;
  78398. _this._needToCompose = false;
  78399. _this._skeleton = skeleton;
  78400. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78401. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78402. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78403. _this._index = index;
  78404. skeleton.bones.push(_this);
  78405. _this.setParent(parentBone, false);
  78406. if (baseMatrix || localMatrix) {
  78407. _this._updateDifferenceMatrix();
  78408. }
  78409. return _this;
  78410. }
  78411. Object.defineProperty(Bone.prototype, "_matrix", {
  78412. /** @hidden */
  78413. get: function () {
  78414. this._compose();
  78415. return this._localMatrix;
  78416. },
  78417. /** @hidden */
  78418. set: function (value) {
  78419. this._localMatrix.copyFrom(value);
  78420. this._needToDecompose = true;
  78421. },
  78422. enumerable: true,
  78423. configurable: true
  78424. });
  78425. // Members
  78426. /**
  78427. * Gets the parent skeleton
  78428. * @returns a skeleton
  78429. */
  78430. Bone.prototype.getSkeleton = function () {
  78431. return this._skeleton;
  78432. };
  78433. /**
  78434. * Gets parent bone
  78435. * @returns a bone or null if the bone is the root of the bone hierarchy
  78436. */
  78437. Bone.prototype.getParent = function () {
  78438. return this._parent;
  78439. };
  78440. /**
  78441. * Sets the parent bone
  78442. * @param parent defines the parent (can be null if the bone is the root)
  78443. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78444. */
  78445. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78446. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78447. if (this._parent === parent) {
  78448. return;
  78449. }
  78450. if (this._parent) {
  78451. var index = this._parent.children.indexOf(this);
  78452. if (index !== -1) {
  78453. this._parent.children.splice(index, 1);
  78454. }
  78455. }
  78456. this._parent = parent;
  78457. if (this._parent) {
  78458. this._parent.children.push(this);
  78459. }
  78460. if (updateDifferenceMatrix) {
  78461. this._updateDifferenceMatrix();
  78462. }
  78463. this.markAsDirty();
  78464. };
  78465. /**
  78466. * Gets the local matrix
  78467. * @returns a matrix
  78468. */
  78469. Bone.prototype.getLocalMatrix = function () {
  78470. this._compose();
  78471. return this._localMatrix;
  78472. };
  78473. /**
  78474. * Gets the base matrix (initial matrix which remains unchanged)
  78475. * @returns a matrix
  78476. */
  78477. Bone.prototype.getBaseMatrix = function () {
  78478. return this._baseMatrix;
  78479. };
  78480. /**
  78481. * Gets the rest pose matrix
  78482. * @returns a matrix
  78483. */
  78484. Bone.prototype.getRestPose = function () {
  78485. return this._restPose;
  78486. };
  78487. /**
  78488. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78489. */
  78490. Bone.prototype.getWorldMatrix = function () {
  78491. return this._worldTransform;
  78492. };
  78493. /**
  78494. * Sets the local matrix to rest pose matrix
  78495. */
  78496. Bone.prototype.returnToRest = function () {
  78497. this.updateMatrix(this._restPose.clone());
  78498. };
  78499. /**
  78500. * Gets the inverse of the absolute transform matrix.
  78501. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78502. * @returns a matrix
  78503. */
  78504. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78505. return this._invertedAbsoluteTransform;
  78506. };
  78507. /**
  78508. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78509. * @returns a matrix
  78510. */
  78511. Bone.prototype.getAbsoluteTransform = function () {
  78512. return this._absoluteTransform;
  78513. };
  78514. Object.defineProperty(Bone.prototype, "position", {
  78515. // Properties (matches AbstractMesh properties)
  78516. /** Gets or sets current position (in local space) */
  78517. get: function () {
  78518. this._decompose();
  78519. return this._localPosition;
  78520. },
  78521. set: function (newPosition) {
  78522. this._decompose();
  78523. this._localPosition.copyFrom(newPosition);
  78524. this._markAsDirtyAndCompose();
  78525. },
  78526. enumerable: true,
  78527. configurable: true
  78528. });
  78529. Object.defineProperty(Bone.prototype, "rotation", {
  78530. /** Gets or sets current rotation (in local space) */
  78531. get: function () {
  78532. return this.getRotation();
  78533. },
  78534. set: function (newRotation) {
  78535. this.setRotation(newRotation);
  78536. },
  78537. enumerable: true,
  78538. configurable: true
  78539. });
  78540. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78541. /** Gets or sets current rotation quaternion (in local space) */
  78542. get: function () {
  78543. this._decompose();
  78544. return this._localRotation;
  78545. },
  78546. set: function (newRotation) {
  78547. this.setRotationQuaternion(newRotation);
  78548. },
  78549. enumerable: true,
  78550. configurable: true
  78551. });
  78552. Object.defineProperty(Bone.prototype, "scaling", {
  78553. /** Gets or sets current scaling (in local space) */
  78554. get: function () {
  78555. return this.getScale();
  78556. },
  78557. set: function (newScaling) {
  78558. this.setScale(newScaling);
  78559. },
  78560. enumerable: true,
  78561. configurable: true
  78562. });
  78563. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78564. /**
  78565. * Gets the animation properties override
  78566. */
  78567. get: function () {
  78568. return this._skeleton.animationPropertiesOverride;
  78569. },
  78570. enumerable: true,
  78571. configurable: true
  78572. });
  78573. // Methods
  78574. Bone.prototype._decompose = function () {
  78575. if (!this._needToDecompose) {
  78576. return;
  78577. }
  78578. this._needToDecompose = false;
  78579. if (!this._localScaling) {
  78580. this._localScaling = BABYLON.Vector3.Zero();
  78581. this._localRotation = BABYLON.Quaternion.Zero();
  78582. this._localPosition = BABYLON.Vector3.Zero();
  78583. }
  78584. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78585. };
  78586. Bone.prototype._compose = function () {
  78587. if (!this._needToCompose) {
  78588. return;
  78589. }
  78590. this._needToCompose = false;
  78591. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78592. };
  78593. /**
  78594. * Update the base and local matrices
  78595. * @param matrix defines the new base or local matrix
  78596. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78597. * @param updateLocalMatrix defines if the local matrix should be updated
  78598. */
  78599. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78600. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78601. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78602. this._baseMatrix.copyFrom(matrix);
  78603. if (updateDifferenceMatrix) {
  78604. this._updateDifferenceMatrix();
  78605. }
  78606. if (updateLocalMatrix) {
  78607. this._localMatrix.copyFrom(matrix);
  78608. this._markAsDirtyAndDecompose();
  78609. }
  78610. else {
  78611. this.markAsDirty();
  78612. }
  78613. };
  78614. /** @hidden */
  78615. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78616. if (updateChildren === void 0) { updateChildren = true; }
  78617. if (!rootMatrix) {
  78618. rootMatrix = this._baseMatrix;
  78619. }
  78620. if (this._parent) {
  78621. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78622. }
  78623. else {
  78624. this._absoluteTransform.copyFrom(rootMatrix);
  78625. }
  78626. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78627. if (updateChildren) {
  78628. for (var index = 0; index < this.children.length; index++) {
  78629. this.children[index]._updateDifferenceMatrix();
  78630. }
  78631. }
  78632. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78633. };
  78634. /**
  78635. * Flag the bone as dirty (Forcing it to update everything)
  78636. */
  78637. Bone.prototype.markAsDirty = function () {
  78638. this._currentRenderId++;
  78639. this._childRenderId++;
  78640. this._skeleton._markAsDirty();
  78641. };
  78642. Bone.prototype._markAsDirtyAndCompose = function () {
  78643. this.markAsDirty();
  78644. this._needToCompose = true;
  78645. };
  78646. Bone.prototype._markAsDirtyAndDecompose = function () {
  78647. this.markAsDirty();
  78648. this._needToDecompose = true;
  78649. };
  78650. /**
  78651. * Copy an animation range from another bone
  78652. * @param source defines the source bone
  78653. * @param rangeName defines the range name to copy
  78654. * @param frameOffset defines the frame offset
  78655. * @param rescaleAsRequired defines if rescaling must be applied if required
  78656. * @param skelDimensionsRatio defines the scaling ratio
  78657. * @returns true if operation was successful
  78658. */
  78659. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78660. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78661. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78662. // all animation may be coming from a library skeleton, so may need to create animation
  78663. if (this.animations.length === 0) {
  78664. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78665. this.animations[0].setKeys([]);
  78666. }
  78667. // get animation info / verify there is such a range from the source bone
  78668. var sourceRange = source.animations[0].getRange(rangeName);
  78669. if (!sourceRange) {
  78670. return false;
  78671. }
  78672. var from = sourceRange.from;
  78673. var to = sourceRange.to;
  78674. var sourceKeys = source.animations[0].getKeys();
  78675. // rescaling prep
  78676. var sourceBoneLength = source.length;
  78677. var sourceParent = source.getParent();
  78678. var parent = this.getParent();
  78679. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78680. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78681. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78682. var destKeys = this.animations[0].getKeys();
  78683. // loop vars declaration
  78684. var orig;
  78685. var origTranslation;
  78686. var mat;
  78687. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78688. orig = sourceKeys[key];
  78689. if (orig.frame >= from && orig.frame <= to) {
  78690. if (rescaleAsRequired) {
  78691. mat = orig.value.clone();
  78692. // scale based on parent ratio, when bone has parent
  78693. if (parentScalingReqd) {
  78694. origTranslation = mat.getTranslation();
  78695. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78696. // scale based on skeleton dimension ratio when root bone, and value is passed
  78697. }
  78698. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78699. origTranslation = mat.getTranslation();
  78700. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78701. // use original when root bone, and no data for skelDimensionsRatio
  78702. }
  78703. else {
  78704. mat = orig.value;
  78705. }
  78706. }
  78707. else {
  78708. mat = orig.value;
  78709. }
  78710. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78711. }
  78712. }
  78713. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78714. return true;
  78715. };
  78716. /**
  78717. * Translate the bone in local or world space
  78718. * @param vec The amount to translate the bone
  78719. * @param space The space that the translation is in
  78720. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78721. */
  78722. Bone.prototype.translate = function (vec, space, mesh) {
  78723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78724. var lm = this.getLocalMatrix();
  78725. if (space == BABYLON.Space.LOCAL) {
  78726. lm.m[12] += vec.x;
  78727. lm.m[13] += vec.y;
  78728. lm.m[14] += vec.z;
  78729. }
  78730. else {
  78731. var wm = null;
  78732. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78733. if (mesh) {
  78734. wm = mesh.getWorldMatrix();
  78735. }
  78736. this._skeleton.computeAbsoluteTransforms();
  78737. var tmat = Bone._tmpMats[0];
  78738. var tvec = Bone._tmpVecs[0];
  78739. if (this._parent) {
  78740. if (mesh && wm) {
  78741. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78742. tmat.multiplyToRef(wm, tmat);
  78743. }
  78744. else {
  78745. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78746. }
  78747. }
  78748. tmat.m[12] = 0;
  78749. tmat.m[13] = 0;
  78750. tmat.m[14] = 0;
  78751. tmat.invert();
  78752. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78753. lm.m[12] += tvec.x;
  78754. lm.m[13] += tvec.y;
  78755. lm.m[14] += tvec.z;
  78756. }
  78757. this._markAsDirtyAndDecompose();
  78758. };
  78759. /**
  78760. * Set the postion of the bone in local or world space
  78761. * @param position The position to set the bone
  78762. * @param space The space that the position is in
  78763. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78764. */
  78765. Bone.prototype.setPosition = function (position, space, mesh) {
  78766. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78767. var lm = this.getLocalMatrix();
  78768. if (space == BABYLON.Space.LOCAL) {
  78769. lm.m[12] = position.x;
  78770. lm.m[13] = position.y;
  78771. lm.m[14] = position.z;
  78772. }
  78773. else {
  78774. var wm = null;
  78775. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78776. if (mesh) {
  78777. wm = mesh.getWorldMatrix();
  78778. }
  78779. this._skeleton.computeAbsoluteTransforms();
  78780. var tmat = Bone._tmpMats[0];
  78781. var vec = Bone._tmpVecs[0];
  78782. if (this._parent) {
  78783. if (mesh && wm) {
  78784. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78785. tmat.multiplyToRef(wm, tmat);
  78786. }
  78787. else {
  78788. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78789. }
  78790. }
  78791. tmat.invert();
  78792. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78793. lm.m[12] = vec.x;
  78794. lm.m[13] = vec.y;
  78795. lm.m[14] = vec.z;
  78796. }
  78797. this._markAsDirtyAndDecompose();
  78798. };
  78799. /**
  78800. * Set the absolute position of the bone (world space)
  78801. * @param position The position to set the bone
  78802. * @param mesh The mesh that this bone is attached to
  78803. */
  78804. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78805. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78806. };
  78807. /**
  78808. * Scale the bone on the x, y and z axes (in local space)
  78809. * @param x The amount to scale the bone on the x axis
  78810. * @param y The amount to scale the bone on the y axis
  78811. * @param z The amount to scale the bone on the z axis
  78812. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78813. */
  78814. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78815. if (scaleChildren === void 0) { scaleChildren = false; }
  78816. var locMat = this.getLocalMatrix();
  78817. // Apply new scaling on top of current local matrix
  78818. var scaleMat = Bone._tmpMats[0];
  78819. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78820. scaleMat.multiplyToRef(locMat, locMat);
  78821. // Invert scaling matrix and apply the inverse to all children
  78822. scaleMat.invert();
  78823. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78824. var child = _a[_i];
  78825. var cm = child.getLocalMatrix();
  78826. cm.multiplyToRef(scaleMat, cm);
  78827. cm.m[12] *= x;
  78828. cm.m[13] *= y;
  78829. cm.m[14] *= z;
  78830. child._markAsDirtyAndDecompose();
  78831. }
  78832. this._markAsDirtyAndDecompose();
  78833. if (scaleChildren) {
  78834. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78835. var child = _c[_b];
  78836. child.scale(x, y, z, scaleChildren);
  78837. }
  78838. }
  78839. };
  78840. /**
  78841. * Set the bone scaling in local space
  78842. * @param scale defines the scaling vector
  78843. */
  78844. Bone.prototype.setScale = function (scale) {
  78845. this._decompose();
  78846. this._localScaling.copyFrom(scale);
  78847. this._markAsDirtyAndCompose();
  78848. };
  78849. /**
  78850. * Gets the current scaling in local space
  78851. * @returns the current scaling vector
  78852. */
  78853. Bone.prototype.getScale = function () {
  78854. this._decompose();
  78855. return this._localScaling;
  78856. };
  78857. /**
  78858. * Gets the current scaling in local space and stores it in a target vector
  78859. * @param result defines the target vector
  78860. */
  78861. Bone.prototype.getScaleToRef = function (result) {
  78862. this._decompose();
  78863. result.copyFrom(this._localScaling);
  78864. };
  78865. /**
  78866. * Set the yaw, pitch, and roll of the bone in local or world space
  78867. * @param yaw The rotation of the bone on the y axis
  78868. * @param pitch The rotation of the bone on the x axis
  78869. * @param roll The rotation of the bone on the z axis
  78870. * @param space The space that the axes of rotation are in
  78871. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78872. */
  78873. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78874. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78875. if (space === BABYLON.Space.LOCAL) {
  78876. var quat = Bone._tmpQuat;
  78877. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78878. this.setRotationQuaternion(quat, space, mesh);
  78879. return;
  78880. }
  78881. var rotMatInv = Bone._tmpMats[0];
  78882. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78883. return;
  78884. }
  78885. var rotMat = Bone._tmpMats[1];
  78886. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78887. rotMatInv.multiplyToRef(rotMat, rotMat);
  78888. this._rotateWithMatrix(rotMat, space, mesh);
  78889. };
  78890. /**
  78891. * Add a rotation to the bone on an axis in local or world space
  78892. * @param axis The axis to rotate the bone on
  78893. * @param amount The amount to rotate the bone
  78894. * @param space The space that the axis is in
  78895. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78896. */
  78897. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78898. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78899. var rmat = Bone._tmpMats[0];
  78900. rmat.m[12] = 0;
  78901. rmat.m[13] = 0;
  78902. rmat.m[14] = 0;
  78903. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78904. this._rotateWithMatrix(rmat, space, mesh);
  78905. };
  78906. /**
  78907. * Set the rotation of the bone to a particular axis angle in local or world space
  78908. * @param axis The axis to rotate the bone on
  78909. * @param angle The angle that the bone should be rotated to
  78910. * @param space The space that the axis is in
  78911. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78912. */
  78913. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78914. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78915. if (space === BABYLON.Space.LOCAL) {
  78916. var quat = Bone._tmpQuat;
  78917. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78918. this.setRotationQuaternion(quat, space, mesh);
  78919. return;
  78920. }
  78921. var rotMatInv = Bone._tmpMats[0];
  78922. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78923. return;
  78924. }
  78925. var rotMat = Bone._tmpMats[1];
  78926. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78927. rotMatInv.multiplyToRef(rotMat, rotMat);
  78928. this._rotateWithMatrix(rotMat, space, mesh);
  78929. };
  78930. /**
  78931. * Set the euler rotation of the bone in local of world space
  78932. * @param rotation The euler rotation that the bone should be set to
  78933. * @param space The space that the rotation is in
  78934. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78935. */
  78936. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78937. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78938. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78939. };
  78940. /**
  78941. * Set the quaternion rotation of the bone in local of world space
  78942. * @param quat The quaternion rotation that the bone should be set to
  78943. * @param space The space that the rotation is in
  78944. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78945. */
  78946. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78947. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78948. if (space === BABYLON.Space.LOCAL) {
  78949. this._decompose();
  78950. this._localRotation.copyFrom(quat);
  78951. this._markAsDirtyAndCompose();
  78952. return;
  78953. }
  78954. var rotMatInv = Bone._tmpMats[0];
  78955. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78956. return;
  78957. }
  78958. var rotMat = Bone._tmpMats[1];
  78959. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78960. rotMatInv.multiplyToRef(rotMat, rotMat);
  78961. this._rotateWithMatrix(rotMat, space, mesh);
  78962. };
  78963. /**
  78964. * Set the rotation matrix of the bone in local of world space
  78965. * @param rotMat The rotation matrix that the bone should be set to
  78966. * @param space The space that the rotation is in
  78967. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78968. */
  78969. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78970. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78971. if (space === BABYLON.Space.LOCAL) {
  78972. var quat = Bone._tmpQuat;
  78973. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78974. this.setRotationQuaternion(quat, space, mesh);
  78975. return;
  78976. }
  78977. var rotMatInv = Bone._tmpMats[0];
  78978. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78979. return;
  78980. }
  78981. var rotMat2 = Bone._tmpMats[1];
  78982. rotMat2.copyFrom(rotMat);
  78983. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78984. this._rotateWithMatrix(rotMat2, space, mesh);
  78985. };
  78986. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78987. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78988. var lmat = this.getLocalMatrix();
  78989. var lx = lmat.m[12];
  78990. var ly = lmat.m[13];
  78991. var lz = lmat.m[14];
  78992. var parent = this.getParent();
  78993. var parentScale = Bone._tmpMats[3];
  78994. var parentScaleInv = Bone._tmpMats[4];
  78995. if (parent && space == BABYLON.Space.WORLD) {
  78996. if (mesh) {
  78997. parentScale.copyFrom(mesh.getWorldMatrix());
  78998. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78999. }
  79000. else {
  79001. parentScale.copyFrom(parent.getAbsoluteTransform());
  79002. }
  79003. parentScaleInv.copyFrom(parentScale);
  79004. parentScaleInv.invert();
  79005. lmat.multiplyToRef(parentScale, lmat);
  79006. lmat.multiplyToRef(rmat, lmat);
  79007. lmat.multiplyToRef(parentScaleInv, lmat);
  79008. }
  79009. else {
  79010. if (space == BABYLON.Space.WORLD && mesh) {
  79011. parentScale.copyFrom(mesh.getWorldMatrix());
  79012. parentScaleInv.copyFrom(parentScale);
  79013. parentScaleInv.invert();
  79014. lmat.multiplyToRef(parentScale, lmat);
  79015. lmat.multiplyToRef(rmat, lmat);
  79016. lmat.multiplyToRef(parentScaleInv, lmat);
  79017. }
  79018. else {
  79019. lmat.multiplyToRef(rmat, lmat);
  79020. }
  79021. }
  79022. lmat.m[12] = lx;
  79023. lmat.m[13] = ly;
  79024. lmat.m[14] = lz;
  79025. this.computeAbsoluteTransforms();
  79026. this._markAsDirtyAndDecompose();
  79027. };
  79028. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79029. var scaleMatrix = Bone._tmpMats[2];
  79030. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79031. if (mesh) {
  79032. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79033. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79034. }
  79035. rotMatInv.invert();
  79036. if (isNaN(rotMatInv.m[0])) {
  79037. // Matrix failed to invert.
  79038. // This can happen if scale is zero for example.
  79039. return false;
  79040. }
  79041. scaleMatrix.m[0] *= this._scalingDeterminant;
  79042. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79043. return true;
  79044. };
  79045. /**
  79046. * Get the position of the bone in local or world space
  79047. * @param space The space that the returned position is in
  79048. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79049. * @returns The position of the bone
  79050. */
  79051. Bone.prototype.getPosition = function (space, mesh) {
  79052. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79053. if (mesh === void 0) { mesh = null; }
  79054. var pos = BABYLON.Vector3.Zero();
  79055. this.getPositionToRef(space, mesh, pos);
  79056. return pos;
  79057. };
  79058. /**
  79059. * Copy the position of the bone to a vector3 in local or world space
  79060. * @param space The space that the returned position is in
  79061. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79062. * @param result The vector3 to copy the position to
  79063. */
  79064. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79065. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79066. if (space == BABYLON.Space.LOCAL) {
  79067. var lm = this.getLocalMatrix();
  79068. result.x = lm.m[12];
  79069. result.y = lm.m[13];
  79070. result.z = lm.m[14];
  79071. }
  79072. else {
  79073. var wm = null;
  79074. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79075. if (mesh) {
  79076. wm = mesh.getWorldMatrix();
  79077. }
  79078. this._skeleton.computeAbsoluteTransforms();
  79079. var tmat = Bone._tmpMats[0];
  79080. if (mesh && wm) {
  79081. tmat.copyFrom(this.getAbsoluteTransform());
  79082. tmat.multiplyToRef(wm, tmat);
  79083. }
  79084. else {
  79085. tmat = this.getAbsoluteTransform();
  79086. }
  79087. result.x = tmat.m[12];
  79088. result.y = tmat.m[13];
  79089. result.z = tmat.m[14];
  79090. }
  79091. };
  79092. /**
  79093. * Get the absolute position of the bone (world space)
  79094. * @param mesh The mesh that this bone is attached to
  79095. * @returns The absolute position of the bone
  79096. */
  79097. Bone.prototype.getAbsolutePosition = function (mesh) {
  79098. if (mesh === void 0) { mesh = null; }
  79099. var pos = BABYLON.Vector3.Zero();
  79100. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79101. return pos;
  79102. };
  79103. /**
  79104. * Copy the absolute position of the bone (world space) to the result param
  79105. * @param mesh The mesh that this bone is attached to
  79106. * @param result The vector3 to copy the absolute position to
  79107. */
  79108. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79109. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79110. };
  79111. /**
  79112. * Compute the absolute transforms of this bone and its children
  79113. */
  79114. Bone.prototype.computeAbsoluteTransforms = function () {
  79115. this._compose();
  79116. if (this._parent) {
  79117. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79118. }
  79119. else {
  79120. this._absoluteTransform.copyFrom(this._localMatrix);
  79121. var poseMatrix = this._skeleton.getPoseMatrix();
  79122. if (poseMatrix) {
  79123. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79124. }
  79125. }
  79126. var children = this.children;
  79127. var len = children.length;
  79128. for (var i = 0; i < len; i++) {
  79129. children[i].computeAbsoluteTransforms();
  79130. }
  79131. };
  79132. /**
  79133. * Get the world direction from an axis that is in the local space of the bone
  79134. * @param localAxis The local direction that is used to compute the world direction
  79135. * @param mesh The mesh that this bone is attached to
  79136. * @returns The world direction
  79137. */
  79138. Bone.prototype.getDirection = function (localAxis, mesh) {
  79139. if (mesh === void 0) { mesh = null; }
  79140. var result = BABYLON.Vector3.Zero();
  79141. this.getDirectionToRef(localAxis, mesh, result);
  79142. return result;
  79143. };
  79144. /**
  79145. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79146. * @param localAxis The local direction that is used to compute the world direction
  79147. * @param mesh The mesh that this bone is attached to
  79148. * @param result The vector3 that the world direction will be copied to
  79149. */
  79150. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79151. if (mesh === void 0) { mesh = null; }
  79152. var wm = null;
  79153. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79154. if (mesh) {
  79155. wm = mesh.getWorldMatrix();
  79156. }
  79157. this._skeleton.computeAbsoluteTransforms();
  79158. var mat = Bone._tmpMats[0];
  79159. mat.copyFrom(this.getAbsoluteTransform());
  79160. if (mesh && wm) {
  79161. mat.multiplyToRef(wm, mat);
  79162. }
  79163. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79164. result.normalize();
  79165. };
  79166. /**
  79167. * Get the euler rotation of the bone in local or world space
  79168. * @param space The space that the rotation should be in
  79169. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79170. * @returns The euler rotation
  79171. */
  79172. Bone.prototype.getRotation = function (space, mesh) {
  79173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79174. if (mesh === void 0) { mesh = null; }
  79175. var result = BABYLON.Vector3.Zero();
  79176. this.getRotationToRef(space, mesh, result);
  79177. return result;
  79178. };
  79179. /**
  79180. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79181. * @param space The space that the rotation should be in
  79182. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79183. * @param result The vector3 that the rotation should be copied to
  79184. */
  79185. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79186. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79187. if (mesh === void 0) { mesh = null; }
  79188. var quat = Bone._tmpQuat;
  79189. this.getRotationQuaternionToRef(space, mesh, quat);
  79190. quat.toEulerAnglesToRef(result);
  79191. };
  79192. /**
  79193. * Get the quaternion rotation of the bone in either local or world space
  79194. * @param space The space that the rotation should be in
  79195. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79196. * @returns The quaternion rotation
  79197. */
  79198. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79200. if (mesh === void 0) { mesh = null; }
  79201. var result = BABYLON.Quaternion.Identity();
  79202. this.getRotationQuaternionToRef(space, mesh, result);
  79203. return result;
  79204. };
  79205. /**
  79206. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79207. * @param space The space that the rotation should be in
  79208. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79209. * @param result The quaternion that the rotation should be copied to
  79210. */
  79211. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79212. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79213. if (mesh === void 0) { mesh = null; }
  79214. if (space == BABYLON.Space.LOCAL) {
  79215. this._decompose();
  79216. result.copyFrom(this._localRotation);
  79217. }
  79218. else {
  79219. var mat = Bone._tmpMats[0];
  79220. var amat = this.getAbsoluteTransform();
  79221. if (mesh) {
  79222. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79223. }
  79224. else {
  79225. mat.copyFrom(amat);
  79226. }
  79227. mat.m[0] *= this._scalingDeterminant;
  79228. mat.m[1] *= this._scalingDeterminant;
  79229. mat.m[2] *= this._scalingDeterminant;
  79230. mat.decompose(undefined, result, undefined);
  79231. }
  79232. };
  79233. /**
  79234. * Get the rotation matrix of the bone in local or world space
  79235. * @param space The space that the rotation should be in
  79236. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79237. * @returns The rotation matrix
  79238. */
  79239. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79240. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79241. var result = BABYLON.Matrix.Identity();
  79242. this.getRotationMatrixToRef(space, mesh, result);
  79243. return result;
  79244. };
  79245. /**
  79246. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79247. * @param space The space that the rotation should be in
  79248. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79249. * @param result The quaternion that the rotation should be copied to
  79250. */
  79251. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79252. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79253. if (space == BABYLON.Space.LOCAL) {
  79254. this.getLocalMatrix().getRotationMatrixToRef(result);
  79255. }
  79256. else {
  79257. var mat = Bone._tmpMats[0];
  79258. var amat = this.getAbsoluteTransform();
  79259. if (mesh) {
  79260. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79261. }
  79262. else {
  79263. mat.copyFrom(amat);
  79264. }
  79265. mat.m[0] *= this._scalingDeterminant;
  79266. mat.m[1] *= this._scalingDeterminant;
  79267. mat.m[2] *= this._scalingDeterminant;
  79268. mat.getRotationMatrixToRef(result);
  79269. }
  79270. };
  79271. /**
  79272. * Get the world position of a point that is in the local space of the bone
  79273. * @param position The local position
  79274. * @param mesh The mesh that this bone is attached to
  79275. * @returns The world position
  79276. */
  79277. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79278. if (mesh === void 0) { mesh = null; }
  79279. var result = BABYLON.Vector3.Zero();
  79280. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79281. return result;
  79282. };
  79283. /**
  79284. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79285. * @param position The local position
  79286. * @param mesh The mesh that this bone is attached to
  79287. * @param result The vector3 that the world position should be copied to
  79288. */
  79289. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79290. if (mesh === void 0) { mesh = null; }
  79291. var wm = null;
  79292. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79293. if (mesh) {
  79294. wm = mesh.getWorldMatrix();
  79295. }
  79296. this._skeleton.computeAbsoluteTransforms();
  79297. var tmat = Bone._tmpMats[0];
  79298. if (mesh && wm) {
  79299. tmat.copyFrom(this.getAbsoluteTransform());
  79300. tmat.multiplyToRef(wm, tmat);
  79301. }
  79302. else {
  79303. tmat = this.getAbsoluteTransform();
  79304. }
  79305. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79306. };
  79307. /**
  79308. * Get the local position of a point that is in world space
  79309. * @param position The world position
  79310. * @param mesh The mesh that this bone is attached to
  79311. * @returns The local position
  79312. */
  79313. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79314. if (mesh === void 0) { mesh = null; }
  79315. var result = BABYLON.Vector3.Zero();
  79316. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79317. return result;
  79318. };
  79319. /**
  79320. * Get the local position of a point that is in world space and copy it to the result param
  79321. * @param position The world position
  79322. * @param mesh The mesh that this bone is attached to
  79323. * @param result The vector3 that the local position should be copied to
  79324. */
  79325. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79326. if (mesh === void 0) { mesh = null; }
  79327. var wm = null;
  79328. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79329. if (mesh) {
  79330. wm = mesh.getWorldMatrix();
  79331. }
  79332. this._skeleton.computeAbsoluteTransforms();
  79333. var tmat = Bone._tmpMats[0];
  79334. tmat.copyFrom(this.getAbsoluteTransform());
  79335. if (mesh && wm) {
  79336. tmat.multiplyToRef(wm, tmat);
  79337. }
  79338. tmat.invert();
  79339. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79340. };
  79341. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79342. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79343. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79344. return Bone;
  79345. }(BABYLON.Node));
  79346. BABYLON.Bone = Bone;
  79347. })(BABYLON || (BABYLON = {}));
  79348. //# sourceMappingURL=babylon.bone.js.map
  79349. var BABYLON;
  79350. (function (BABYLON) {
  79351. /**
  79352. * Class used to apply inverse kinematics to bones
  79353. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79354. */
  79355. var BoneIKController = /** @class */ (function () {
  79356. /**
  79357. * Creates a new BoneIKController
  79358. * @param mesh defines the mesh to control
  79359. * @param bone defines the bone to control
  79360. * @param options defines options to set up the controller
  79361. */
  79362. function BoneIKController(mesh, bone, options) {
  79363. /**
  79364. * Gets or sets the target position
  79365. */
  79366. this.targetPosition = BABYLON.Vector3.Zero();
  79367. /**
  79368. * Gets or sets the pole target position
  79369. */
  79370. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79371. /**
  79372. * Gets or sets the pole target local offset
  79373. */
  79374. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79375. /**
  79376. * Gets or sets the pole angle
  79377. */
  79378. this.poleAngle = 0;
  79379. /**
  79380. * 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)
  79381. */
  79382. this.slerpAmount = 1;
  79383. this._bone1Quat = BABYLON.Quaternion.Identity();
  79384. this._bone1Mat = BABYLON.Matrix.Identity();
  79385. this._bone2Ang = Math.PI;
  79386. this._maxAngle = Math.PI;
  79387. this._rightHandedSystem = false;
  79388. this._bendAxis = BABYLON.Vector3.Right();
  79389. this._slerping = false;
  79390. this._adjustRoll = 0;
  79391. this._bone2 = bone;
  79392. this._bone1 = bone.getParent();
  79393. if (!this._bone1) {
  79394. return;
  79395. }
  79396. this.mesh = mesh;
  79397. var bonePos = bone.getPosition();
  79398. if (bone.getAbsoluteTransform().determinant() > 0) {
  79399. this._rightHandedSystem = true;
  79400. this._bendAxis.x = 0;
  79401. this._bendAxis.y = 0;
  79402. this._bendAxis.z = -1;
  79403. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79404. this._adjustRoll = Math.PI * .5;
  79405. this._bendAxis.z = 1;
  79406. }
  79407. }
  79408. if (this._bone1.length) {
  79409. var boneScale1 = this._bone1.getScale();
  79410. var boneScale2 = this._bone2.getScale();
  79411. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79412. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79413. }
  79414. else if (this._bone1.children[0]) {
  79415. mesh.computeWorldMatrix(true);
  79416. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79417. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79418. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79419. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79420. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79421. }
  79422. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79423. this.maxAngle = Math.PI;
  79424. if (options) {
  79425. if (options.targetMesh) {
  79426. this.targetMesh = options.targetMesh;
  79427. this.targetMesh.computeWorldMatrix(true);
  79428. }
  79429. if (options.poleTargetMesh) {
  79430. this.poleTargetMesh = options.poleTargetMesh;
  79431. this.poleTargetMesh.computeWorldMatrix(true);
  79432. }
  79433. else if (options.poleTargetBone) {
  79434. this.poleTargetBone = options.poleTargetBone;
  79435. }
  79436. else if (this._bone1.getParent()) {
  79437. this.poleTargetBone = this._bone1.getParent();
  79438. }
  79439. if (options.poleTargetLocalOffset) {
  79440. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79441. }
  79442. if (options.poleAngle) {
  79443. this.poleAngle = options.poleAngle;
  79444. }
  79445. if (options.bendAxis) {
  79446. this._bendAxis.copyFrom(options.bendAxis);
  79447. }
  79448. if (options.maxAngle) {
  79449. this.maxAngle = options.maxAngle;
  79450. }
  79451. if (options.slerpAmount) {
  79452. this.slerpAmount = options.slerpAmount;
  79453. }
  79454. }
  79455. }
  79456. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79457. /**
  79458. * Gets or sets maximum allowed angle
  79459. */
  79460. get: function () {
  79461. return this._maxAngle;
  79462. },
  79463. set: function (value) {
  79464. this._setMaxAngle(value);
  79465. },
  79466. enumerable: true,
  79467. configurable: true
  79468. });
  79469. BoneIKController.prototype._setMaxAngle = function (ang) {
  79470. if (ang < 0) {
  79471. ang = 0;
  79472. }
  79473. if (ang > Math.PI || ang == undefined) {
  79474. ang = Math.PI;
  79475. }
  79476. this._maxAngle = ang;
  79477. var a = this._bone1Length;
  79478. var b = this._bone2Length;
  79479. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79480. };
  79481. /**
  79482. * Force the controller to update the bones
  79483. */
  79484. BoneIKController.prototype.update = function () {
  79485. var bone1 = this._bone1;
  79486. if (!bone1) {
  79487. return;
  79488. }
  79489. var target = this.targetPosition;
  79490. var poleTarget = this.poleTargetPosition;
  79491. var mat1 = BoneIKController._tmpMats[0];
  79492. var mat2 = BoneIKController._tmpMats[1];
  79493. if (this.targetMesh) {
  79494. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79495. }
  79496. if (this.poleTargetBone) {
  79497. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79498. }
  79499. else if (this.poleTargetMesh) {
  79500. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79501. }
  79502. var bonePos = BoneIKController._tmpVecs[0];
  79503. var zaxis = BoneIKController._tmpVecs[1];
  79504. var xaxis = BoneIKController._tmpVecs[2];
  79505. var yaxis = BoneIKController._tmpVecs[3];
  79506. var upAxis = BoneIKController._tmpVecs[4];
  79507. var _tmpQuat = BoneIKController._tmpQuat;
  79508. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79509. poleTarget.subtractToRef(bonePos, upAxis);
  79510. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79511. upAxis.y = 1;
  79512. }
  79513. else {
  79514. upAxis.normalize();
  79515. }
  79516. target.subtractToRef(bonePos, yaxis);
  79517. yaxis.normalize();
  79518. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79519. zaxis.normalize();
  79520. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79521. xaxis.normalize();
  79522. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79523. var a = this._bone1Length;
  79524. var b = this._bone2Length;
  79525. var c = BABYLON.Vector3.Distance(bonePos, target);
  79526. if (this._maxReach > 0) {
  79527. c = Math.min(this._maxReach, c);
  79528. }
  79529. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79530. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79531. if (acosa > 1) {
  79532. acosa = 1;
  79533. }
  79534. if (acosb > 1) {
  79535. acosb = 1;
  79536. }
  79537. if (acosa < -1) {
  79538. acosa = -1;
  79539. }
  79540. if (acosb < -1) {
  79541. acosb = -1;
  79542. }
  79543. var angA = Math.acos(acosa);
  79544. var angB = Math.acos(acosb);
  79545. var angC = -angA - angB;
  79546. if (this._rightHandedSystem) {
  79547. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79548. mat2.multiplyToRef(mat1, mat1);
  79549. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79550. mat2.multiplyToRef(mat1, mat1);
  79551. }
  79552. else {
  79553. var _tmpVec = BoneIKController._tmpVecs[5];
  79554. _tmpVec.copyFrom(this._bendAxis);
  79555. _tmpVec.x *= -1;
  79556. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79557. mat2.multiplyToRef(mat1, mat1);
  79558. }
  79559. if (this.poleAngle) {
  79560. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79561. mat1.multiplyToRef(mat2, mat1);
  79562. }
  79563. if (this._bone1) {
  79564. if (this.slerpAmount < 1) {
  79565. if (!this._slerping) {
  79566. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79567. }
  79568. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79569. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79570. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79571. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79572. this._slerping = true;
  79573. }
  79574. else {
  79575. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79576. this._bone1Mat.copyFrom(mat1);
  79577. this._slerping = false;
  79578. }
  79579. }
  79580. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79581. this._bone2Ang = angC;
  79582. };
  79583. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79584. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79585. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79586. return BoneIKController;
  79587. }());
  79588. BABYLON.BoneIKController = BoneIKController;
  79589. })(BABYLON || (BABYLON = {}));
  79590. //# sourceMappingURL=babylon.boneIKController.js.map
  79591. var BABYLON;
  79592. (function (BABYLON) {
  79593. /**
  79594. * Class used to make a bone look toward a point in space
  79595. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79596. */
  79597. var BoneLookController = /** @class */ (function () {
  79598. /**
  79599. * Create a BoneLookController
  79600. * @param mesh the mesh that the bone belongs to
  79601. * @param bone the bone that will be looking to the target
  79602. * @param target the target Vector3 to look at
  79603. * @param settings optional settings:
  79604. * * maxYaw: the maximum angle the bone will yaw to
  79605. * * minYaw: the minimum angle the bone will yaw to
  79606. * * maxPitch: the maximum angle the bone will pitch to
  79607. * * minPitch: the minimum angle the bone will yaw to
  79608. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79609. * * upAxis: the up axis of the coordinate system
  79610. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79611. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79612. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79613. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79614. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79615. * * adjustRoll: used to make an adjustment to the roll of the bone
  79616. **/
  79617. function BoneLookController(mesh, bone, target, options) {
  79618. /**
  79619. * The up axis of the coordinate system that is used when the bone is rotated
  79620. */
  79621. this.upAxis = BABYLON.Vector3.Up();
  79622. /**
  79623. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79624. */
  79625. this.upAxisSpace = BABYLON.Space.LOCAL;
  79626. /**
  79627. * Used to make an adjustment to the yaw of the bone
  79628. */
  79629. this.adjustYaw = 0;
  79630. /**
  79631. * Used to make an adjustment to the pitch of the bone
  79632. */
  79633. this.adjustPitch = 0;
  79634. /**
  79635. * Used to make an adjustment to the roll of the bone
  79636. */
  79637. this.adjustRoll = 0;
  79638. /**
  79639. * 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)
  79640. */
  79641. this.slerpAmount = 1;
  79642. this._boneQuat = BABYLON.Quaternion.Identity();
  79643. this._slerping = false;
  79644. this._firstFrameSkipped = false;
  79645. this._fowardAxis = BABYLON.Vector3.Forward();
  79646. this.mesh = mesh;
  79647. this.bone = bone;
  79648. this.target = target;
  79649. if (options) {
  79650. if (options.adjustYaw) {
  79651. this.adjustYaw = options.adjustYaw;
  79652. }
  79653. if (options.adjustPitch) {
  79654. this.adjustPitch = options.adjustPitch;
  79655. }
  79656. if (options.adjustRoll) {
  79657. this.adjustRoll = options.adjustRoll;
  79658. }
  79659. if (options.maxYaw != null) {
  79660. this.maxYaw = options.maxYaw;
  79661. }
  79662. else {
  79663. this.maxYaw = Math.PI;
  79664. }
  79665. if (options.minYaw != null) {
  79666. this.minYaw = options.minYaw;
  79667. }
  79668. else {
  79669. this.minYaw = -Math.PI;
  79670. }
  79671. if (options.maxPitch != null) {
  79672. this.maxPitch = options.maxPitch;
  79673. }
  79674. else {
  79675. this.maxPitch = Math.PI;
  79676. }
  79677. if (options.minPitch != null) {
  79678. this.minPitch = options.minPitch;
  79679. }
  79680. else {
  79681. this.minPitch = -Math.PI;
  79682. }
  79683. if (options.slerpAmount != null) {
  79684. this.slerpAmount = options.slerpAmount;
  79685. }
  79686. if (options.upAxis != null) {
  79687. this.upAxis = options.upAxis;
  79688. }
  79689. if (options.upAxisSpace != null) {
  79690. this.upAxisSpace = options.upAxisSpace;
  79691. }
  79692. if (options.yawAxis != null || options.pitchAxis != null) {
  79693. var newYawAxis = BABYLON.Axis.Y;
  79694. var newPitchAxis = BABYLON.Axis.X;
  79695. if (options.yawAxis != null) {
  79696. newYawAxis = options.yawAxis.clone();
  79697. newYawAxis.normalize();
  79698. }
  79699. if (options.pitchAxis != null) {
  79700. newPitchAxis = options.pitchAxis.clone();
  79701. newPitchAxis.normalize();
  79702. }
  79703. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79704. this._transformYawPitch = BABYLON.Matrix.Identity();
  79705. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79706. this._transformYawPitchInv = this._transformYawPitch.clone();
  79707. this._transformYawPitch.invert();
  79708. }
  79709. }
  79710. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79711. this.upAxisSpace = BABYLON.Space.LOCAL;
  79712. }
  79713. }
  79714. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79715. /**
  79716. * Gets or sets the minimum yaw angle that the bone can look to
  79717. */
  79718. get: function () {
  79719. return this._minYaw;
  79720. },
  79721. set: function (value) {
  79722. this._minYaw = value;
  79723. this._minYawSin = Math.sin(value);
  79724. this._minYawCos = Math.cos(value);
  79725. if (this._maxYaw != null) {
  79726. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79727. this._yawRange = this._maxYaw - this._minYaw;
  79728. }
  79729. },
  79730. enumerable: true,
  79731. configurable: true
  79732. });
  79733. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79734. /**
  79735. * Gets or sets the maximum yaw angle that the bone can look to
  79736. */
  79737. get: function () {
  79738. return this._maxYaw;
  79739. },
  79740. set: function (value) {
  79741. this._maxYaw = value;
  79742. this._maxYawSin = Math.sin(value);
  79743. this._maxYawCos = Math.cos(value);
  79744. if (this._minYaw != null) {
  79745. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79746. this._yawRange = this._maxYaw - this._minYaw;
  79747. }
  79748. },
  79749. enumerable: true,
  79750. configurable: true
  79751. });
  79752. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79753. /**
  79754. * Gets or sets the minimum pitch angle that the bone can look to
  79755. */
  79756. get: function () {
  79757. return this._minPitch;
  79758. },
  79759. set: function (value) {
  79760. this._minPitch = value;
  79761. this._minPitchTan = Math.tan(value);
  79762. },
  79763. enumerable: true,
  79764. configurable: true
  79765. });
  79766. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79767. /**
  79768. * Gets or sets the maximum pitch angle that the bone can look to
  79769. */
  79770. get: function () {
  79771. return this._maxPitch;
  79772. },
  79773. set: function (value) {
  79774. this._maxPitch = value;
  79775. this._maxPitchTan = Math.tan(value);
  79776. },
  79777. enumerable: true,
  79778. configurable: true
  79779. });
  79780. /**
  79781. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79782. */
  79783. BoneLookController.prototype.update = function () {
  79784. //skip the first frame when slerping so that the mesh rotation is correct
  79785. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79786. this._firstFrameSkipped = true;
  79787. return;
  79788. }
  79789. var bone = this.bone;
  79790. var bonePos = BoneLookController._tmpVecs[0];
  79791. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79792. var target = this.target;
  79793. var _tmpMat1 = BoneLookController._tmpMats[0];
  79794. var _tmpMat2 = BoneLookController._tmpMats[1];
  79795. var mesh = this.mesh;
  79796. var parentBone = bone.getParent();
  79797. var upAxis = BoneLookController._tmpVecs[1];
  79798. upAxis.copyFrom(this.upAxis);
  79799. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79800. if (this._transformYawPitch) {
  79801. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79802. }
  79803. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79804. }
  79805. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79806. mesh.getDirectionToRef(upAxis, upAxis);
  79807. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79808. upAxis.normalize();
  79809. }
  79810. }
  79811. var checkYaw = false;
  79812. var checkPitch = false;
  79813. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79814. checkYaw = true;
  79815. }
  79816. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79817. checkPitch = true;
  79818. }
  79819. if (checkYaw || checkPitch) {
  79820. var spaceMat = BoneLookController._tmpMats[2];
  79821. var spaceMatInv = BoneLookController._tmpMats[3];
  79822. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79823. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79824. }
  79825. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79826. spaceMat.copyFrom(mesh.getWorldMatrix());
  79827. }
  79828. else {
  79829. var forwardAxis = BoneLookController._tmpVecs[2];
  79830. forwardAxis.copyFrom(this._fowardAxis);
  79831. if (this._transformYawPitch) {
  79832. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79833. }
  79834. if (parentBone) {
  79835. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79836. }
  79837. else {
  79838. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79839. }
  79840. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79841. rightAxis.normalize();
  79842. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79843. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79844. }
  79845. spaceMat.invertToRef(spaceMatInv);
  79846. var xzlen = null;
  79847. if (checkPitch) {
  79848. var localTarget = BoneLookController._tmpVecs[3];
  79849. target.subtractToRef(bonePos, localTarget);
  79850. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79851. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79852. var pitch = Math.atan2(localTarget.y, xzlen);
  79853. var newPitch = pitch;
  79854. if (pitch > this._maxPitch) {
  79855. localTarget.y = this._maxPitchTan * xzlen;
  79856. newPitch = this._maxPitch;
  79857. }
  79858. else if (pitch < this._minPitch) {
  79859. localTarget.y = this._minPitchTan * xzlen;
  79860. newPitch = this._minPitch;
  79861. }
  79862. if (pitch != newPitch) {
  79863. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79864. localTarget.addInPlace(bonePos);
  79865. target = localTarget;
  79866. }
  79867. }
  79868. if (checkYaw) {
  79869. var localTarget = BoneLookController._tmpVecs[4];
  79870. target.subtractToRef(bonePos, localTarget);
  79871. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79872. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79873. var newYaw = yaw;
  79874. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79875. if (xzlen == null) {
  79876. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79877. }
  79878. if (this._yawRange > Math.PI) {
  79879. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79880. localTarget.z = this._maxYawCos * xzlen;
  79881. localTarget.x = this._maxYawSin * xzlen;
  79882. newYaw = this._maxYaw;
  79883. }
  79884. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79885. localTarget.z = this._minYawCos * xzlen;
  79886. localTarget.x = this._minYawSin * xzlen;
  79887. newYaw = this._minYaw;
  79888. }
  79889. }
  79890. else {
  79891. if (yaw > this._maxYaw) {
  79892. localTarget.z = this._maxYawCos * xzlen;
  79893. localTarget.x = this._maxYawSin * xzlen;
  79894. newYaw = this._maxYaw;
  79895. }
  79896. else if (yaw < this._minYaw) {
  79897. localTarget.z = this._minYawCos * xzlen;
  79898. localTarget.x = this._minYawSin * xzlen;
  79899. newYaw = this._minYaw;
  79900. }
  79901. }
  79902. }
  79903. if (this._slerping && this._yawRange > Math.PI) {
  79904. //are we going to be crossing into the min/max region?
  79905. var boneFwd = BoneLookController._tmpVecs[8];
  79906. boneFwd.copyFrom(BABYLON.Axis.Z);
  79907. if (this._transformYawPitch) {
  79908. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79909. }
  79910. var boneRotMat = BoneLookController._tmpMats[4];
  79911. this._boneQuat.toRotationMatrix(boneRotMat);
  79912. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79913. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79914. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79915. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79916. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79917. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79918. if (angBtwTar > angBtwMidYaw) {
  79919. if (xzlen == null) {
  79920. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79921. }
  79922. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79923. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79924. if (angBtwMin < angBtwMax) {
  79925. newYaw = boneYaw + Math.PI * .75;
  79926. localTarget.z = Math.cos(newYaw) * xzlen;
  79927. localTarget.x = Math.sin(newYaw) * xzlen;
  79928. }
  79929. else {
  79930. newYaw = boneYaw - Math.PI * .75;
  79931. localTarget.z = Math.cos(newYaw) * xzlen;
  79932. localTarget.x = Math.sin(newYaw) * xzlen;
  79933. }
  79934. }
  79935. }
  79936. if (yaw != newYaw) {
  79937. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79938. localTarget.addInPlace(bonePos);
  79939. target = localTarget;
  79940. }
  79941. }
  79942. }
  79943. var zaxis = BoneLookController._tmpVecs[5];
  79944. var xaxis = BoneLookController._tmpVecs[6];
  79945. var yaxis = BoneLookController._tmpVecs[7];
  79946. var _tmpQuat = BoneLookController._tmpQuat;
  79947. target.subtractToRef(bonePos, zaxis);
  79948. zaxis.normalize();
  79949. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79950. xaxis.normalize();
  79951. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79952. yaxis.normalize();
  79953. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79954. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79955. return;
  79956. }
  79957. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79958. return;
  79959. }
  79960. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79961. return;
  79962. }
  79963. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79964. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79965. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79966. }
  79967. if (this.slerpAmount < 1) {
  79968. if (!this._slerping) {
  79969. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79970. }
  79971. if (this._transformYawPitch) {
  79972. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79973. }
  79974. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79975. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79976. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79977. this._slerping = true;
  79978. }
  79979. else {
  79980. if (this._transformYawPitch) {
  79981. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79982. }
  79983. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79984. this._slerping = false;
  79985. }
  79986. };
  79987. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79988. var angDiff = ang2 - ang1;
  79989. angDiff %= Math.PI * 2;
  79990. if (angDiff > Math.PI) {
  79991. angDiff -= Math.PI * 2;
  79992. }
  79993. else if (angDiff < -Math.PI) {
  79994. angDiff += Math.PI * 2;
  79995. }
  79996. return angDiff;
  79997. };
  79998. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79999. ang1 %= (2 * Math.PI);
  80000. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80001. ang2 %= (2 * Math.PI);
  80002. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80003. var ab = 0;
  80004. if (ang1 < ang2) {
  80005. ab = ang2 - ang1;
  80006. }
  80007. else {
  80008. ab = ang1 - ang2;
  80009. }
  80010. if (ab > Math.PI) {
  80011. ab = Math.PI * 2 - ab;
  80012. }
  80013. return ab;
  80014. };
  80015. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80016. ang %= (2 * Math.PI);
  80017. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80018. ang1 %= (2 * Math.PI);
  80019. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80020. ang2 %= (2 * Math.PI);
  80021. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80022. if (ang1 < ang2) {
  80023. if (ang > ang1 && ang < ang2) {
  80024. return true;
  80025. }
  80026. }
  80027. else {
  80028. if (ang > ang2 && ang < ang1) {
  80029. return true;
  80030. }
  80031. }
  80032. return false;
  80033. };
  80034. 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()];
  80035. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80036. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80037. return BoneLookController;
  80038. }());
  80039. BABYLON.BoneLookController = BoneLookController;
  80040. })(BABYLON || (BABYLON = {}));
  80041. //# sourceMappingURL=babylon.boneLookController.js.map
  80042. var BABYLON;
  80043. (function (BABYLON) {
  80044. /**
  80045. * Class used to handle skinning animations
  80046. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80047. */
  80048. var Skeleton = /** @class */ (function () {
  80049. /**
  80050. * Creates a new skeleton
  80051. * @param name defines the skeleton name
  80052. * @param id defines the skeleton Id
  80053. * @param scene defines the hosting scene
  80054. */
  80055. function Skeleton(
  80056. /** defines the skeleton name */
  80057. name,
  80058. /** defines the skeleton Id */
  80059. id, scene) {
  80060. this.name = name;
  80061. this.id = id;
  80062. /**
  80063. * Gets the list of child bones
  80064. */
  80065. this.bones = new Array();
  80066. /**
  80067. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80068. */
  80069. this.needInitialSkinMatrix = false;
  80070. this._isDirty = true;
  80071. this._meshesWithPoseMatrix = new Array();
  80072. this._identity = BABYLON.Matrix.Identity();
  80073. this._ranges = {};
  80074. this._lastAbsoluteTransformsUpdateId = -1;
  80075. /**
  80076. * Specifies if the skeleton should be serialized
  80077. */
  80078. this.doNotSerialize = false;
  80079. this._animationPropertiesOverride = null;
  80080. // Events
  80081. /**
  80082. * An observable triggered before computing the skeleton's matrices
  80083. */
  80084. this.onBeforeComputeObservable = new BABYLON.Observable();
  80085. this.bones = [];
  80086. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80087. scene.skeletons.push(this);
  80088. //make sure it will recalculate the matrix next time prepare is called.
  80089. this._isDirty = true;
  80090. }
  80091. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80092. /**
  80093. * Gets or sets the animation properties override
  80094. */
  80095. get: function () {
  80096. if (!this._animationPropertiesOverride) {
  80097. return this._scene.animationPropertiesOverride;
  80098. }
  80099. return this._animationPropertiesOverride;
  80100. },
  80101. set: function (value) {
  80102. this._animationPropertiesOverride = value;
  80103. },
  80104. enumerable: true,
  80105. configurable: true
  80106. });
  80107. // Members
  80108. /**
  80109. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80110. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80111. * @returns a Float32Array containing matrices data
  80112. */
  80113. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80114. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80115. return mesh._bonesTransformMatrices;
  80116. }
  80117. if (!this._transformMatrices) {
  80118. this.prepare();
  80119. }
  80120. return this._transformMatrices;
  80121. };
  80122. /**
  80123. * Gets the current hosting scene
  80124. * @returns a scene object
  80125. */
  80126. Skeleton.prototype.getScene = function () {
  80127. return this._scene;
  80128. };
  80129. // Methods
  80130. /**
  80131. * Gets a string representing the current skeleton data
  80132. * @param fullDetails defines a boolean indicating if we want a verbose version
  80133. * @returns a string representing the current skeleton data
  80134. */
  80135. Skeleton.prototype.toString = function (fullDetails) {
  80136. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80137. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80138. if (fullDetails) {
  80139. ret += ", Ranges: {";
  80140. var first = true;
  80141. for (var name_1 in this._ranges) {
  80142. if (first) {
  80143. ret += ", ";
  80144. first = false;
  80145. }
  80146. ret += name_1;
  80147. }
  80148. ret += "}";
  80149. }
  80150. return ret;
  80151. };
  80152. /**
  80153. * Get bone's index searching by name
  80154. * @param name defines bone's name to search for
  80155. * @return the indice of the bone. Returns -1 if not found
  80156. */
  80157. Skeleton.prototype.getBoneIndexByName = function (name) {
  80158. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80159. if (this.bones[boneIndex].name === name) {
  80160. return boneIndex;
  80161. }
  80162. }
  80163. return -1;
  80164. };
  80165. /**
  80166. * Creater a new animation range
  80167. * @param name defines the name of the range
  80168. * @param from defines the start key
  80169. * @param to defines the end key
  80170. */
  80171. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80172. // check name not already in use
  80173. if (!this._ranges[name]) {
  80174. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80175. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80176. if (this.bones[i].animations[0]) {
  80177. this.bones[i].animations[0].createRange(name, from, to);
  80178. }
  80179. }
  80180. }
  80181. };
  80182. /**
  80183. * Delete a specific animation range
  80184. * @param name defines the name of the range
  80185. * @param deleteFrames defines if frames must be removed as well
  80186. */
  80187. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80188. if (deleteFrames === void 0) { deleteFrames = true; }
  80189. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80190. if (this.bones[i].animations[0]) {
  80191. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80192. }
  80193. }
  80194. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80195. };
  80196. /**
  80197. * Gets a specific animation range
  80198. * @param name defines the name of the range to look for
  80199. * @returns the requested animation range or null if not found
  80200. */
  80201. Skeleton.prototype.getAnimationRange = function (name) {
  80202. return this._ranges[name];
  80203. };
  80204. /**
  80205. * Gets the list of all animation ranges defined on this skeleton
  80206. * @returns an array
  80207. */
  80208. Skeleton.prototype.getAnimationRanges = function () {
  80209. var animationRanges = [];
  80210. var name;
  80211. var i = 0;
  80212. for (name in this._ranges) {
  80213. animationRanges[i] = this._ranges[name];
  80214. i++;
  80215. }
  80216. return animationRanges;
  80217. };
  80218. /**
  80219. * Copy animation range from a source skeleton.
  80220. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80221. * @param source defines the source skeleton
  80222. * @param name defines the name of the range to copy
  80223. * @param rescaleAsRequired defines if rescaling must be applied if required
  80224. * @returns true if operation was successful
  80225. */
  80226. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80227. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80228. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80229. return false;
  80230. }
  80231. var ret = true;
  80232. var frameOffset = this._getHighestAnimationFrame() + 1;
  80233. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80234. var boneDict = {};
  80235. var sourceBones = source.bones;
  80236. var nBones;
  80237. var i;
  80238. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80239. boneDict[sourceBones[i].name] = sourceBones[i];
  80240. }
  80241. if (this.bones.length !== sourceBones.length) {
  80242. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80243. ret = false;
  80244. }
  80245. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80246. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80247. var boneName = this.bones[i].name;
  80248. var sourceBone = boneDict[boneName];
  80249. if (sourceBone) {
  80250. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80251. }
  80252. else {
  80253. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80254. ret = false;
  80255. }
  80256. }
  80257. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80258. var range = source.getAnimationRange(name);
  80259. if (range) {
  80260. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80261. }
  80262. return ret;
  80263. };
  80264. /**
  80265. * Forces the skeleton to go to rest pose
  80266. */
  80267. Skeleton.prototype.returnToRest = function () {
  80268. for (var index = 0; index < this.bones.length; index++) {
  80269. this.bones[index].returnToRest();
  80270. }
  80271. };
  80272. Skeleton.prototype._getHighestAnimationFrame = function () {
  80273. var ret = 0;
  80274. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80275. if (this.bones[i].animations[0]) {
  80276. var highest = this.bones[i].animations[0].getHighestFrame();
  80277. if (ret < highest) {
  80278. ret = highest;
  80279. }
  80280. }
  80281. }
  80282. return ret;
  80283. };
  80284. /**
  80285. * Begin a specific animation range
  80286. * @param name defines the name of the range to start
  80287. * @param loop defines if looping must be turned on (false by default)
  80288. * @param speedRatio defines the speed ratio to apply (1 by default)
  80289. * @param onAnimationEnd defines a callback which will be called when animation will end
  80290. * @returns a new animatable
  80291. */
  80292. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80293. var range = this.getAnimationRange(name);
  80294. if (!range) {
  80295. return null;
  80296. }
  80297. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80298. };
  80299. /** @hidden */
  80300. Skeleton.prototype._markAsDirty = function () {
  80301. this._isDirty = true;
  80302. };
  80303. /** @hidden */
  80304. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80305. this._meshesWithPoseMatrix.push(mesh);
  80306. };
  80307. /** @hidden */
  80308. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80309. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80310. if (index > -1) {
  80311. this._meshesWithPoseMatrix.splice(index, 1);
  80312. }
  80313. };
  80314. /** @hidden */
  80315. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80316. this.onBeforeComputeObservable.notifyObservers(this);
  80317. for (var index = 0; index < this.bones.length; index++) {
  80318. var bone = this.bones[index];
  80319. var parentBone = bone.getParent();
  80320. if (parentBone) {
  80321. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80322. }
  80323. else {
  80324. if (initialSkinMatrix) {
  80325. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80326. }
  80327. else {
  80328. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80329. }
  80330. }
  80331. if (bone._index !== -1) {
  80332. var mappedIndex = bone._index === null ? index : bone._index;
  80333. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80334. }
  80335. }
  80336. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80337. };
  80338. /**
  80339. * Build all resources required to render a skeleton
  80340. */
  80341. Skeleton.prototype.prepare = function () {
  80342. if (!this._isDirty) {
  80343. return;
  80344. }
  80345. if (this.needInitialSkinMatrix) {
  80346. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80347. var mesh = this._meshesWithPoseMatrix[index];
  80348. var poseMatrix = mesh.getPoseMatrix();
  80349. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80350. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80351. }
  80352. if (this._synchronizedWithMesh !== mesh) {
  80353. this._synchronizedWithMesh = mesh;
  80354. // Prepare bones
  80355. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80356. var bone = this.bones[boneIndex];
  80357. if (!bone.getParent()) {
  80358. var matrix = bone.getBaseMatrix();
  80359. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80360. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80361. }
  80362. }
  80363. }
  80364. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80365. }
  80366. }
  80367. else {
  80368. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80369. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80370. }
  80371. this._computeTransformMatrices(this._transformMatrices, null);
  80372. }
  80373. this._isDirty = false;
  80374. this._scene._activeBones.addCount(this.bones.length, false);
  80375. };
  80376. /**
  80377. * Gets the list of animatables currently running for this skeleton
  80378. * @returns an array of animatables
  80379. */
  80380. Skeleton.prototype.getAnimatables = function () {
  80381. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80382. this._animatables = [];
  80383. for (var index = 0; index < this.bones.length; index++) {
  80384. this._animatables.push(this.bones[index]);
  80385. }
  80386. }
  80387. return this._animatables;
  80388. };
  80389. /**
  80390. * Clone the current skeleton
  80391. * @param name defines the name of the new skeleton
  80392. * @param id defines the id of the enw skeleton
  80393. * @returns the new skeleton
  80394. */
  80395. Skeleton.prototype.clone = function (name, id) {
  80396. var result = new Skeleton(name, id || name, this._scene);
  80397. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80398. for (var index = 0; index < this.bones.length; index++) {
  80399. var source = this.bones[index];
  80400. var parentBone = null;
  80401. var parent_1 = source.getParent();
  80402. if (parent_1) {
  80403. var parentIndex = this.bones.indexOf(parent_1);
  80404. parentBone = result.bones[parentIndex];
  80405. }
  80406. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80407. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80408. }
  80409. if (this._ranges) {
  80410. result._ranges = {};
  80411. for (var rangeName in this._ranges) {
  80412. var range = this._ranges[rangeName];
  80413. if (range) {
  80414. result._ranges[rangeName] = range.clone();
  80415. }
  80416. }
  80417. }
  80418. this._isDirty = true;
  80419. return result;
  80420. };
  80421. /**
  80422. * Enable animation blending for this skeleton
  80423. * @param blendingSpeed defines the blending speed to apply
  80424. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80425. */
  80426. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80427. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80428. this.bones.forEach(function (bone) {
  80429. bone.animations.forEach(function (animation) {
  80430. animation.enableBlending = true;
  80431. animation.blendingSpeed = blendingSpeed;
  80432. });
  80433. });
  80434. };
  80435. /**
  80436. * Releases all resources associated with the current skeleton
  80437. */
  80438. Skeleton.prototype.dispose = function () {
  80439. this._meshesWithPoseMatrix = [];
  80440. // Animations
  80441. this.getScene().stopAnimation(this);
  80442. // Remove from scene
  80443. this.getScene().removeSkeleton(this);
  80444. };
  80445. /**
  80446. * Serialize the skeleton in a JSON object
  80447. * @returns a JSON object
  80448. */
  80449. Skeleton.prototype.serialize = function () {
  80450. var serializationObject = {};
  80451. serializationObject.name = this.name;
  80452. serializationObject.id = this.id;
  80453. if (this.dimensionsAtRest) {
  80454. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80455. }
  80456. serializationObject.bones = [];
  80457. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80458. for (var index = 0; index < this.bones.length; index++) {
  80459. var bone = this.bones[index];
  80460. var parent_2 = bone.getParent();
  80461. var serializedBone = {
  80462. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80463. name: bone.name,
  80464. matrix: bone.getBaseMatrix().toArray(),
  80465. rest: bone.getRestPose().toArray()
  80466. };
  80467. serializationObject.bones.push(serializedBone);
  80468. if (bone.length) {
  80469. serializedBone.length = bone.length;
  80470. }
  80471. if (bone.metadata) {
  80472. serializedBone.metadata = bone.metadata;
  80473. }
  80474. if (bone.animations && bone.animations.length > 0) {
  80475. serializedBone.animation = bone.animations[0].serialize();
  80476. }
  80477. serializationObject.ranges = [];
  80478. for (var name in this._ranges) {
  80479. var source = this._ranges[name];
  80480. if (!source) {
  80481. continue;
  80482. }
  80483. var range = {};
  80484. range.name = name;
  80485. range.from = source.from;
  80486. range.to = source.to;
  80487. serializationObject.ranges.push(range);
  80488. }
  80489. }
  80490. return serializationObject;
  80491. };
  80492. /**
  80493. * Creates a new skeleton from serialized data
  80494. * @param parsedSkeleton defines the serialized data
  80495. * @param scene defines the hosting scene
  80496. * @returns a new skeleton
  80497. */
  80498. Skeleton.Parse = function (parsedSkeleton, scene) {
  80499. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80500. if (parsedSkeleton.dimensionsAtRest) {
  80501. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80502. }
  80503. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80504. var index;
  80505. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80506. var parsedBone = parsedSkeleton.bones[index];
  80507. var parentBone = null;
  80508. if (parsedBone.parentBoneIndex > -1) {
  80509. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80510. }
  80511. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80512. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80513. if (parsedBone.length) {
  80514. bone.length = parsedBone.length;
  80515. }
  80516. if (parsedBone.metadata) {
  80517. bone.metadata = parsedBone.metadata;
  80518. }
  80519. if (parsedBone.animation) {
  80520. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80521. }
  80522. }
  80523. // placed after bones, so createAnimationRange can cascade down
  80524. if (parsedSkeleton.ranges) {
  80525. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80526. var data = parsedSkeleton.ranges[index];
  80527. skeleton.createAnimationRange(data.name, data.from, data.to);
  80528. }
  80529. }
  80530. return skeleton;
  80531. };
  80532. /**
  80533. * Compute all node absolute transforms
  80534. * @param forceUpdate defines if computation must be done even if cache is up to date
  80535. */
  80536. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80537. if (forceUpdate === void 0) { forceUpdate = false; }
  80538. var renderId = this._scene.getRenderId();
  80539. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80540. this.bones[0].computeAbsoluteTransforms();
  80541. this._lastAbsoluteTransformsUpdateId = renderId;
  80542. }
  80543. };
  80544. /**
  80545. * Gets the root pose matrix
  80546. * @returns a matrix
  80547. */
  80548. Skeleton.prototype.getPoseMatrix = function () {
  80549. var poseMatrix = null;
  80550. if (this._meshesWithPoseMatrix.length > 0) {
  80551. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80552. }
  80553. return poseMatrix;
  80554. };
  80555. /**
  80556. * Sorts bones per internal index
  80557. */
  80558. Skeleton.prototype.sortBones = function () {
  80559. var bones = new Array();
  80560. var visited = new Array(this.bones.length);
  80561. for (var index = 0; index < this.bones.length; index++) {
  80562. this._sortBones(index, bones, visited);
  80563. }
  80564. this.bones = bones;
  80565. };
  80566. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80567. if (visited[index]) {
  80568. return;
  80569. }
  80570. visited[index] = true;
  80571. var bone = this.bones[index];
  80572. if (bone._index === undefined) {
  80573. bone._index = index;
  80574. }
  80575. var parentBone = bone.getParent();
  80576. if (parentBone) {
  80577. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80578. }
  80579. bones.push(bone);
  80580. };
  80581. return Skeleton;
  80582. }());
  80583. BABYLON.Skeleton = Skeleton;
  80584. })(BABYLON || (BABYLON = {}));
  80585. //# sourceMappingURL=babylon.skeleton.js.map
  80586. var BABYLON;
  80587. (function (BABYLON) {
  80588. var SphericalPolynomial = /** @class */ (function () {
  80589. function SphericalPolynomial() {
  80590. this.x = BABYLON.Vector3.Zero();
  80591. this.y = BABYLON.Vector3.Zero();
  80592. this.z = BABYLON.Vector3.Zero();
  80593. this.xx = BABYLON.Vector3.Zero();
  80594. this.yy = BABYLON.Vector3.Zero();
  80595. this.zz = BABYLON.Vector3.Zero();
  80596. this.xy = BABYLON.Vector3.Zero();
  80597. this.yz = BABYLON.Vector3.Zero();
  80598. this.zx = BABYLON.Vector3.Zero();
  80599. }
  80600. SphericalPolynomial.prototype.addAmbient = function (color) {
  80601. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80602. this.xx = this.xx.add(colorVector);
  80603. this.yy = this.yy.add(colorVector);
  80604. this.zz = this.zz.add(colorVector);
  80605. };
  80606. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80607. var result = new SphericalPolynomial();
  80608. result.x = harmonics.L11.scale(1.02333);
  80609. result.y = harmonics.L1_1.scale(1.02333);
  80610. result.z = harmonics.L10.scale(1.02333);
  80611. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80612. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80613. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80614. result.yz = harmonics.L2_1.scale(0.858086);
  80615. result.zx = harmonics.L21.scale(0.858086);
  80616. result.xy = harmonics.L2_2.scale(0.858086);
  80617. result.scale(1.0 / Math.PI);
  80618. return result;
  80619. };
  80620. SphericalPolynomial.prototype.scale = function (scale) {
  80621. this.x = this.x.scale(scale);
  80622. this.y = this.y.scale(scale);
  80623. this.z = this.z.scale(scale);
  80624. this.xx = this.xx.scale(scale);
  80625. this.yy = this.yy.scale(scale);
  80626. this.zz = this.zz.scale(scale);
  80627. this.yz = this.yz.scale(scale);
  80628. this.zx = this.zx.scale(scale);
  80629. this.xy = this.xy.scale(scale);
  80630. };
  80631. return SphericalPolynomial;
  80632. }());
  80633. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80634. var SphericalHarmonics = /** @class */ (function () {
  80635. function SphericalHarmonics() {
  80636. this.L00 = BABYLON.Vector3.Zero();
  80637. this.L1_1 = BABYLON.Vector3.Zero();
  80638. this.L10 = BABYLON.Vector3.Zero();
  80639. this.L11 = BABYLON.Vector3.Zero();
  80640. this.L2_2 = BABYLON.Vector3.Zero();
  80641. this.L2_1 = BABYLON.Vector3.Zero();
  80642. this.L20 = BABYLON.Vector3.Zero();
  80643. this.L21 = BABYLON.Vector3.Zero();
  80644. this.L22 = BABYLON.Vector3.Zero();
  80645. }
  80646. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80647. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80648. var c = colorVector.scale(deltaSolidAngle);
  80649. this.L00 = this.L00.add(c.scale(0.282095));
  80650. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80651. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80652. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80653. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80654. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80655. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80656. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80657. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80658. };
  80659. SphericalHarmonics.prototype.scale = function (scale) {
  80660. this.L00 = this.L00.scale(scale);
  80661. this.L1_1 = this.L1_1.scale(scale);
  80662. this.L10 = this.L10.scale(scale);
  80663. this.L11 = this.L11.scale(scale);
  80664. this.L2_2 = this.L2_2.scale(scale);
  80665. this.L2_1 = this.L2_1.scale(scale);
  80666. this.L20 = this.L20.scale(scale);
  80667. this.L21 = this.L21.scale(scale);
  80668. this.L22 = this.L22.scale(scale);
  80669. };
  80670. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80671. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80672. //
  80673. // E_lm = A_l * L_lm
  80674. //
  80675. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80676. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80677. // the scaling factors are given in equation 9.
  80678. // Constant (Band 0)
  80679. this.L00 = this.L00.scale(3.141593);
  80680. // Linear (Band 1)
  80681. this.L1_1 = this.L1_1.scale(2.094395);
  80682. this.L10 = this.L10.scale(2.094395);
  80683. this.L11 = this.L11.scale(2.094395);
  80684. // Quadratic (Band 2)
  80685. this.L2_2 = this.L2_2.scale(0.785398);
  80686. this.L2_1 = this.L2_1.scale(0.785398);
  80687. this.L20 = this.L20.scale(0.785398);
  80688. this.L21 = this.L21.scale(0.785398);
  80689. this.L22 = this.L22.scale(0.785398);
  80690. };
  80691. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80692. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80693. // L = (1/pi) * E * rho
  80694. //
  80695. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80696. this.scale(1.0 / Math.PI);
  80697. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80698. // (The pixel shader must apply albedo after texture fetches, etc).
  80699. };
  80700. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80701. var result = new SphericalHarmonics();
  80702. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80703. result.L1_1 = polynomial.y.scale(0.977204);
  80704. result.L10 = polynomial.z.scale(0.977204);
  80705. result.L11 = polynomial.x.scale(0.977204);
  80706. result.L2_2 = polynomial.xy.scale(1.16538);
  80707. result.L2_1 = polynomial.yz.scale(1.16538);
  80708. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80709. result.L21 = polynomial.zx.scale(1.16538);
  80710. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80711. result.scale(Math.PI);
  80712. return result;
  80713. };
  80714. return SphericalHarmonics;
  80715. }());
  80716. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80717. })(BABYLON || (BABYLON = {}));
  80718. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80719. var BABYLON;
  80720. (function (BABYLON) {
  80721. var FileFaceOrientation = /** @class */ (function () {
  80722. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80723. this.name = name;
  80724. this.worldAxisForNormal = worldAxisForNormal;
  80725. this.worldAxisForFileX = worldAxisForFileX;
  80726. this.worldAxisForFileY = worldAxisForFileY;
  80727. }
  80728. return FileFaceOrientation;
  80729. }());
  80730. ;
  80731. /**
  80732. * Helper class dealing with the extraction of spherical polynomial dataArray
  80733. * from a cube map.
  80734. */
  80735. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80736. function CubeMapToSphericalPolynomialTools() {
  80737. }
  80738. /**
  80739. * Converts a texture to the according Spherical Polynomial data.
  80740. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80741. *
  80742. * @param texture The texture to extract the information from.
  80743. * @return The Spherical Polynomial data.
  80744. */
  80745. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80746. if (!texture.isCube) {
  80747. // Only supports cube Textures currently.
  80748. return null;
  80749. }
  80750. var size = texture.getSize().width;
  80751. var right = texture.readPixels(0);
  80752. var left = texture.readPixels(1);
  80753. var up;
  80754. var down;
  80755. if (texture.isRenderTarget) {
  80756. up = texture.readPixels(3);
  80757. down = texture.readPixels(2);
  80758. }
  80759. else {
  80760. up = texture.readPixels(2);
  80761. down = texture.readPixels(3);
  80762. }
  80763. var front = texture.readPixels(4);
  80764. var back = texture.readPixels(5);
  80765. var gammaSpace = texture.gammaSpace;
  80766. // Always read as RGBA.
  80767. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80768. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80769. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80770. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80771. }
  80772. var cubeInfo = {
  80773. size: size,
  80774. right: right,
  80775. left: left,
  80776. up: up,
  80777. down: down,
  80778. front: front,
  80779. back: back,
  80780. format: format,
  80781. type: type,
  80782. gammaSpace: gammaSpace,
  80783. };
  80784. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80785. };
  80786. /**
  80787. * Converts a cubemap to the according Spherical Polynomial data.
  80788. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80789. *
  80790. * @param cubeInfo The Cube map to extract the information from.
  80791. * @return The Spherical Polynomial data.
  80792. */
  80793. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80794. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80795. var totalSolidAngle = 0.0;
  80796. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80797. var du = 2.0 / cubeInfo.size;
  80798. var dv = du;
  80799. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80800. var minUV = du * 0.5 - 1.0;
  80801. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80802. var fileFace = this.FileFaces[faceIndex];
  80803. var dataArray = cubeInfo[fileFace.name];
  80804. var v = minUV;
  80805. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80806. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80807. // Because SP is still linear, so summation is fine in that basis.
  80808. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80809. for (var y = 0; y < cubeInfo.size; y++) {
  80810. var u = minUV;
  80811. for (var x = 0; x < cubeInfo.size; x++) {
  80812. // World direction (not normalised)
  80813. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80814. worldDirection.normalize();
  80815. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80816. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80817. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80818. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80819. // Handle Integer types.
  80820. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80821. r /= 255;
  80822. g /= 255;
  80823. b /= 255;
  80824. }
  80825. // Handle Gamma space textures.
  80826. if (cubeInfo.gammaSpace) {
  80827. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80828. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80829. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80830. }
  80831. var color = new BABYLON.Color3(r, g, b);
  80832. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80833. totalSolidAngle += deltaSolidAngle;
  80834. u += du;
  80835. }
  80836. v += dv;
  80837. }
  80838. }
  80839. // Solid angle for entire sphere is 4*pi
  80840. var sphereSolidAngle = 4.0 * Math.PI;
  80841. // Adjust the solid angle to allow for how many faces we processed.
  80842. var facesProcessed = 6.0;
  80843. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80844. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80845. // This is needed because the numerical integration over the cube uses a
  80846. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80847. // and also to compensate for accumulative error due to float precision in the summation.
  80848. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80849. sphericalHarmonics.scale(correctionFactor);
  80850. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80851. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80852. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80853. };
  80854. CubeMapToSphericalPolynomialTools.FileFaces = [
  80855. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80856. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80857. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80858. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80859. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80860. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80861. ];
  80862. return CubeMapToSphericalPolynomialTools;
  80863. }());
  80864. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80865. })(BABYLON || (BABYLON = {}));
  80866. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80867. var BABYLON;
  80868. (function (BABYLON) {
  80869. /**
  80870. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80871. */
  80872. var PanoramaToCubeMapTools = /** @class */ (function () {
  80873. function PanoramaToCubeMapTools() {
  80874. }
  80875. /**
  80876. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80877. *
  80878. * @param float32Array The source data.
  80879. * @param inputWidth The width of the input panorama.
  80880. * @param inputhHeight The height of the input panorama.
  80881. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80882. * @return The cubemap data
  80883. */
  80884. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80885. if (!float32Array) {
  80886. throw "ConvertPanoramaToCubemap: input cannot be null";
  80887. }
  80888. if (float32Array.length != inputWidth * inputHeight * 3) {
  80889. throw "ConvertPanoramaToCubemap: input size is wrong";
  80890. }
  80891. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80892. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80893. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80894. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80895. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80896. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80897. return {
  80898. front: textureFront,
  80899. back: textureBack,
  80900. left: textureLeft,
  80901. right: textureRight,
  80902. up: textureUp,
  80903. down: textureDown,
  80904. size: size,
  80905. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80906. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80907. gammaSpace: false,
  80908. };
  80909. };
  80910. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80911. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80912. var textureArray = new Float32Array(buffer);
  80913. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80914. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80915. var dy = 1 / texSize;
  80916. var fy = 0;
  80917. for (var y = 0; y < texSize; y++) {
  80918. var xv1 = faceData[0];
  80919. var xv2 = faceData[2];
  80920. for (var x = 0; x < texSize; x++) {
  80921. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80922. v.normalize();
  80923. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80924. // 3 channels per pixels
  80925. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80926. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80927. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80928. xv1 = xv1.add(rotDX1);
  80929. xv2 = xv2.add(rotDX2);
  80930. }
  80931. fy += dy;
  80932. }
  80933. return textureArray;
  80934. };
  80935. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80936. var theta = Math.atan2(vDir.z, vDir.x);
  80937. var phi = Math.acos(vDir.y);
  80938. while (theta < -Math.PI)
  80939. theta += 2 * Math.PI;
  80940. while (theta > Math.PI)
  80941. theta -= 2 * Math.PI;
  80942. var dx = theta / Math.PI;
  80943. var dy = phi / Math.PI;
  80944. // recenter.
  80945. dx = dx * 0.5 + 0.5;
  80946. var px = Math.round(dx * inputWidth);
  80947. if (px < 0)
  80948. px = 0;
  80949. else if (px >= inputWidth)
  80950. px = inputWidth - 1;
  80951. var py = Math.round(dy * inputHeight);
  80952. if (py < 0)
  80953. py = 0;
  80954. else if (py >= inputHeight)
  80955. py = inputHeight - 1;
  80956. var inputY = (inputHeight - py - 1);
  80957. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80958. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80959. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80960. return {
  80961. r: r,
  80962. g: g,
  80963. b: b
  80964. };
  80965. };
  80966. PanoramaToCubeMapTools.FACE_FRONT = [
  80967. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80968. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80969. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80970. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80971. ];
  80972. PanoramaToCubeMapTools.FACE_BACK = [
  80973. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80974. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80975. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80976. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80977. ];
  80978. PanoramaToCubeMapTools.FACE_RIGHT = [
  80979. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80980. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80981. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80982. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80983. ];
  80984. PanoramaToCubeMapTools.FACE_LEFT = [
  80985. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80986. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80987. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80988. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80989. ];
  80990. PanoramaToCubeMapTools.FACE_DOWN = [
  80991. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80992. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80993. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80994. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80995. ];
  80996. PanoramaToCubeMapTools.FACE_UP = [
  80997. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80998. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80999. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81000. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81001. ];
  81002. return PanoramaToCubeMapTools;
  81003. }());
  81004. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81005. })(BABYLON || (BABYLON = {}));
  81006. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81007. var BABYLON;
  81008. (function (BABYLON) {
  81009. ;
  81010. /**
  81011. * This groups tools to convert HDR texture to native colors array.
  81012. */
  81013. var HDRTools = /** @class */ (function () {
  81014. function HDRTools() {
  81015. }
  81016. HDRTools.Ldexp = function (mantissa, exponent) {
  81017. if (exponent > 1023) {
  81018. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81019. }
  81020. if (exponent < -1074) {
  81021. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81022. }
  81023. return mantissa * Math.pow(2, exponent);
  81024. };
  81025. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81026. if (exponent > 0) { /*nonzero pixel*/
  81027. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81028. float32array[index + 0] = red * exponent;
  81029. float32array[index + 1] = green * exponent;
  81030. float32array[index + 2] = blue * exponent;
  81031. }
  81032. else {
  81033. float32array[index + 0] = 0;
  81034. float32array[index + 1] = 0;
  81035. float32array[index + 2] = 0;
  81036. }
  81037. };
  81038. HDRTools.readStringLine = function (uint8array, startIndex) {
  81039. var line = "";
  81040. var character = "";
  81041. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81042. character = String.fromCharCode(uint8array[i]);
  81043. if (character == "\n") {
  81044. break;
  81045. }
  81046. line += character;
  81047. }
  81048. return line;
  81049. };
  81050. /**
  81051. * Reads header information from an RGBE texture stored in a native array.
  81052. * More information on this format are available here:
  81053. * https://en.wikipedia.org/wiki/RGBE_image_format
  81054. *
  81055. * @param uint8array The binary file stored in native array.
  81056. * @return The header information.
  81057. */
  81058. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81059. var height = 0;
  81060. var width = 0;
  81061. var line = this.readStringLine(uint8array, 0);
  81062. if (line[0] != '#' || line[1] != '?') {
  81063. throw "Bad HDR Format.";
  81064. }
  81065. var endOfHeader = false;
  81066. var findFormat = false;
  81067. var lineIndex = 0;
  81068. do {
  81069. lineIndex += (line.length + 1);
  81070. line = this.readStringLine(uint8array, lineIndex);
  81071. if (line == "FORMAT=32-bit_rle_rgbe") {
  81072. findFormat = true;
  81073. }
  81074. else if (line.length == 0) {
  81075. endOfHeader = true;
  81076. }
  81077. } while (!endOfHeader);
  81078. if (!findFormat) {
  81079. throw "HDR Bad header format, unsupported FORMAT";
  81080. }
  81081. lineIndex += (line.length + 1);
  81082. line = this.readStringLine(uint8array, lineIndex);
  81083. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81084. var match = sizeRegexp.exec(line);
  81085. // TODO. Support +Y and -X if needed.
  81086. if (!match || match.length < 3) {
  81087. throw "HDR Bad header format, no size";
  81088. }
  81089. width = parseInt(match[2]);
  81090. height = parseInt(match[1]);
  81091. if (width < 8 || width > 0x7fff) {
  81092. throw "HDR Bad header format, unsupported size";
  81093. }
  81094. lineIndex += (line.length + 1);
  81095. return {
  81096. height: height,
  81097. width: width,
  81098. dataPosition: lineIndex
  81099. };
  81100. };
  81101. /**
  81102. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81103. * This RGBE texture needs to store the information as a panorama.
  81104. *
  81105. * More information on this format are available here:
  81106. * https://en.wikipedia.org/wiki/RGBE_image_format
  81107. *
  81108. * @param buffer The binary file stored in an array buffer.
  81109. * @param size The expected size of the extracted cubemap.
  81110. * @return The Cube Map information.
  81111. */
  81112. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81113. var uint8array = new Uint8Array(buffer);
  81114. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81115. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81116. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81117. return cubeMapData;
  81118. };
  81119. /**
  81120. * Returns the pixels data extracted from an RGBE texture.
  81121. * This pixels will be stored left to right up to down in the R G B order in one array.
  81122. *
  81123. * More information on this format are available here:
  81124. * https://en.wikipedia.org/wiki/RGBE_image_format
  81125. *
  81126. * @param uint8array The binary file stored in an array buffer.
  81127. * @param hdrInfo The header information of the file.
  81128. * @return The pixels data in RGB right to left up to down order.
  81129. */
  81130. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81131. // Keep for multi format supports.
  81132. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81133. };
  81134. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81135. var num_scanlines = hdrInfo.height;
  81136. var scanline_width = hdrInfo.width;
  81137. var a, b, c, d, count;
  81138. var dataIndex = hdrInfo.dataPosition;
  81139. var index = 0, endIndex = 0, i = 0;
  81140. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81141. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81142. // 3 channels of 4 bytes per pixel in float.
  81143. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81144. var resultArray = new Float32Array(resultBuffer);
  81145. // read in each successive scanline
  81146. while (num_scanlines > 0) {
  81147. a = uint8array[dataIndex++];
  81148. b = uint8array[dataIndex++];
  81149. c = uint8array[dataIndex++];
  81150. d = uint8array[dataIndex++];
  81151. if (a != 2 || b != 2 || (c & 0x80)) {
  81152. // this file is not run length encoded
  81153. throw "HDR Bad header format, not RLE";
  81154. }
  81155. if (((c << 8) | d) != scanline_width) {
  81156. throw "HDR Bad header format, wrong scan line width";
  81157. }
  81158. index = 0;
  81159. // read each of the four channels for the scanline into the buffer
  81160. for (i = 0; i < 4; i++) {
  81161. endIndex = (i + 1) * scanline_width;
  81162. while (index < endIndex) {
  81163. a = uint8array[dataIndex++];
  81164. b = uint8array[dataIndex++];
  81165. if (a > 128) {
  81166. // a run of the same value
  81167. count = a - 128;
  81168. if ((count == 0) || (count > endIndex - index)) {
  81169. throw "HDR Bad Format, bad scanline data (run)";
  81170. }
  81171. while (count-- > 0) {
  81172. scanLineArray[index++] = b;
  81173. }
  81174. }
  81175. else {
  81176. // a non-run
  81177. count = a;
  81178. if ((count == 0) || (count > endIndex - index)) {
  81179. throw "HDR Bad Format, bad scanline data (non-run)";
  81180. }
  81181. scanLineArray[index++] = b;
  81182. if (--count > 0) {
  81183. for (var j = 0; j < count; j++) {
  81184. scanLineArray[index++] = uint8array[dataIndex++];
  81185. }
  81186. }
  81187. }
  81188. }
  81189. }
  81190. // now convert data from buffer into floats
  81191. for (i = 0; i < scanline_width; i++) {
  81192. a = scanLineArray[i];
  81193. b = scanLineArray[i + scanline_width];
  81194. c = scanLineArray[i + 2 * scanline_width];
  81195. d = scanLineArray[i + 3 * scanline_width];
  81196. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81197. }
  81198. num_scanlines--;
  81199. }
  81200. return resultArray;
  81201. };
  81202. return HDRTools;
  81203. }());
  81204. BABYLON.HDRTools = HDRTools;
  81205. })(BABYLON || (BABYLON = {}));
  81206. //# sourceMappingURL=babylon.hdr.js.map
  81207. var BABYLON;
  81208. (function (BABYLON) {
  81209. /**
  81210. * Sets of helpers addressing the serialization and deserialization of environment texture
  81211. * stored in a BabylonJS env file.
  81212. * Those files are usually stored as .env files.
  81213. */
  81214. var EnvironmentTextureTools = /** @class */ (function () {
  81215. function EnvironmentTextureTools() {
  81216. }
  81217. /**
  81218. * Gets the environment info from an env file.
  81219. * @param data The array buffer containing the .env bytes.
  81220. * @returns the environment file info (the json header) if successfully parsed.
  81221. */
  81222. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81223. var dataView = new DataView(data);
  81224. var pos = 0;
  81225. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81226. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81227. BABYLON.Tools.Error('Not a babylon environment map');
  81228. return null;
  81229. }
  81230. }
  81231. // Read json manifest - collect characters up to null terminator
  81232. var manifestString = '';
  81233. var charCode = 0x00;
  81234. while ((charCode = dataView.getUint8(pos++))) {
  81235. manifestString += String.fromCharCode(charCode);
  81236. }
  81237. var manifest = JSON.parse(manifestString);
  81238. if (manifest.specular) {
  81239. // Extend the header with the position of the payload.
  81240. manifest.specular.specularDataPosition = pos;
  81241. }
  81242. return manifest;
  81243. };
  81244. /**
  81245. * Creates an environment texture from a loaded cube texture.
  81246. * @param texture defines the cube texture to convert in env file
  81247. * @return a promise containing the environment data if succesfull.
  81248. */
  81249. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81250. var _this = this;
  81251. var internalTexture = texture.getInternalTexture();
  81252. if (!internalTexture) {
  81253. return Promise.reject("The cube texture is invalid.");
  81254. }
  81255. if (!texture._prefiltered) {
  81256. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81257. }
  81258. var engine = internalTexture.getEngine();
  81259. if (engine && engine.premultipliedAlpha) {
  81260. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81261. }
  81262. var canvas = engine.getRenderingCanvas();
  81263. if (!canvas) {
  81264. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81265. }
  81266. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81267. if (!engine.getCaps().textureFloatRender) {
  81268. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81269. if (!engine.getCaps().textureHalfFloatRender) {
  81270. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81271. }
  81272. }
  81273. var cubeWidth = internalTexture.width;
  81274. var hostingScene = new BABYLON.Scene(engine);
  81275. var specularTextures = {};
  81276. var promises = [];
  81277. // Read and collect all mipmaps data from the cube.
  81278. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81279. mipmapsCount = Math.round(mipmapsCount);
  81280. var _loop_1 = function (i) {
  81281. var faceWidth = Math.pow(2, mipmapsCount - i);
  81282. var _loop_2 = function (face) {
  81283. var data = texture.readPixels(face, i);
  81284. // Creates a temp texture with the face data.
  81285. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81286. // And rgbdEncode them.
  81287. var promise = new Promise(function (resolve, reject) {
  81288. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81289. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81290. rgbdPostProcess.onApply = function (effect) {
  81291. effect._bindTexture("textureSampler", tempTexture);
  81292. };
  81293. // As the process needs to happen on the main canvas, keep track of the current size
  81294. var currentW = engine.getRenderWidth();
  81295. var currentH = engine.getRenderHeight();
  81296. // Set the desired size for the texture
  81297. engine.setSize(faceWidth, faceWidth);
  81298. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81299. // Reading datas from WebGL
  81300. canvas.toBlob(function (blob) {
  81301. var fileReader = new FileReader();
  81302. fileReader.onload = function (event) {
  81303. var arrayBuffer = event.target.result;
  81304. specularTextures[i * 6 + face] = arrayBuffer;
  81305. resolve();
  81306. };
  81307. fileReader.readAsArrayBuffer(blob);
  81308. });
  81309. // Reapply the previous canvas size
  81310. engine.setSize(currentW, currentH);
  81311. });
  81312. });
  81313. promises.push(promise);
  81314. };
  81315. // All faces of the cube.
  81316. for (var face = 0; face < 6; face++) {
  81317. _loop_2(face);
  81318. }
  81319. };
  81320. for (var i = 0; i <= mipmapsCount; i++) {
  81321. _loop_1(i);
  81322. }
  81323. // Once all the textures haves been collected as RGBD stored in PNGs
  81324. return Promise.all(promises).then(function () {
  81325. // We can delete the hosting scene keeping track of all the creation objects
  81326. hostingScene.dispose();
  81327. // Creates the json header for the env texture
  81328. var info = {
  81329. version: 1,
  81330. width: cubeWidth,
  81331. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81332. specular: {
  81333. mipmaps: []
  81334. }
  81335. };
  81336. // Sets the specular image data information
  81337. var position = 0;
  81338. for (var i = 0; i <= mipmapsCount; i++) {
  81339. for (var face = 0; face < 6; face++) {
  81340. var byteLength = specularTextures[i * 6 + face].byteLength;
  81341. info.specular.mipmaps.push({
  81342. length: byteLength,
  81343. position: position
  81344. });
  81345. position += byteLength;
  81346. }
  81347. }
  81348. // Encode the JSON as an array buffer
  81349. var infoString = JSON.stringify(info);
  81350. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81351. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81352. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81353. infoView[i] = infoString.charCodeAt(i);
  81354. }
  81355. // Ends up with a null terminator for easier parsing
  81356. infoView[infoString.length] = 0x00;
  81357. // Computes the final required size and creates the storage
  81358. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81359. var finalBuffer = new ArrayBuffer(totalSize);
  81360. var finalBufferView = new Uint8Array(finalBuffer);
  81361. var dataView = new DataView(finalBuffer);
  81362. // Copy the magic bytes identifying the file in
  81363. var pos = 0;
  81364. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81365. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81366. }
  81367. // Add the json info
  81368. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81369. pos += infoBuffer.byteLength;
  81370. // Finally inserts the texture data
  81371. for (var i = 0; i <= mipmapsCount; i++) {
  81372. for (var face = 0; face < 6; face++) {
  81373. var dataBuffer = specularTextures[i * 6 + face];
  81374. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81375. pos += dataBuffer.byteLength;
  81376. }
  81377. }
  81378. // Voila
  81379. return finalBuffer;
  81380. });
  81381. };
  81382. /**
  81383. * Creates a JSON representation of the spherical data.
  81384. * @param texture defines the texture containing the polynomials
  81385. * @return the JSON representation of the spherical info
  81386. */
  81387. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81388. var polynmials = texture.sphericalPolynomial;
  81389. if (polynmials == null) {
  81390. return null;
  81391. }
  81392. return {
  81393. polynomials: true,
  81394. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81395. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81396. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81397. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81398. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81399. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81400. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81401. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81402. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81403. };
  81404. };
  81405. /**
  81406. * Uploads the texture info contained in the env file to te GPU.
  81407. * @param texture defines the internal texture to upload to
  81408. * @param arrayBuffer defines the buffer cotaining the data to load
  81409. * @param info defines the texture info retrieved through the GetEnvInfo method
  81410. * @returns a promise
  81411. */
  81412. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81413. if (info.version !== 1) {
  81414. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81415. }
  81416. var specularInfo = info.specular;
  81417. if (!specularInfo) {
  81418. // Nothing else parsed so far
  81419. return Promise.resolve();
  81420. }
  81421. // Double checks the enclosed info
  81422. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81423. mipmapsCount = Math.round(mipmapsCount) + 1;
  81424. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81425. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81426. }
  81427. // Gets everything ready.
  81428. var engine = texture.getEngine();
  81429. var expandTexture = false;
  81430. var generateNonLODTextures = false;
  81431. var rgbdPostProcess = null;
  81432. var cubeRtt = null;
  81433. var lodTextures = null;
  81434. var caps = engine.getCaps();
  81435. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81436. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81437. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81438. // Add extra process if texture lod is not supported
  81439. if (!caps.textureLOD) {
  81440. expandTexture = false;
  81441. generateNonLODTextures = true;
  81442. lodTextures = {};
  81443. }
  81444. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81445. else if (engine.webGLVersion < 2) {
  81446. expandTexture = false;
  81447. }
  81448. // If half float available we can uncompress the texture
  81449. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81450. expandTexture = true;
  81451. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81452. }
  81453. // If full float available we can uncompress the texture
  81454. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81455. expandTexture = true;
  81456. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81457. }
  81458. // Expand the texture if possible
  81459. if (expandTexture) {
  81460. // Simply run through the decode PP
  81461. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81462. texture._isRGBD = false;
  81463. texture.invertY = false;
  81464. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81465. generateDepthBuffer: false,
  81466. generateMipMaps: true,
  81467. generateStencilBuffer: false,
  81468. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81469. type: texture.type,
  81470. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81471. });
  81472. }
  81473. else {
  81474. texture._isRGBD = true;
  81475. texture.invertY = true;
  81476. // In case of missing support, applies the same patch than DDS files.
  81477. if (generateNonLODTextures) {
  81478. var mipSlices = 3;
  81479. var scale = texture._lodGenerationScale;
  81480. var offset = texture._lodGenerationOffset;
  81481. for (var i = 0; i < mipSlices; i++) {
  81482. //compute LOD from even spacing in smoothness (matching shader calculation)
  81483. var smoothness = i / (mipSlices - 1);
  81484. var roughness = 1 - smoothness;
  81485. var minLODIndex = offset; // roughness = 0
  81486. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81487. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81488. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81489. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81490. glTextureFromLod.isCube = true;
  81491. glTextureFromLod.invertY = true;
  81492. glTextureFromLod.generateMipMaps = false;
  81493. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81494. // Wrap in a base texture for easy binding.
  81495. var lodTexture = new BABYLON.BaseTexture(null);
  81496. lodTexture.isCube = true;
  81497. lodTexture._texture = glTextureFromLod;
  81498. lodTextures[mipmapIndex] = lodTexture;
  81499. switch (i) {
  81500. case 0:
  81501. texture._lodTextureLow = lodTexture;
  81502. break;
  81503. case 1:
  81504. texture._lodTextureMid = lodTexture;
  81505. break;
  81506. case 2:
  81507. texture._lodTextureHigh = lodTexture;
  81508. break;
  81509. }
  81510. }
  81511. }
  81512. }
  81513. var promises = [];
  81514. var _loop_3 = function (i) {
  81515. var _loop_4 = function (face) {
  81516. // Retrieves the face data
  81517. var imageData = specularInfo.mipmaps[i * 6 + face];
  81518. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81519. // Constructs an image element from bytes
  81520. var blob = new Blob([bytes], { type: 'image/png' });
  81521. var url = URL.createObjectURL(blob);
  81522. var image = new Image();
  81523. image.src = url;
  81524. // Enqueue promise to upload to the texture.
  81525. var promise = new Promise(function (resolve, reject) {
  81526. ;
  81527. image.onload = function () {
  81528. if (expandTexture) {
  81529. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81530. reject(message);
  81531. }, image);
  81532. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81533. // Uncompress the data to a RTT
  81534. rgbdPostProcess.onApply = function (effect) {
  81535. effect._bindTexture("textureSampler", tempTexture_1);
  81536. effect.setFloat2("scale", 1, 1);
  81537. };
  81538. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81539. // Cleanup
  81540. engine.restoreDefaultFramebuffer();
  81541. tempTexture_1.dispose();
  81542. window.URL.revokeObjectURL(url);
  81543. resolve();
  81544. });
  81545. }
  81546. else {
  81547. engine._uploadImageToTexture(texture, face, i, image);
  81548. // Upload the face to the none lod texture support
  81549. if (generateNonLODTextures) {
  81550. var lodTexture = lodTextures[i];
  81551. if (lodTexture) {
  81552. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81553. }
  81554. }
  81555. resolve();
  81556. }
  81557. };
  81558. image.onerror = function (error) {
  81559. reject(error);
  81560. };
  81561. });
  81562. promises.push(promise);
  81563. };
  81564. // All faces
  81565. for (var face = 0; face < 6; face++) {
  81566. _loop_4(face);
  81567. }
  81568. };
  81569. // All mipmaps
  81570. for (var i = 0; i < mipmapsCount; i++) {
  81571. _loop_3(i);
  81572. }
  81573. // Once all done, finishes the cleanup and return
  81574. return Promise.all(promises).then(function () {
  81575. // Relase temp RTT.
  81576. if (cubeRtt) {
  81577. engine._releaseFramebufferObjects(cubeRtt);
  81578. cubeRtt._swapAndDie(texture);
  81579. }
  81580. // Relase temp Post Process.
  81581. if (rgbdPostProcess) {
  81582. rgbdPostProcess.dispose();
  81583. }
  81584. // Flag internal texture as ready in case they are in use.
  81585. if (generateNonLODTextures) {
  81586. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81587. texture._lodTextureHigh._texture.isReady = true;
  81588. }
  81589. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81590. texture._lodTextureMid._texture.isReady = true;
  81591. }
  81592. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81593. texture._lodTextureLow._texture.isReady = true;
  81594. }
  81595. }
  81596. });
  81597. };
  81598. /**
  81599. * Uploads spherical polynomials information to the texture.
  81600. * @param texture defines the texture we are trying to upload the information to
  81601. * @param arrayBuffer defines the array buffer holding the data
  81602. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81603. */
  81604. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81605. if (info.version !== 1) {
  81606. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81607. }
  81608. var irradianceInfo = info.irradiance;
  81609. if (!irradianceInfo) {
  81610. return;
  81611. }
  81612. //harmonics now represent radiance
  81613. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81614. if (irradianceInfo.polynomials) {
  81615. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81616. }
  81617. else {
  81618. // convert From SH to SP.
  81619. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81620. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81621. }
  81622. };
  81623. /**
  81624. * Upload spherical polynomial coefficients to the texture
  81625. * @param polynmials Spherical polynmial coefficients (9)
  81626. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81627. */
  81628. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81629. outPolynomialCoefficents.x.x = polynmials.x[0];
  81630. outPolynomialCoefficents.x.y = polynmials.x[1];
  81631. outPolynomialCoefficents.x.z = polynmials.x[2];
  81632. outPolynomialCoefficents.y.x = polynmials.y[0];
  81633. outPolynomialCoefficents.y.y = polynmials.y[1];
  81634. outPolynomialCoefficents.y.z = polynmials.y[2];
  81635. outPolynomialCoefficents.z.x = polynmials.z[0];
  81636. outPolynomialCoefficents.z.y = polynmials.z[1];
  81637. outPolynomialCoefficents.z.z = polynmials.z[2];
  81638. //xx
  81639. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81640. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81641. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81642. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81643. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81644. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81645. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81646. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81647. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81648. //yz
  81649. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81650. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81651. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81652. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81653. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81654. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81655. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81656. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81657. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81658. };
  81659. /**
  81660. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81661. * L = (1/pi) * E * rho
  81662. *
  81663. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81664. * @param harmonics Spherical harmonic coefficients (9)
  81665. */
  81666. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81667. var scaleFactor = 1 / Math.PI;
  81668. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81669. // (The pixel shader must apply albedo after texture fetches, etc).
  81670. harmonics.l00[0] *= scaleFactor;
  81671. harmonics.l00[1] *= scaleFactor;
  81672. harmonics.l00[2] *= scaleFactor;
  81673. harmonics.l1_1[0] *= scaleFactor;
  81674. harmonics.l1_1[1] *= scaleFactor;
  81675. harmonics.l1_1[2] *= scaleFactor;
  81676. harmonics.l10[0] *= scaleFactor;
  81677. harmonics.l10[1] *= scaleFactor;
  81678. harmonics.l10[2] *= scaleFactor;
  81679. harmonics.l11[0] *= scaleFactor;
  81680. harmonics.l11[1] *= scaleFactor;
  81681. harmonics.l11[2] *= scaleFactor;
  81682. harmonics.l2_2[0] *= scaleFactor;
  81683. harmonics.l2_2[1] *= scaleFactor;
  81684. harmonics.l2_2[2] *= scaleFactor;
  81685. harmonics.l2_1[0] *= scaleFactor;
  81686. harmonics.l2_1[1] *= scaleFactor;
  81687. harmonics.l2_1[2] *= scaleFactor;
  81688. harmonics.l20[0] *= scaleFactor;
  81689. harmonics.l20[1] *= scaleFactor;
  81690. harmonics.l20[2] *= scaleFactor;
  81691. harmonics.l21[0] *= scaleFactor;
  81692. harmonics.l21[1] *= scaleFactor;
  81693. harmonics.l21[2] *= scaleFactor;
  81694. harmonics.l22[0] *= scaleFactor;
  81695. harmonics.l22[1] *= scaleFactor;
  81696. harmonics.l22[2] *= scaleFactor;
  81697. };
  81698. /**
  81699. * Convert spherical harmonics to spherical polynomial coefficients
  81700. * @param harmonics Spherical harmonic coefficients (9)
  81701. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81702. */
  81703. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81704. var rPi = 1 / Math.PI;
  81705. //x
  81706. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81707. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81708. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81709. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81710. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81711. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81712. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81713. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81714. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81715. //xx
  81716. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81717. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81718. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81719. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81720. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81721. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81722. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81723. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81724. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81725. //yz
  81726. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81727. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81728. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81729. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81730. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81731. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81732. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81733. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81734. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81735. };
  81736. /**
  81737. * Magic number identifying the env file.
  81738. */
  81739. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81740. return EnvironmentTextureTools;
  81741. }());
  81742. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81743. })(BABYLON || (BABYLON = {}));
  81744. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81745. var BABYLON;
  81746. (function (BABYLON) {
  81747. /**
  81748. * This represents a texture coming from an HDR input.
  81749. *
  81750. * The only supported format is currently panorama picture stored in RGBE format.
  81751. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81752. */
  81753. var HDRCubeTexture = /** @class */ (function (_super) {
  81754. __extends(HDRCubeTexture, _super);
  81755. /**
  81756. * Instantiates an HDRTexture from the following parameters.
  81757. *
  81758. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81759. * @param scene The scene the texture will be used in
  81760. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81761. * @param noMipmap Forces to not generate the mipmap if true
  81762. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81763. * @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)
  81764. * @param reserved Reserved flag for internal use.
  81765. */
  81766. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81767. if (noMipmap === void 0) { noMipmap = false; }
  81768. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81769. if (gammaSpace === void 0) { gammaSpace = false; }
  81770. if (reserved === void 0) { reserved = false; }
  81771. if (onLoad === void 0) { onLoad = null; }
  81772. if (onError === void 0) { onError = null; }
  81773. var _this = _super.call(this, scene) || this;
  81774. _this._generateHarmonics = true;
  81775. _this._onLoad = null;
  81776. _this._onError = null;
  81777. /**
  81778. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81779. */
  81780. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81781. _this._isBlocking = true;
  81782. _this._rotationY = 0;
  81783. /**
  81784. * Gets or sets the center of the bounding box associated with the cube texture
  81785. * It must define where the camera used to render the texture was set
  81786. */
  81787. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81788. if (!url) {
  81789. return _this;
  81790. }
  81791. _this.name = url;
  81792. _this.url = url;
  81793. _this.hasAlpha = false;
  81794. _this.isCube = true;
  81795. _this._textureMatrix = BABYLON.Matrix.Identity();
  81796. _this._onLoad = onLoad;
  81797. _this._onError = onError;
  81798. _this.gammaSpace = gammaSpace;
  81799. _this._noMipmap = noMipmap;
  81800. _this._size = size;
  81801. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81802. if (!_this._texture) {
  81803. if (!scene.useDelayedTextureLoading) {
  81804. _this.loadTexture();
  81805. }
  81806. else {
  81807. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81808. }
  81809. }
  81810. return _this;
  81811. }
  81812. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81813. /**
  81814. * Gets wether or not the texture is blocking during loading.
  81815. */
  81816. get: function () {
  81817. return this._isBlocking;
  81818. },
  81819. /**
  81820. * Sets wether or not the texture is blocking during loading.
  81821. */
  81822. set: function (value) {
  81823. this._isBlocking = value;
  81824. },
  81825. enumerable: true,
  81826. configurable: true
  81827. });
  81828. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81829. /**
  81830. * Gets texture matrix rotation angle around Y axis radians.
  81831. */
  81832. get: function () {
  81833. return this._rotationY;
  81834. },
  81835. /**
  81836. * Sets texture matrix rotation angle around Y axis in radians.
  81837. */
  81838. set: function (value) {
  81839. this._rotationY = value;
  81840. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81841. },
  81842. enumerable: true,
  81843. configurable: true
  81844. });
  81845. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81846. get: function () {
  81847. return this._boundingBoxSize;
  81848. },
  81849. /**
  81850. * Gets or sets the size of the bounding box associated with the cube texture
  81851. * When defined, the cubemap will switch to local mode
  81852. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81853. * @example https://www.babylonjs-playground.com/#RNASML
  81854. */
  81855. set: function (value) {
  81856. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81857. return;
  81858. }
  81859. this._boundingBoxSize = value;
  81860. var scene = this.getScene();
  81861. if (scene) {
  81862. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81863. }
  81864. },
  81865. enumerable: true,
  81866. configurable: true
  81867. });
  81868. /**
  81869. * Occurs when the file is raw .hdr file.
  81870. */
  81871. HDRCubeTexture.prototype.loadTexture = function () {
  81872. var _this = this;
  81873. var callback = function (buffer) {
  81874. _this.lodGenerationOffset = 0.0;
  81875. _this.lodGenerationScale = 0.8;
  81876. var scene = _this.getScene();
  81877. if (!scene) {
  81878. return null;
  81879. }
  81880. // Extract the raw linear data.
  81881. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81882. // Generate harmonics if needed.
  81883. if (_this._generateHarmonics) {
  81884. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81885. _this.sphericalPolynomial = sphericalPolynomial;
  81886. }
  81887. var results = [];
  81888. var byteArray = null;
  81889. // Push each faces.
  81890. for (var j = 0; j < 6; j++) {
  81891. // Create uintarray fallback.
  81892. if (!scene.getEngine().getCaps().textureFloat) {
  81893. // 3 channels of 1 bytes per pixel in bytes.
  81894. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81895. byteArray = new Uint8Array(byteBuffer);
  81896. }
  81897. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81898. // If special cases.
  81899. if (_this.gammaSpace || byteArray) {
  81900. for (var i = 0; i < _this._size * _this._size; i++) {
  81901. // Put in gamma space if requested.
  81902. if (_this.gammaSpace) {
  81903. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81904. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81905. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81906. }
  81907. // Convert to int texture for fallback.
  81908. if (byteArray) {
  81909. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81910. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81911. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81912. // May use luminance instead if the result is not accurate.
  81913. var max = Math.max(Math.max(r, g), b);
  81914. if (max > 255) {
  81915. var scale = 255 / max;
  81916. r *= scale;
  81917. g *= scale;
  81918. b *= scale;
  81919. }
  81920. byteArray[(i * 3) + 0] = r;
  81921. byteArray[(i * 3) + 1] = g;
  81922. byteArray[(i * 3) + 2] = b;
  81923. }
  81924. }
  81925. }
  81926. if (byteArray) {
  81927. results.push(byteArray);
  81928. }
  81929. else {
  81930. results.push(dataFace);
  81931. }
  81932. }
  81933. return results;
  81934. };
  81935. var scene = this.getScene();
  81936. if (scene) {
  81937. 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);
  81938. }
  81939. };
  81940. HDRCubeTexture.prototype.clone = function () {
  81941. var scene = this.getScene();
  81942. if (!scene) {
  81943. return this;
  81944. }
  81945. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81946. // Base texture
  81947. newTexture.level = this.level;
  81948. newTexture.wrapU = this.wrapU;
  81949. newTexture.wrapV = this.wrapV;
  81950. newTexture.coordinatesIndex = this.coordinatesIndex;
  81951. newTexture.coordinatesMode = this.coordinatesMode;
  81952. return newTexture;
  81953. };
  81954. // Methods
  81955. HDRCubeTexture.prototype.delayLoad = function () {
  81956. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81957. return;
  81958. }
  81959. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81960. this._texture = this._getFromCache(this.url, this._noMipmap);
  81961. if (!this._texture) {
  81962. this.loadTexture();
  81963. }
  81964. };
  81965. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81966. return this._textureMatrix;
  81967. };
  81968. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81969. this._textureMatrix = value;
  81970. };
  81971. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81972. var texture = null;
  81973. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81974. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81975. texture.name = parsedTexture.name;
  81976. texture.hasAlpha = parsedTexture.hasAlpha;
  81977. texture.level = parsedTexture.level;
  81978. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81979. texture.isBlocking = parsedTexture.isBlocking;
  81980. }
  81981. if (texture) {
  81982. if (parsedTexture.boundingBoxPosition) {
  81983. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81984. }
  81985. if (parsedTexture.boundingBoxSize) {
  81986. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81987. }
  81988. if (parsedTexture.rotationY) {
  81989. texture.rotationY = parsedTexture.rotationY;
  81990. }
  81991. }
  81992. return texture;
  81993. };
  81994. HDRCubeTexture.prototype.serialize = function () {
  81995. if (!this.name) {
  81996. return null;
  81997. }
  81998. var serializationObject = {};
  81999. serializationObject.name = this.name;
  82000. serializationObject.hasAlpha = this.hasAlpha;
  82001. serializationObject.isCube = true;
  82002. serializationObject.level = this.level;
  82003. serializationObject.size = this._size;
  82004. serializationObject.coordinatesMode = this.coordinatesMode;
  82005. serializationObject.useInGammaSpace = this.gammaSpace;
  82006. serializationObject.generateHarmonics = this._generateHarmonics;
  82007. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82008. serializationObject.noMipmap = this._noMipmap;
  82009. serializationObject.isBlocking = this._isBlocking;
  82010. serializationObject.rotationY = this._rotationY;
  82011. return serializationObject;
  82012. };
  82013. HDRCubeTexture._facesMapping = [
  82014. "right",
  82015. "left",
  82016. "up",
  82017. "down",
  82018. "front",
  82019. "back"
  82020. ];
  82021. return HDRCubeTexture;
  82022. }(BABYLON.BaseTexture));
  82023. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82024. })(BABYLON || (BABYLON = {}));
  82025. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82026. var BABYLON;
  82027. (function (BABYLON) {
  82028. var IndexedVector2 = /** @class */ (function (_super) {
  82029. __extends(IndexedVector2, _super);
  82030. function IndexedVector2(original, index) {
  82031. var _this = _super.call(this, original.x, original.y) || this;
  82032. _this.index = index;
  82033. return _this;
  82034. }
  82035. return IndexedVector2;
  82036. }(BABYLON.Vector2));
  82037. var PolygonPoints = /** @class */ (function () {
  82038. function PolygonPoints() {
  82039. this.elements = new Array();
  82040. }
  82041. PolygonPoints.prototype.add = function (originalPoints) {
  82042. var _this = this;
  82043. var result = new Array();
  82044. originalPoints.forEach(function (point) {
  82045. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82046. var newPoint = new IndexedVector2(point, _this.elements.length);
  82047. result.push(newPoint);
  82048. _this.elements.push(newPoint);
  82049. }
  82050. });
  82051. return result;
  82052. };
  82053. PolygonPoints.prototype.computeBounds = function () {
  82054. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82055. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82056. this.elements.forEach(function (point) {
  82057. // x
  82058. if (point.x < lmin.x) {
  82059. lmin.x = point.x;
  82060. }
  82061. else if (point.x > lmax.x) {
  82062. lmax.x = point.x;
  82063. }
  82064. // y
  82065. if (point.y < lmin.y) {
  82066. lmin.y = point.y;
  82067. }
  82068. else if (point.y > lmax.y) {
  82069. lmax.y = point.y;
  82070. }
  82071. });
  82072. return {
  82073. min: lmin,
  82074. max: lmax,
  82075. width: lmax.x - lmin.x,
  82076. height: lmax.y - lmin.y
  82077. };
  82078. };
  82079. return PolygonPoints;
  82080. }());
  82081. var Polygon = /** @class */ (function () {
  82082. function Polygon() {
  82083. }
  82084. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82085. return [
  82086. new BABYLON.Vector2(xmin, ymin),
  82087. new BABYLON.Vector2(xmax, ymin),
  82088. new BABYLON.Vector2(xmax, ymax),
  82089. new BABYLON.Vector2(xmin, ymax)
  82090. ];
  82091. };
  82092. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82093. if (cx === void 0) { cx = 0; }
  82094. if (cy === void 0) { cy = 0; }
  82095. if (numberOfSides === void 0) { numberOfSides = 32; }
  82096. var result = new Array();
  82097. var angle = 0;
  82098. var increment = (Math.PI * 2) / numberOfSides;
  82099. for (var i = 0; i < numberOfSides; i++) {
  82100. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82101. angle -= increment;
  82102. }
  82103. return result;
  82104. };
  82105. Polygon.Parse = function (input) {
  82106. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82107. var i, result = [];
  82108. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82109. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82110. }
  82111. return result;
  82112. };
  82113. Polygon.StartingAt = function (x, y) {
  82114. return BABYLON.Path2.StartingAt(x, y);
  82115. };
  82116. return Polygon;
  82117. }());
  82118. BABYLON.Polygon = Polygon;
  82119. var PolygonMeshBuilder = /** @class */ (function () {
  82120. function PolygonMeshBuilder(name, contours, scene) {
  82121. this._points = new PolygonPoints();
  82122. this._outlinepoints = new PolygonPoints();
  82123. this._holes = new Array();
  82124. this._epoints = new Array();
  82125. this._eholes = new Array();
  82126. this._name = name;
  82127. this._scene = scene;
  82128. var points;
  82129. if (contours instanceof BABYLON.Path2) {
  82130. points = contours.getPoints();
  82131. }
  82132. else {
  82133. points = contours;
  82134. }
  82135. this._addToepoint(points);
  82136. this._points.add(points);
  82137. this._outlinepoints.add(points);
  82138. if (typeof earcut === 'undefined') {
  82139. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82140. }
  82141. }
  82142. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82143. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82144. var p = points_1[_i];
  82145. this._epoints.push(p.x, p.y);
  82146. }
  82147. };
  82148. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82149. this._points.add(hole);
  82150. var holepoints = new PolygonPoints();
  82151. holepoints.add(hole);
  82152. this._holes.push(holepoints);
  82153. this._eholes.push(this._epoints.length / 2);
  82154. this._addToepoint(hole);
  82155. return this;
  82156. };
  82157. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82158. var _this = this;
  82159. if (updatable === void 0) { updatable = false; }
  82160. if (depth === void 0) { depth = 0; }
  82161. var result = new BABYLON.Mesh(this._name, this._scene);
  82162. var normals = new Array();
  82163. var positions = new Array();
  82164. var uvs = new Array();
  82165. var bounds = this._points.computeBounds();
  82166. this._points.elements.forEach(function (p) {
  82167. normals.push(0, 1.0, 0);
  82168. positions.push(p.x, 0, p.y);
  82169. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82170. });
  82171. var indices = new Array();
  82172. var res = earcut(this._epoints, this._eholes, 2);
  82173. for (var i = 0; i < res.length; i++) {
  82174. indices.push(res[i]);
  82175. }
  82176. if (depth > 0) {
  82177. var positionscount = (positions.length / 3); //get the current pointcount
  82178. this._points.elements.forEach(function (p) {
  82179. normals.push(0, -1.0, 0);
  82180. positions.push(p.x, -depth, p.y);
  82181. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82182. });
  82183. var totalCount = indices.length;
  82184. for (var i = 0; i < totalCount; i += 3) {
  82185. var i0 = indices[i + 0];
  82186. var i1 = indices[i + 1];
  82187. var i2 = indices[i + 2];
  82188. indices.push(i2 + positionscount);
  82189. indices.push(i1 + positionscount);
  82190. indices.push(i0 + positionscount);
  82191. }
  82192. //Add the sides
  82193. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82194. this._holes.forEach(function (hole) {
  82195. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82196. });
  82197. }
  82198. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82199. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82200. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82201. result.setIndices(indices);
  82202. return result;
  82203. };
  82204. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82205. var StartIndex = positions.length / 3;
  82206. var ulength = 0;
  82207. for (var i = 0; i < points.elements.length; i++) {
  82208. var p = points.elements[i];
  82209. var p1;
  82210. if ((i + 1) > points.elements.length - 1) {
  82211. p1 = points.elements[0];
  82212. }
  82213. else {
  82214. p1 = points.elements[i + 1];
  82215. }
  82216. positions.push(p.x, 0, p.y);
  82217. positions.push(p.x, -depth, p.y);
  82218. positions.push(p1.x, 0, p1.y);
  82219. positions.push(p1.x, -depth, p1.y);
  82220. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82221. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82222. var v3 = v2.subtract(v1);
  82223. var v4 = new BABYLON.Vector3(0, 1, 0);
  82224. var vn = BABYLON.Vector3.Cross(v3, v4);
  82225. vn = vn.normalize();
  82226. uvs.push(ulength / bounds.width, 0);
  82227. uvs.push(ulength / bounds.width, 1);
  82228. ulength += v3.length();
  82229. uvs.push((ulength / bounds.width), 0);
  82230. uvs.push((ulength / bounds.width), 1);
  82231. if (!flip) {
  82232. normals.push(-vn.x, -vn.y, -vn.z);
  82233. normals.push(-vn.x, -vn.y, -vn.z);
  82234. normals.push(-vn.x, -vn.y, -vn.z);
  82235. normals.push(-vn.x, -vn.y, -vn.z);
  82236. indices.push(StartIndex);
  82237. indices.push(StartIndex + 1);
  82238. indices.push(StartIndex + 2);
  82239. indices.push(StartIndex + 1);
  82240. indices.push(StartIndex + 3);
  82241. indices.push(StartIndex + 2);
  82242. }
  82243. else {
  82244. normals.push(vn.x, vn.y, vn.z);
  82245. normals.push(vn.x, vn.y, vn.z);
  82246. normals.push(vn.x, vn.y, vn.z);
  82247. normals.push(vn.x, vn.y, vn.z);
  82248. indices.push(StartIndex);
  82249. indices.push(StartIndex + 2);
  82250. indices.push(StartIndex + 1);
  82251. indices.push(StartIndex + 1);
  82252. indices.push(StartIndex + 2);
  82253. indices.push(StartIndex + 3);
  82254. }
  82255. StartIndex += 4;
  82256. }
  82257. ;
  82258. };
  82259. return PolygonMeshBuilder;
  82260. }());
  82261. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82262. })(BABYLON || (BABYLON = {}));
  82263. //# sourceMappingURL=babylon.polygonMesh.js.map
  82264. var BABYLON;
  82265. (function (BABYLON) {
  82266. // Unique ID when we import meshes from Babylon to CSG
  82267. var currentCSGMeshId = 0;
  82268. // # class Vertex
  82269. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82270. // one to provide additional features like texture coordinates and vertex
  82271. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82272. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82273. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82274. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82275. // is not used anywhere else.
  82276. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82277. var Vertex = /** @class */ (function () {
  82278. function Vertex(pos, normal, uv) {
  82279. this.pos = pos;
  82280. this.normal = normal;
  82281. this.uv = uv;
  82282. }
  82283. Vertex.prototype.clone = function () {
  82284. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82285. };
  82286. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82287. // orientation of a polygon is flipped.
  82288. Vertex.prototype.flip = function () {
  82289. this.normal = this.normal.scale(-1);
  82290. };
  82291. // Create a new vertex between this vertex and `other` by linearly
  82292. // interpolating all properties using a parameter of `t`. Subclasses should
  82293. // override this to interpolate additional properties.
  82294. Vertex.prototype.interpolate = function (other, t) {
  82295. 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));
  82296. };
  82297. return Vertex;
  82298. }());
  82299. // # class Plane
  82300. // Represents a plane in 3D space.
  82301. var Plane = /** @class */ (function () {
  82302. function Plane(normal, w) {
  82303. this.normal = normal;
  82304. this.w = w;
  82305. }
  82306. Plane.FromPoints = function (a, b, c) {
  82307. var v0 = c.subtract(a);
  82308. var v1 = b.subtract(a);
  82309. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82310. return null;
  82311. }
  82312. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82313. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82314. };
  82315. Plane.prototype.clone = function () {
  82316. return new Plane(this.normal.clone(), this.w);
  82317. };
  82318. Plane.prototype.flip = function () {
  82319. this.normal.scaleInPlace(-1);
  82320. this.w = -this.w;
  82321. };
  82322. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82323. // fragments in the appropriate lists. Coplanar polygons go into either
  82324. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82325. // respect to this plane. Polygons in front or in back of this plane go into
  82326. // either `front` or `back`.
  82327. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82328. var COPLANAR = 0;
  82329. var FRONT = 1;
  82330. var BACK = 2;
  82331. var SPANNING = 3;
  82332. // Classify each point as well as the entire polygon into one of the above
  82333. // four classes.
  82334. var polygonType = 0;
  82335. var types = [];
  82336. var i;
  82337. var t;
  82338. for (i = 0; i < polygon.vertices.length; i++) {
  82339. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82340. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82341. polygonType |= type;
  82342. types.push(type);
  82343. }
  82344. // Put the polygon in the correct list, splitting it when necessary.
  82345. switch (polygonType) {
  82346. case COPLANAR:
  82347. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82348. break;
  82349. case FRONT:
  82350. front.push(polygon);
  82351. break;
  82352. case BACK:
  82353. back.push(polygon);
  82354. break;
  82355. case SPANNING:
  82356. var f = [], b = [];
  82357. for (i = 0; i < polygon.vertices.length; i++) {
  82358. var j = (i + 1) % polygon.vertices.length;
  82359. var ti = types[i], tj = types[j];
  82360. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82361. if (ti !== BACK)
  82362. f.push(vi);
  82363. if (ti !== FRONT)
  82364. b.push(ti !== BACK ? vi.clone() : vi);
  82365. if ((ti | tj) === SPANNING) {
  82366. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82367. var v = vi.interpolate(vj, t);
  82368. f.push(v);
  82369. b.push(v.clone());
  82370. }
  82371. }
  82372. var poly;
  82373. if (f.length >= 3) {
  82374. poly = new Polygon(f, polygon.shared);
  82375. if (poly.plane)
  82376. front.push(poly);
  82377. }
  82378. if (b.length >= 3) {
  82379. poly = new Polygon(b, polygon.shared);
  82380. if (poly.plane)
  82381. back.push(poly);
  82382. }
  82383. break;
  82384. }
  82385. };
  82386. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82387. // point is on the plane.
  82388. Plane.EPSILON = 1e-5;
  82389. return Plane;
  82390. }());
  82391. // # class Polygon
  82392. // Represents a convex polygon. The vertices used to initialize a polygon must
  82393. // be coplanar and form a convex loop.
  82394. //
  82395. // Each convex polygon has a `shared` property, which is shared between all
  82396. // polygons that are clones of each other or were split from the same polygon.
  82397. // This can be used to define per-polygon properties (such as surface color).
  82398. var Polygon = /** @class */ (function () {
  82399. function Polygon(vertices, shared) {
  82400. this.vertices = vertices;
  82401. this.shared = shared;
  82402. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82403. }
  82404. Polygon.prototype.clone = function () {
  82405. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82406. return new Polygon(vertices, this.shared);
  82407. };
  82408. Polygon.prototype.flip = function () {
  82409. this.vertices.reverse().map(function (v) { v.flip(); });
  82410. this.plane.flip();
  82411. };
  82412. return Polygon;
  82413. }());
  82414. // # class Node
  82415. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82416. // by picking a polygon to split along. That polygon (and all other coplanar
  82417. // polygons) are added directly to that node and the other polygons are added to
  82418. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82419. // no distinction between internal and leaf nodes.
  82420. var Node = /** @class */ (function () {
  82421. function Node(polygons) {
  82422. this.plane = null;
  82423. this.front = null;
  82424. this.back = null;
  82425. this.polygons = new Array();
  82426. if (polygons) {
  82427. this.build(polygons);
  82428. }
  82429. }
  82430. Node.prototype.clone = function () {
  82431. var node = new Node();
  82432. node.plane = this.plane && this.plane.clone();
  82433. node.front = this.front && this.front.clone();
  82434. node.back = this.back && this.back.clone();
  82435. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82436. return node;
  82437. };
  82438. // Convert solid space to empty space and empty space to solid space.
  82439. Node.prototype.invert = function () {
  82440. for (var i = 0; i < this.polygons.length; i++) {
  82441. this.polygons[i].flip();
  82442. }
  82443. if (this.plane) {
  82444. this.plane.flip();
  82445. }
  82446. if (this.front) {
  82447. this.front.invert();
  82448. }
  82449. if (this.back) {
  82450. this.back.invert();
  82451. }
  82452. var temp = this.front;
  82453. this.front = this.back;
  82454. this.back = temp;
  82455. };
  82456. // Recursively remove all polygons in `polygons` that are inside this BSP
  82457. // tree.
  82458. Node.prototype.clipPolygons = function (polygons) {
  82459. if (!this.plane)
  82460. return polygons.slice();
  82461. var front = new Array(), back = new Array();
  82462. for (var i = 0; i < polygons.length; i++) {
  82463. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82464. }
  82465. if (this.front) {
  82466. front = this.front.clipPolygons(front);
  82467. }
  82468. if (this.back) {
  82469. back = this.back.clipPolygons(back);
  82470. }
  82471. else {
  82472. back = [];
  82473. }
  82474. return front.concat(back);
  82475. };
  82476. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82477. // `bsp`.
  82478. Node.prototype.clipTo = function (bsp) {
  82479. this.polygons = bsp.clipPolygons(this.polygons);
  82480. if (this.front)
  82481. this.front.clipTo(bsp);
  82482. if (this.back)
  82483. this.back.clipTo(bsp);
  82484. };
  82485. // Return a list of all polygons in this BSP tree.
  82486. Node.prototype.allPolygons = function () {
  82487. var polygons = this.polygons.slice();
  82488. if (this.front)
  82489. polygons = polygons.concat(this.front.allPolygons());
  82490. if (this.back)
  82491. polygons = polygons.concat(this.back.allPolygons());
  82492. return polygons;
  82493. };
  82494. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82495. // new polygons are filtered down to the bottom of the tree and become new
  82496. // nodes there. Each set of polygons is partitioned using the first polygon
  82497. // (no heuristic is used to pick a good split).
  82498. Node.prototype.build = function (polygons) {
  82499. if (!polygons.length)
  82500. return;
  82501. if (!this.plane)
  82502. this.plane = polygons[0].plane.clone();
  82503. var front = new Array(), back = new Array();
  82504. for (var i = 0; i < polygons.length; i++) {
  82505. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82506. }
  82507. if (front.length) {
  82508. if (!this.front)
  82509. this.front = new Node();
  82510. this.front.build(front);
  82511. }
  82512. if (back.length) {
  82513. if (!this.back)
  82514. this.back = new Node();
  82515. this.back.build(back);
  82516. }
  82517. };
  82518. return Node;
  82519. }());
  82520. var CSG = /** @class */ (function () {
  82521. function CSG() {
  82522. this.polygons = new Array();
  82523. }
  82524. // Convert BABYLON.Mesh to BABYLON.CSG
  82525. CSG.FromMesh = function (mesh) {
  82526. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82527. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82528. if (mesh instanceof BABYLON.Mesh) {
  82529. mesh.computeWorldMatrix(true);
  82530. matrix = mesh.getWorldMatrix();
  82531. meshPosition = mesh.position.clone();
  82532. meshRotation = mesh.rotation.clone();
  82533. if (mesh.rotationQuaternion) {
  82534. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82535. }
  82536. meshScaling = mesh.scaling.clone();
  82537. }
  82538. else {
  82539. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82540. }
  82541. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82542. var subMeshes = mesh.subMeshes;
  82543. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82544. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82545. vertices = [];
  82546. for (var j = 0; j < 3; j++) {
  82547. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82548. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82549. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82550. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82551. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82552. vertex = new Vertex(position, normal, uv);
  82553. vertices.push(vertex);
  82554. }
  82555. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82556. // To handle the case of degenerated triangle
  82557. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82558. if (polygon.plane)
  82559. polygons.push(polygon);
  82560. }
  82561. }
  82562. var csg = CSG.FromPolygons(polygons);
  82563. csg.matrix = matrix;
  82564. csg.position = meshPosition;
  82565. csg.rotation = meshRotation;
  82566. csg.scaling = meshScaling;
  82567. csg.rotationQuaternion = meshRotationQuaternion;
  82568. currentCSGMeshId++;
  82569. return csg;
  82570. };
  82571. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82572. CSG.FromPolygons = function (polygons) {
  82573. var csg = new CSG();
  82574. csg.polygons = polygons;
  82575. return csg;
  82576. };
  82577. CSG.prototype.clone = function () {
  82578. var csg = new CSG();
  82579. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82580. csg.copyTransformAttributes(this);
  82581. return csg;
  82582. };
  82583. CSG.prototype.union = function (csg) {
  82584. var a = new Node(this.clone().polygons);
  82585. var b = new Node(csg.clone().polygons);
  82586. a.clipTo(b);
  82587. b.clipTo(a);
  82588. b.invert();
  82589. b.clipTo(a);
  82590. b.invert();
  82591. a.build(b.allPolygons());
  82592. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82593. };
  82594. CSG.prototype.unionInPlace = function (csg) {
  82595. var a = new Node(this.polygons);
  82596. var b = new Node(csg.polygons);
  82597. a.clipTo(b);
  82598. b.clipTo(a);
  82599. b.invert();
  82600. b.clipTo(a);
  82601. b.invert();
  82602. a.build(b.allPolygons());
  82603. this.polygons = a.allPolygons();
  82604. };
  82605. CSG.prototype.subtract = function (csg) {
  82606. var a = new Node(this.clone().polygons);
  82607. var b = new Node(csg.clone().polygons);
  82608. a.invert();
  82609. a.clipTo(b);
  82610. b.clipTo(a);
  82611. b.invert();
  82612. b.clipTo(a);
  82613. b.invert();
  82614. a.build(b.allPolygons());
  82615. a.invert();
  82616. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82617. };
  82618. CSG.prototype.subtractInPlace = function (csg) {
  82619. var a = new Node(this.polygons);
  82620. var b = new Node(csg.polygons);
  82621. a.invert();
  82622. a.clipTo(b);
  82623. b.clipTo(a);
  82624. b.invert();
  82625. b.clipTo(a);
  82626. b.invert();
  82627. a.build(b.allPolygons());
  82628. a.invert();
  82629. this.polygons = a.allPolygons();
  82630. };
  82631. CSG.prototype.intersect = function (csg) {
  82632. var a = new Node(this.clone().polygons);
  82633. var b = new Node(csg.clone().polygons);
  82634. a.invert();
  82635. b.clipTo(a);
  82636. b.invert();
  82637. a.clipTo(b);
  82638. b.clipTo(a);
  82639. a.build(b.allPolygons());
  82640. a.invert();
  82641. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82642. };
  82643. CSG.prototype.intersectInPlace = function (csg) {
  82644. var a = new Node(this.polygons);
  82645. var b = new Node(csg.polygons);
  82646. a.invert();
  82647. b.clipTo(a);
  82648. b.invert();
  82649. a.clipTo(b);
  82650. b.clipTo(a);
  82651. a.build(b.allPolygons());
  82652. a.invert();
  82653. this.polygons = a.allPolygons();
  82654. };
  82655. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82656. // not modified.
  82657. CSG.prototype.inverse = function () {
  82658. var csg = this.clone();
  82659. csg.inverseInPlace();
  82660. return csg;
  82661. };
  82662. CSG.prototype.inverseInPlace = function () {
  82663. this.polygons.map(function (p) { p.flip(); });
  82664. };
  82665. // This is used to keep meshes transformations so they can be restored
  82666. // when we build back a Babylon Mesh
  82667. // NB : All CSG operations are performed in world coordinates
  82668. CSG.prototype.copyTransformAttributes = function (csg) {
  82669. this.matrix = csg.matrix;
  82670. this.position = csg.position;
  82671. this.rotation = csg.rotation;
  82672. this.scaling = csg.scaling;
  82673. this.rotationQuaternion = csg.rotationQuaternion;
  82674. return this;
  82675. };
  82676. // Build Raw mesh from CSG
  82677. // Coordinates here are in world space
  82678. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82679. var matrix = this.matrix.clone();
  82680. matrix.invert();
  82681. 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;
  82682. if (keepSubMeshes) {
  82683. // Sort Polygons, since subMeshes are indices range
  82684. polygons.sort(function (a, b) {
  82685. if (a.shared.meshId === b.shared.meshId) {
  82686. return a.shared.subMeshId - b.shared.subMeshId;
  82687. }
  82688. else {
  82689. return a.shared.meshId - b.shared.meshId;
  82690. }
  82691. });
  82692. }
  82693. for (var i = 0, il = polygons.length; i < il; i++) {
  82694. polygon = polygons[i];
  82695. // Building SubMeshes
  82696. if (!subMesh_dict[polygon.shared.meshId]) {
  82697. subMesh_dict[polygon.shared.meshId] = {};
  82698. }
  82699. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82700. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82701. indexStart: +Infinity,
  82702. indexEnd: -Infinity,
  82703. materialIndex: polygon.shared.materialIndex
  82704. };
  82705. }
  82706. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82707. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82708. polygonIndices[0] = 0;
  82709. polygonIndices[1] = j - 1;
  82710. polygonIndices[2] = j;
  82711. for (var k = 0; k < 3; k++) {
  82712. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82713. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82714. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82715. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82716. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82717. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82718. // Check if 2 points can be merged
  82719. if (!(typeof vertex_idx !== 'undefined' &&
  82720. normals[vertex_idx * 3] === localNormal.x &&
  82721. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82722. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82723. uvs[vertex_idx * 2] === uv.x &&
  82724. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82725. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82726. uvs.push(uv.x, uv.y);
  82727. normals.push(normal.x, normal.y, normal.z);
  82728. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82729. }
  82730. indices.push(vertex_idx);
  82731. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82732. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82733. currentIndex++;
  82734. }
  82735. }
  82736. }
  82737. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82738. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82739. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82740. mesh.setIndices(indices, null);
  82741. if (keepSubMeshes) {
  82742. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82743. var materialIndexOffset = 0, materialMaxIndex;
  82744. mesh.subMeshes = new Array();
  82745. for (var m in subMesh_dict) {
  82746. materialMaxIndex = -1;
  82747. for (var sm in subMesh_dict[m]) {
  82748. subMesh_obj = subMesh_dict[m][sm];
  82749. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82750. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82751. }
  82752. materialIndexOffset += ++materialMaxIndex;
  82753. }
  82754. }
  82755. return mesh;
  82756. };
  82757. // Build Mesh from CSG taking material and transforms into account
  82758. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82759. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82760. mesh.material = material;
  82761. mesh.position.copyFrom(this.position);
  82762. mesh.rotation.copyFrom(this.rotation);
  82763. if (this.rotationQuaternion) {
  82764. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82765. }
  82766. mesh.scaling.copyFrom(this.scaling);
  82767. mesh.computeWorldMatrix(true);
  82768. return mesh;
  82769. };
  82770. return CSG;
  82771. }());
  82772. BABYLON.CSG = CSG;
  82773. })(BABYLON || (BABYLON = {}));
  82774. //# sourceMappingURL=babylon.csg.js.map
  82775. var BABYLON;
  82776. (function (BABYLON) {
  82777. var LensFlare = /** @class */ (function () {
  82778. function LensFlare(size, position, color, imgUrl, system) {
  82779. this.size = size;
  82780. this.position = position;
  82781. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82782. this.color = color || new BABYLON.Color3(1, 1, 1);
  82783. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82784. this._system = system;
  82785. system.lensFlares.push(this);
  82786. }
  82787. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82788. return new LensFlare(size, position, color, imgUrl, system);
  82789. };
  82790. LensFlare.prototype.dispose = function () {
  82791. if (this.texture) {
  82792. this.texture.dispose();
  82793. }
  82794. // Remove from scene
  82795. var index = this._system.lensFlares.indexOf(this);
  82796. this._system.lensFlares.splice(index, 1);
  82797. };
  82798. ;
  82799. return LensFlare;
  82800. }());
  82801. BABYLON.LensFlare = LensFlare;
  82802. })(BABYLON || (BABYLON = {}));
  82803. //# sourceMappingURL=babylon.lensFlare.js.map
  82804. var BABYLON;
  82805. (function (BABYLON) {
  82806. var LensFlareSystem = /** @class */ (function () {
  82807. function LensFlareSystem(name, emitter, scene) {
  82808. this.name = name;
  82809. this.lensFlares = new Array();
  82810. this.borderLimit = 300;
  82811. this.viewportBorder = 0;
  82812. this.layerMask = 0x0FFFFFFF;
  82813. this._vertexBuffers = {};
  82814. this._isEnabled = true;
  82815. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82816. this._emitter = emitter;
  82817. this.id = name;
  82818. scene.lensFlareSystems.push(this);
  82819. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82820. var engine = scene.getEngine();
  82821. // VBO
  82822. var vertices = [];
  82823. vertices.push(1, 1);
  82824. vertices.push(-1, 1);
  82825. vertices.push(-1, -1);
  82826. vertices.push(1, -1);
  82827. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82828. // Indices
  82829. var indices = [];
  82830. indices.push(0);
  82831. indices.push(1);
  82832. indices.push(2);
  82833. indices.push(0);
  82834. indices.push(2);
  82835. indices.push(3);
  82836. this._indexBuffer = engine.createIndexBuffer(indices);
  82837. // Effects
  82838. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82839. }
  82840. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82841. get: function () {
  82842. return this._isEnabled;
  82843. },
  82844. set: function (value) {
  82845. this._isEnabled = value;
  82846. },
  82847. enumerable: true,
  82848. configurable: true
  82849. });
  82850. LensFlareSystem.prototype.getScene = function () {
  82851. return this._scene;
  82852. };
  82853. LensFlareSystem.prototype.getEmitter = function () {
  82854. return this._emitter;
  82855. };
  82856. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82857. this._emitter = newEmitter;
  82858. };
  82859. LensFlareSystem.prototype.getEmitterPosition = function () {
  82860. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82861. };
  82862. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82863. var position = this.getEmitterPosition();
  82864. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82865. this._positionX = position.x;
  82866. this._positionY = position.y;
  82867. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82868. if (this.viewportBorder > 0) {
  82869. globalViewport.x -= this.viewportBorder;
  82870. globalViewport.y -= this.viewportBorder;
  82871. globalViewport.width += this.viewportBorder * 2;
  82872. globalViewport.height += this.viewportBorder * 2;
  82873. position.x += this.viewportBorder;
  82874. position.y += this.viewportBorder;
  82875. this._positionX += this.viewportBorder;
  82876. this._positionY += this.viewportBorder;
  82877. }
  82878. if (position.z > 0) {
  82879. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82880. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82881. return true;
  82882. }
  82883. return true;
  82884. }
  82885. return false;
  82886. };
  82887. LensFlareSystem.prototype._isVisible = function () {
  82888. if (!this._isEnabled || !this._scene.activeCamera) {
  82889. return false;
  82890. }
  82891. var emitterPosition = this.getEmitterPosition();
  82892. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82893. var distance = direction.length();
  82894. direction.normalize();
  82895. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82896. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82897. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82898. };
  82899. LensFlareSystem.prototype.render = function () {
  82900. if (!this._effect.isReady() || !this._scene.activeCamera)
  82901. return false;
  82902. var engine = this._scene.getEngine();
  82903. var viewport = this._scene.activeCamera.viewport;
  82904. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82905. // Position
  82906. if (!this.computeEffectivePosition(globalViewport)) {
  82907. return false;
  82908. }
  82909. // Visibility
  82910. if (!this._isVisible()) {
  82911. return false;
  82912. }
  82913. // Intensity
  82914. var awayX;
  82915. var awayY;
  82916. if (this._positionX < this.borderLimit + globalViewport.x) {
  82917. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82918. }
  82919. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82920. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82921. }
  82922. else {
  82923. awayX = 0;
  82924. }
  82925. if (this._positionY < this.borderLimit + globalViewport.y) {
  82926. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82927. }
  82928. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82929. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82930. }
  82931. else {
  82932. awayY = 0;
  82933. }
  82934. var away = (awayX > awayY) ? awayX : awayY;
  82935. away -= this.viewportBorder;
  82936. if (away > this.borderLimit) {
  82937. away = this.borderLimit;
  82938. }
  82939. var intensity = 1.0 - (away / this.borderLimit);
  82940. if (intensity < 0) {
  82941. return false;
  82942. }
  82943. if (intensity > 1.0) {
  82944. intensity = 1.0;
  82945. }
  82946. if (this.viewportBorder > 0) {
  82947. globalViewport.x += this.viewportBorder;
  82948. globalViewport.y += this.viewportBorder;
  82949. globalViewport.width -= this.viewportBorder * 2;
  82950. globalViewport.height -= this.viewportBorder * 2;
  82951. this._positionX -= this.viewportBorder;
  82952. this._positionY -= this.viewportBorder;
  82953. }
  82954. // Position
  82955. var centerX = globalViewport.x + globalViewport.width / 2;
  82956. var centerY = globalViewport.y + globalViewport.height / 2;
  82957. var distX = centerX - this._positionX;
  82958. var distY = centerY - this._positionY;
  82959. // Effects
  82960. engine.enableEffect(this._effect);
  82961. engine.setState(false);
  82962. engine.setDepthBuffer(false);
  82963. // VBOs
  82964. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82965. // Flares
  82966. for (var index = 0; index < this.lensFlares.length; index++) {
  82967. var flare = this.lensFlares[index];
  82968. engine.setAlphaMode(flare.alphaMode);
  82969. var x = centerX - (distX * flare.position);
  82970. var y = centerY - (distY * flare.position);
  82971. var cw = flare.size;
  82972. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82973. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82974. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82975. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82976. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82977. // Texture
  82978. this._effect.setTexture("textureSampler", flare.texture);
  82979. // Color
  82980. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82981. // Draw order
  82982. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82983. }
  82984. engine.setDepthBuffer(true);
  82985. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82986. return true;
  82987. };
  82988. LensFlareSystem.prototype.dispose = function () {
  82989. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82990. if (vertexBuffer) {
  82991. vertexBuffer.dispose();
  82992. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82993. }
  82994. if (this._indexBuffer) {
  82995. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82996. this._indexBuffer = null;
  82997. }
  82998. while (this.lensFlares.length) {
  82999. this.lensFlares[0].dispose();
  83000. }
  83001. // Remove from scene
  83002. var index = this._scene.lensFlareSystems.indexOf(this);
  83003. this._scene.lensFlareSystems.splice(index, 1);
  83004. };
  83005. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83006. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83007. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83008. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83009. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83010. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83011. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83012. var parsedFlare = parsedLensFlareSystem.flares[index];
  83013. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83014. }
  83015. return lensFlareSystem;
  83016. };
  83017. LensFlareSystem.prototype.serialize = function () {
  83018. var serializationObject = {};
  83019. serializationObject.id = this.id;
  83020. serializationObject.name = this.name;
  83021. serializationObject.emitterId = this.getEmitter().id;
  83022. serializationObject.borderLimit = this.borderLimit;
  83023. serializationObject.flares = [];
  83024. for (var index = 0; index < this.lensFlares.length; index++) {
  83025. var flare = this.lensFlares[index];
  83026. serializationObject.flares.push({
  83027. size: flare.size,
  83028. position: flare.position,
  83029. color: flare.color.asArray(),
  83030. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83031. });
  83032. }
  83033. return serializationObject;
  83034. };
  83035. return LensFlareSystem;
  83036. }());
  83037. BABYLON.LensFlareSystem = LensFlareSystem;
  83038. })(BABYLON || (BABYLON = {}));
  83039. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83040. var BABYLON;
  83041. (function (BABYLON) {
  83042. /**
  83043. * This is a holder class for the physics joint created by the physics plugin.
  83044. * It holds a set of functions to control the underlying joint.
  83045. */
  83046. var PhysicsJoint = /** @class */ (function () {
  83047. function PhysicsJoint(type, jointData) {
  83048. this.type = type;
  83049. this.jointData = jointData;
  83050. jointData.nativeParams = jointData.nativeParams || {};
  83051. }
  83052. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83053. get: function () {
  83054. return this._physicsJoint;
  83055. },
  83056. set: function (newJoint) {
  83057. if (this._physicsJoint) {
  83058. //remove from the wolrd
  83059. }
  83060. this._physicsJoint = newJoint;
  83061. },
  83062. enumerable: true,
  83063. configurable: true
  83064. });
  83065. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83066. set: function (physicsPlugin) {
  83067. this._physicsPlugin = physicsPlugin;
  83068. },
  83069. enumerable: true,
  83070. configurable: true
  83071. });
  83072. /**
  83073. * Execute a function that is physics-plugin specific.
  83074. * @param {Function} func the function that will be executed.
  83075. * It accepts two parameters: the physics world and the physics joint.
  83076. */
  83077. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83078. func(this._physicsPlugin.world, this._physicsJoint);
  83079. };
  83080. //TODO check if the native joints are the same
  83081. //Joint Types
  83082. PhysicsJoint.DistanceJoint = 0;
  83083. PhysicsJoint.HingeJoint = 1;
  83084. PhysicsJoint.BallAndSocketJoint = 2;
  83085. PhysicsJoint.WheelJoint = 3;
  83086. PhysicsJoint.SliderJoint = 4;
  83087. //OIMO
  83088. PhysicsJoint.PrismaticJoint = 5;
  83089. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83090. PhysicsJoint.UniversalJoint = 6;
  83091. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83092. //Cannon
  83093. //Similar to a Ball-Joint. Different in params
  83094. PhysicsJoint.PointToPointJoint = 8;
  83095. //Cannon only at the moment
  83096. PhysicsJoint.SpringJoint = 9;
  83097. PhysicsJoint.LockJoint = 10;
  83098. return PhysicsJoint;
  83099. }());
  83100. BABYLON.PhysicsJoint = PhysicsJoint;
  83101. /**
  83102. * A class representing a physics distance joint.
  83103. */
  83104. var DistanceJoint = /** @class */ (function (_super) {
  83105. __extends(DistanceJoint, _super);
  83106. function DistanceJoint(jointData) {
  83107. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83108. }
  83109. /**
  83110. * Update the predefined distance.
  83111. */
  83112. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83113. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83114. };
  83115. return DistanceJoint;
  83116. }(PhysicsJoint));
  83117. BABYLON.DistanceJoint = DistanceJoint;
  83118. var MotorEnabledJoint = /** @class */ (function (_super) {
  83119. __extends(MotorEnabledJoint, _super);
  83120. function MotorEnabledJoint(type, jointData) {
  83121. return _super.call(this, type, jointData) || this;
  83122. }
  83123. /**
  83124. * Set the motor values.
  83125. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83126. * @param {number} force the force to apply
  83127. * @param {number} maxForce max force for this motor.
  83128. */
  83129. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83130. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83131. };
  83132. /**
  83133. * Set the motor's limits.
  83134. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83135. */
  83136. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83137. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83138. };
  83139. return MotorEnabledJoint;
  83140. }(PhysicsJoint));
  83141. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83142. /**
  83143. * This class represents a single hinge physics joint
  83144. */
  83145. var HingeJoint = /** @class */ (function (_super) {
  83146. __extends(HingeJoint, _super);
  83147. function HingeJoint(jointData) {
  83148. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83149. }
  83150. /**
  83151. * Set the motor values.
  83152. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83153. * @param {number} force the force to apply
  83154. * @param {number} maxForce max force for this motor.
  83155. */
  83156. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83157. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83158. };
  83159. /**
  83160. * Set the motor's limits.
  83161. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83162. */
  83163. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83164. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83165. };
  83166. return HingeJoint;
  83167. }(MotorEnabledJoint));
  83168. BABYLON.HingeJoint = HingeJoint;
  83169. /**
  83170. * This class represents a dual hinge physics joint (same as wheel joint)
  83171. */
  83172. var Hinge2Joint = /** @class */ (function (_super) {
  83173. __extends(Hinge2Joint, _super);
  83174. function Hinge2Joint(jointData) {
  83175. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83176. }
  83177. /**
  83178. * Set the motor values.
  83179. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83180. * @param {number} force the force to apply
  83181. * @param {number} maxForce max force for this motor.
  83182. * @param {motorIndex} the motor's index, 0 or 1.
  83183. */
  83184. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83185. if (motorIndex === void 0) { motorIndex = 0; }
  83186. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83187. };
  83188. /**
  83189. * Set the motor limits.
  83190. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83191. * @param {number} upperLimit the upper limit
  83192. * @param {number} lowerLimit lower limit
  83193. * @param {motorIndex} the motor's index, 0 or 1.
  83194. */
  83195. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83196. if (motorIndex === void 0) { motorIndex = 0; }
  83197. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83198. };
  83199. return Hinge2Joint;
  83200. }(MotorEnabledJoint));
  83201. BABYLON.Hinge2Joint = Hinge2Joint;
  83202. })(BABYLON || (BABYLON = {}));
  83203. //# sourceMappingURL=babylon.physicsJoint.js.map
  83204. var BABYLON;
  83205. (function (BABYLON) {
  83206. var PhysicsImpostor = /** @class */ (function () {
  83207. function PhysicsImpostor(object, type, _options, _scene) {
  83208. if (_options === void 0) { _options = { mass: 0 }; }
  83209. var _this = this;
  83210. this.object = object;
  83211. this.type = type;
  83212. this._options = _options;
  83213. this._scene = _scene;
  83214. this._bodyUpdateRequired = false;
  83215. this._onBeforePhysicsStepCallbacks = new Array();
  83216. this._onAfterPhysicsStepCallbacks = new Array();
  83217. this._onPhysicsCollideCallbacks = [];
  83218. this._deltaPosition = BABYLON.Vector3.Zero();
  83219. this._isDisposed = false;
  83220. //temp variables for parent rotation calculations
  83221. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83222. this._tmpQuat = new BABYLON.Quaternion();
  83223. this._tmpQuat2 = new BABYLON.Quaternion();
  83224. /**
  83225. * this function is executed by the physics engine.
  83226. */
  83227. this.beforeStep = function () {
  83228. if (!_this._physicsEngine) {
  83229. return;
  83230. }
  83231. _this.object.translate(_this._deltaPosition, -1);
  83232. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83233. _this.object.computeWorldMatrix(false);
  83234. if (_this.object.parent && _this.object.rotationQuaternion) {
  83235. _this.getParentsRotation();
  83236. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83237. }
  83238. else {
  83239. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83240. }
  83241. if (!_this._options.disableBidirectionalTransformation) {
  83242. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83243. }
  83244. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83245. func(_this);
  83246. });
  83247. };
  83248. /**
  83249. * this function is executed by the physics engine.
  83250. */
  83251. this.afterStep = function () {
  83252. if (!_this._physicsEngine) {
  83253. return;
  83254. }
  83255. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83256. func(_this);
  83257. });
  83258. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83259. // object has now its world rotation. needs to be converted to local.
  83260. if (_this.object.parent && _this.object.rotationQuaternion) {
  83261. _this.getParentsRotation();
  83262. _this._tmpQuat.conjugateInPlace();
  83263. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83264. }
  83265. // take the position set and make it the absolute position of this object.
  83266. _this.object.setAbsolutePosition(_this.object.position);
  83267. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83268. _this.object.translate(_this._deltaPosition, 1);
  83269. };
  83270. /**
  83271. * Legacy collision detection event support
  83272. */
  83273. this.onCollideEvent = null;
  83274. //event and body object due to cannon's event-based architecture.
  83275. this.onCollide = function (e) {
  83276. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83277. return;
  83278. }
  83279. if (!_this._physicsEngine) {
  83280. return;
  83281. }
  83282. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83283. if (otherImpostor) {
  83284. // Legacy collision detection event support
  83285. if (_this.onCollideEvent) {
  83286. _this.onCollideEvent(_this, otherImpostor);
  83287. }
  83288. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83289. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83290. }).forEach(function (obj) {
  83291. obj.callback(_this, otherImpostor);
  83292. });
  83293. }
  83294. };
  83295. //sanity check!
  83296. if (!this.object) {
  83297. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83298. return;
  83299. }
  83300. //legacy support for old syntax.
  83301. if (!this._scene && object.getScene) {
  83302. this._scene = object.getScene();
  83303. }
  83304. if (!this._scene) {
  83305. return;
  83306. }
  83307. this._physicsEngine = this._scene.getPhysicsEngine();
  83308. if (!this._physicsEngine) {
  83309. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83310. }
  83311. else {
  83312. //set the object's quaternion, if not set
  83313. if (!this.object.rotationQuaternion) {
  83314. if (this.object.rotation) {
  83315. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83316. }
  83317. else {
  83318. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83319. }
  83320. }
  83321. //default options params
  83322. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83323. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83324. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83325. this._joints = [];
  83326. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83327. if (!this.object.parent || this._options.ignoreParent) {
  83328. this._init();
  83329. }
  83330. else if (this.object.parent.physicsImpostor) {
  83331. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83332. }
  83333. }
  83334. }
  83335. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83336. get: function () {
  83337. return this._isDisposed;
  83338. },
  83339. enumerable: true,
  83340. configurable: true
  83341. });
  83342. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83343. get: function () {
  83344. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83345. },
  83346. set: function (value) {
  83347. this.setMass(value);
  83348. },
  83349. enumerable: true,
  83350. configurable: true
  83351. });
  83352. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83353. get: function () {
  83354. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83355. },
  83356. set: function (value) {
  83357. if (!this._physicsEngine) {
  83358. return;
  83359. }
  83360. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83361. },
  83362. enumerable: true,
  83363. configurable: true
  83364. });
  83365. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83366. get: function () {
  83367. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83368. },
  83369. set: function (value) {
  83370. if (!this._physicsEngine) {
  83371. return;
  83372. }
  83373. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83374. },
  83375. enumerable: true,
  83376. configurable: true
  83377. });
  83378. /**
  83379. * This function will completly initialize this impostor.
  83380. * It will create a new body - but only if this mesh has no parent.
  83381. * If it has, this impostor will not be used other than to define the impostor
  83382. * of the child mesh.
  83383. */
  83384. PhysicsImpostor.prototype._init = function () {
  83385. if (!this._physicsEngine) {
  83386. return;
  83387. }
  83388. this._physicsEngine.removeImpostor(this);
  83389. this.physicsBody = null;
  83390. this._parent = this._parent || this._getPhysicsParent();
  83391. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83392. this._physicsEngine.addImpostor(this);
  83393. }
  83394. };
  83395. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83396. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83397. var parentMesh = this.object.parent;
  83398. return parentMesh.physicsImpostor;
  83399. }
  83400. return null;
  83401. };
  83402. /**
  83403. * Should a new body be generated.
  83404. */
  83405. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83406. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83407. };
  83408. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83409. this.forceUpdate();
  83410. };
  83411. /**
  83412. * Force a regeneration of this or the parent's impostor's body.
  83413. * Use under cautious - This will remove all joints already implemented.
  83414. */
  83415. PhysicsImpostor.prototype.forceUpdate = function () {
  83416. this._init();
  83417. if (this.parent && !this._options.ignoreParent) {
  83418. this.parent.forceUpdate();
  83419. }
  83420. };
  83421. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83422. /*public get mesh(): AbstractMesh {
  83423. return this._mesh;
  83424. }*/
  83425. /**
  83426. * Gets the body that holds this impostor. Either its own, or its parent.
  83427. */
  83428. get: function () {
  83429. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83430. },
  83431. /**
  83432. * Set the physics body. Used mainly by the physics engine/plugin
  83433. */
  83434. set: function (physicsBody) {
  83435. if (this._physicsBody && this._physicsEngine) {
  83436. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83437. }
  83438. this._physicsBody = physicsBody;
  83439. this.resetUpdateFlags();
  83440. },
  83441. enumerable: true,
  83442. configurable: true
  83443. });
  83444. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83445. get: function () {
  83446. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83447. },
  83448. set: function (value) {
  83449. this._parent = value;
  83450. },
  83451. enumerable: true,
  83452. configurable: true
  83453. });
  83454. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83455. this._bodyUpdateRequired = false;
  83456. };
  83457. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83458. if (this.object.getBoundingInfo) {
  83459. var q = this.object.rotationQuaternion;
  83460. //reset rotation
  83461. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83462. //calculate the world matrix with no rotation
  83463. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83464. var boundingInfo = this.object.getBoundingInfo();
  83465. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83466. //bring back the rotation
  83467. this.object.rotationQuaternion = q;
  83468. //calculate the world matrix with the new rotation
  83469. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83470. return size;
  83471. }
  83472. else {
  83473. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83474. }
  83475. };
  83476. PhysicsImpostor.prototype.getObjectCenter = function () {
  83477. if (this.object.getBoundingInfo) {
  83478. var boundingInfo = this.object.getBoundingInfo();
  83479. return boundingInfo.boundingBox.centerWorld;
  83480. }
  83481. else {
  83482. return this.object.position;
  83483. }
  83484. };
  83485. /**
  83486. * Get a specific parametes from the options parameter.
  83487. */
  83488. PhysicsImpostor.prototype.getParam = function (paramName) {
  83489. return this._options[paramName];
  83490. };
  83491. /**
  83492. * Sets a specific parameter in the options given to the physics plugin
  83493. */
  83494. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83495. this._options[paramName] = value;
  83496. this._bodyUpdateRequired = true;
  83497. };
  83498. /**
  83499. * Specifically change the body's mass option. Won't recreate the physics body object
  83500. */
  83501. PhysicsImpostor.prototype.setMass = function (mass) {
  83502. if (this.getParam("mass") !== mass) {
  83503. this.setParam("mass", mass);
  83504. }
  83505. if (this._physicsEngine) {
  83506. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83507. }
  83508. };
  83509. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83510. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83511. };
  83512. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83513. if (this._physicsEngine) {
  83514. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83515. }
  83516. };
  83517. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83518. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83519. };
  83520. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83521. if (this._physicsEngine) {
  83522. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83523. }
  83524. };
  83525. /**
  83526. * Execute a function with the physics plugin native code.
  83527. * Provide a function the will have two variables - the world object and the physics body object.
  83528. */
  83529. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83530. if (this._physicsEngine) {
  83531. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83532. }
  83533. };
  83534. /**
  83535. * Register a function that will be executed before the physics world is stepping forward.
  83536. */
  83537. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83538. this._onBeforePhysicsStepCallbacks.push(func);
  83539. };
  83540. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83541. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83542. if (index > -1) {
  83543. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83544. }
  83545. else {
  83546. BABYLON.Tools.Warn("Function to remove was not found");
  83547. }
  83548. };
  83549. /**
  83550. * Register a function that will be executed after the physics step
  83551. */
  83552. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83553. this._onAfterPhysicsStepCallbacks.push(func);
  83554. };
  83555. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83556. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83557. if (index > -1) {
  83558. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83559. }
  83560. else {
  83561. BABYLON.Tools.Warn("Function to remove was not found");
  83562. }
  83563. };
  83564. /**
  83565. * register a function that will be executed when this impostor collides against a different body.
  83566. */
  83567. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83568. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83569. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83570. };
  83571. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83572. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83573. var index = -1;
  83574. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83575. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83576. // chcek the arrays match
  83577. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83578. return collidedAgainstList.indexOf(impostor) > -1;
  83579. });
  83580. if (sameList) {
  83581. index = idx;
  83582. }
  83583. return sameList;
  83584. }
  83585. return false;
  83586. });
  83587. if (found) {
  83588. this._onPhysicsCollideCallbacks.splice(index, 1);
  83589. }
  83590. else {
  83591. BABYLON.Tools.Warn("Function to remove was not found");
  83592. }
  83593. };
  83594. PhysicsImpostor.prototype.getParentsRotation = function () {
  83595. var parent = this.object.parent;
  83596. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83597. while (parent) {
  83598. if (parent.rotationQuaternion) {
  83599. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83600. }
  83601. else {
  83602. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83603. }
  83604. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83605. parent = parent.parent;
  83606. }
  83607. return this._tmpQuat;
  83608. };
  83609. /**
  83610. * Apply a force
  83611. */
  83612. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83613. if (this._physicsEngine) {
  83614. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83615. }
  83616. return this;
  83617. };
  83618. /**
  83619. * Apply an impulse
  83620. */
  83621. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83622. if (this._physicsEngine) {
  83623. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83624. }
  83625. return this;
  83626. };
  83627. /**
  83628. * A help function to create a joint.
  83629. */
  83630. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83631. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83632. this.addJoint(otherImpostor, joint);
  83633. return this;
  83634. };
  83635. /**
  83636. * Add a joint to this impostor with a different impostor.
  83637. */
  83638. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83639. this._joints.push({
  83640. otherImpostor: otherImpostor,
  83641. joint: joint
  83642. });
  83643. if (this._physicsEngine) {
  83644. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83645. }
  83646. return this;
  83647. };
  83648. /**
  83649. * Will keep this body still, in a sleep mode.
  83650. */
  83651. PhysicsImpostor.prototype.sleep = function () {
  83652. if (this._physicsEngine) {
  83653. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83654. }
  83655. return this;
  83656. };
  83657. /**
  83658. * Wake the body up.
  83659. */
  83660. PhysicsImpostor.prototype.wakeUp = function () {
  83661. if (this._physicsEngine) {
  83662. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83663. }
  83664. return this;
  83665. };
  83666. PhysicsImpostor.prototype.clone = function (newObject) {
  83667. if (!newObject)
  83668. return null;
  83669. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83670. };
  83671. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83672. var _this = this;
  83673. //no dispose if no physics engine is available.
  83674. if (!this._physicsEngine) {
  83675. return;
  83676. }
  83677. this._joints.forEach(function (j) {
  83678. if (_this._physicsEngine) {
  83679. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83680. }
  83681. });
  83682. //dispose the physics body
  83683. this._physicsEngine.removeImpostor(this);
  83684. if (this.parent) {
  83685. this.parent.forceUpdate();
  83686. }
  83687. else {
  83688. /*this._object.getChildMeshes().forEach(function(mesh) {
  83689. if (mesh.physicsImpostor) {
  83690. if (disposeChildren) {
  83691. mesh.physicsImpostor.dispose();
  83692. mesh.physicsImpostor = null;
  83693. }
  83694. }
  83695. })*/
  83696. }
  83697. this._isDisposed = true;
  83698. };
  83699. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83700. this._deltaPosition.copyFrom(position);
  83701. };
  83702. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83703. if (!this._deltaRotation) {
  83704. this._deltaRotation = new BABYLON.Quaternion();
  83705. }
  83706. this._deltaRotation.copyFrom(rotation);
  83707. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83708. };
  83709. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83710. if (this._physicsEngine) {
  83711. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83712. }
  83713. return this;
  83714. };
  83715. PhysicsImpostor.prototype.getRadius = function () {
  83716. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83717. };
  83718. /**
  83719. * Sync a bone with this impostor
  83720. * @param bone The bone to sync to the impostor.
  83721. * @param boneMesh The mesh that the bone is influencing.
  83722. * @param jointPivot The pivot of the joint / bone in local space.
  83723. * @param distToJoint Optional distance from the impostor to the joint.
  83724. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83725. */
  83726. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83727. var tempVec = PhysicsImpostor._tmpVecs[0];
  83728. var mesh = this.object;
  83729. if (mesh.rotationQuaternion) {
  83730. if (adjustRotation) {
  83731. var tempQuat = PhysicsImpostor._tmpQuat;
  83732. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83733. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83734. }
  83735. else {
  83736. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83737. }
  83738. }
  83739. tempVec.x = 0;
  83740. tempVec.y = 0;
  83741. tempVec.z = 0;
  83742. if (jointPivot) {
  83743. tempVec.x = jointPivot.x;
  83744. tempVec.y = jointPivot.y;
  83745. tempVec.z = jointPivot.z;
  83746. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83747. if (distToJoint === undefined || distToJoint === null) {
  83748. distToJoint = jointPivot.length();
  83749. }
  83750. tempVec.x *= distToJoint;
  83751. tempVec.y *= distToJoint;
  83752. tempVec.z *= distToJoint;
  83753. }
  83754. if (bone.getParent()) {
  83755. tempVec.addInPlace(mesh.getAbsolutePosition());
  83756. bone.setAbsolutePosition(tempVec, boneMesh);
  83757. }
  83758. else {
  83759. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83760. boneMesh.position.x -= tempVec.x;
  83761. boneMesh.position.y -= tempVec.y;
  83762. boneMesh.position.z -= tempVec.z;
  83763. }
  83764. };
  83765. /**
  83766. * Sync impostor to a bone
  83767. * @param bone The bone that the impostor will be synced to.
  83768. * @param boneMesh The mesh that the bone is influencing.
  83769. * @param jointPivot The pivot of the joint / bone in local space.
  83770. * @param distToJoint Optional distance from the impostor to the joint.
  83771. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83772. * @param boneAxis Optional vector3 axis the bone is aligned with
  83773. */
  83774. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83775. var mesh = this.object;
  83776. if (mesh.rotationQuaternion) {
  83777. if (adjustRotation) {
  83778. var tempQuat = PhysicsImpostor._tmpQuat;
  83779. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83780. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83781. }
  83782. else {
  83783. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83784. }
  83785. }
  83786. var pos = PhysicsImpostor._tmpVecs[0];
  83787. var boneDir = PhysicsImpostor._tmpVecs[1];
  83788. if (!boneAxis) {
  83789. boneAxis = PhysicsImpostor._tmpVecs[2];
  83790. boneAxis.x = 0;
  83791. boneAxis.y = 1;
  83792. boneAxis.z = 0;
  83793. }
  83794. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83795. bone.getAbsolutePositionToRef(boneMesh, pos);
  83796. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83797. distToJoint = jointPivot.length();
  83798. }
  83799. if (distToJoint !== undefined && distToJoint !== null) {
  83800. pos.x += boneDir.x * distToJoint;
  83801. pos.y += boneDir.y * distToJoint;
  83802. pos.z += boneDir.z * distToJoint;
  83803. }
  83804. mesh.setAbsolutePosition(pos);
  83805. };
  83806. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83807. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83808. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83809. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83810. //Impostor types
  83811. PhysicsImpostor.NoImpostor = 0;
  83812. PhysicsImpostor.SphereImpostor = 1;
  83813. PhysicsImpostor.BoxImpostor = 2;
  83814. PhysicsImpostor.PlaneImpostor = 3;
  83815. PhysicsImpostor.MeshImpostor = 4;
  83816. PhysicsImpostor.CylinderImpostor = 7;
  83817. PhysicsImpostor.ParticleImpostor = 8;
  83818. PhysicsImpostor.HeightmapImpostor = 9;
  83819. return PhysicsImpostor;
  83820. }());
  83821. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83822. })(BABYLON || (BABYLON = {}));
  83823. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83824. var BABYLON;
  83825. (function (BABYLON) {
  83826. var PhysicsEngine = /** @class */ (function () {
  83827. function PhysicsEngine(gravity, _physicsPlugin) {
  83828. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83829. this._physicsPlugin = _physicsPlugin;
  83830. //new methods and parameters
  83831. this._impostors = [];
  83832. this._joints = [];
  83833. if (!this._physicsPlugin.isSupported()) {
  83834. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83835. + "Please make sure it is included.");
  83836. }
  83837. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83838. this.setGravity(gravity);
  83839. this.setTimeStep();
  83840. }
  83841. PhysicsEngine.prototype.setGravity = function (gravity) {
  83842. this.gravity = gravity;
  83843. this._physicsPlugin.setGravity(this.gravity);
  83844. };
  83845. /**
  83846. * Set the time step of the physics engine.
  83847. * default is 1/60.
  83848. * To slow it down, enter 1/600 for example.
  83849. * To speed it up, 1/30
  83850. * @param {number} newTimeStep the new timestep to apply to this world.
  83851. */
  83852. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83853. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83854. this._physicsPlugin.setTimeStep(newTimeStep);
  83855. };
  83856. /**
  83857. * Get the time step of the physics engine.
  83858. */
  83859. PhysicsEngine.prototype.getTimeStep = function () {
  83860. return this._physicsPlugin.getTimeStep();
  83861. };
  83862. PhysicsEngine.prototype.dispose = function () {
  83863. this._impostors.forEach(function (impostor) {
  83864. impostor.dispose();
  83865. });
  83866. this._physicsPlugin.dispose();
  83867. };
  83868. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83869. return this._physicsPlugin.name;
  83870. };
  83871. /**
  83872. * Adding a new impostor for the impostor tracking.
  83873. * This will be done by the impostor itself.
  83874. * @param {PhysicsImpostor} impostor the impostor to add
  83875. */
  83876. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83877. impostor.uniqueId = this._impostors.push(impostor);
  83878. //if no parent, generate the body
  83879. if (!impostor.parent) {
  83880. this._physicsPlugin.generatePhysicsBody(impostor);
  83881. }
  83882. };
  83883. /**
  83884. * Remove an impostor from the engine.
  83885. * This impostor and its mesh will not longer be updated by the physics engine.
  83886. * @param {PhysicsImpostor} impostor the impostor to remove
  83887. */
  83888. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83889. var index = this._impostors.indexOf(impostor);
  83890. if (index > -1) {
  83891. var removed = this._impostors.splice(index, 1);
  83892. //Is it needed?
  83893. if (removed.length) {
  83894. //this will also remove it from the world.
  83895. removed[0].physicsBody = null;
  83896. }
  83897. }
  83898. };
  83899. /**
  83900. * Add a joint to the physics engine
  83901. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83902. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83903. * @param {PhysicsJoint} the joint that will connect both impostors.
  83904. */
  83905. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83906. var impostorJoint = {
  83907. mainImpostor: mainImpostor,
  83908. connectedImpostor: connectedImpostor,
  83909. joint: joint
  83910. };
  83911. joint.physicsPlugin = this._physicsPlugin;
  83912. this._joints.push(impostorJoint);
  83913. this._physicsPlugin.generateJoint(impostorJoint);
  83914. };
  83915. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83916. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83917. return (impostorJoint.connectedImpostor === connectedImpostor
  83918. && impostorJoint.joint === joint
  83919. && impostorJoint.mainImpostor === mainImpostor);
  83920. });
  83921. if (matchingJoints.length) {
  83922. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83923. //TODO remove it from the list as well
  83924. }
  83925. };
  83926. /**
  83927. * Called by the scene. no need to call it.
  83928. */
  83929. PhysicsEngine.prototype._step = function (delta) {
  83930. var _this = this;
  83931. //check if any mesh has no body / requires an update
  83932. this._impostors.forEach(function (impostor) {
  83933. if (impostor.isBodyInitRequired()) {
  83934. _this._physicsPlugin.generatePhysicsBody(impostor);
  83935. }
  83936. });
  83937. if (delta > 0.1) {
  83938. delta = 0.1;
  83939. }
  83940. else if (delta <= 0) {
  83941. delta = 1.0 / 60.0;
  83942. }
  83943. this._physicsPlugin.executeStep(delta, this._impostors);
  83944. };
  83945. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83946. return this._physicsPlugin;
  83947. };
  83948. PhysicsEngine.prototype.getImpostors = function () {
  83949. return this._impostors;
  83950. };
  83951. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83952. for (var i = 0; i < this._impostors.length; ++i) {
  83953. if (this._impostors[i].object === object) {
  83954. return this._impostors[i];
  83955. }
  83956. }
  83957. return null;
  83958. };
  83959. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83960. for (var i = 0; i < this._impostors.length; ++i) {
  83961. if (this._impostors[i].physicsBody === body) {
  83962. return this._impostors[i];
  83963. }
  83964. }
  83965. return null;
  83966. };
  83967. // Statics
  83968. PhysicsEngine.Epsilon = 0.001;
  83969. return PhysicsEngine;
  83970. }());
  83971. BABYLON.PhysicsEngine = PhysicsEngine;
  83972. })(BABYLON || (BABYLON = {}));
  83973. //# sourceMappingURL=babylon.physicsEngine.js.map
  83974. var BABYLON;
  83975. (function (BABYLON) {
  83976. var PhysicsHelper = /** @class */ (function () {
  83977. function PhysicsHelper(scene) {
  83978. this._scene = scene;
  83979. this._physicsEngine = this._scene.getPhysicsEngine();
  83980. if (!this._physicsEngine) {
  83981. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83982. }
  83983. }
  83984. /**
  83985. * @param {Vector3} origin the origin of the explosion
  83986. * @param {number} radius the explosion radius
  83987. * @param {number} strength the explosion strength
  83988. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83989. */
  83990. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83991. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83992. if (!this._physicsEngine) {
  83993. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83994. return null;
  83995. }
  83996. var impostors = this._physicsEngine.getImpostors();
  83997. if (impostors.length === 0) {
  83998. return null;
  83999. }
  84000. var event = new PhysicsRadialExplosionEvent(this._scene);
  84001. impostors.forEach(function (impostor) {
  84002. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84003. if (!impostorForceAndContactPoint) {
  84004. return;
  84005. }
  84006. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84007. });
  84008. event.dispose(false);
  84009. return event;
  84010. };
  84011. /**
  84012. * @param {Vector3} origin the origin of the explosion
  84013. * @param {number} radius the explosion radius
  84014. * @param {number} strength the explosion strength
  84015. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84016. */
  84017. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84018. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84019. if (!this._physicsEngine) {
  84020. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84021. return null;
  84022. }
  84023. var impostors = this._physicsEngine.getImpostors();
  84024. if (impostors.length === 0) {
  84025. return null;
  84026. }
  84027. var event = new PhysicsRadialExplosionEvent(this._scene);
  84028. impostors.forEach(function (impostor) {
  84029. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84030. if (!impostorForceAndContactPoint) {
  84031. return;
  84032. }
  84033. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84034. });
  84035. event.dispose(false);
  84036. return event;
  84037. };
  84038. /**
  84039. * @param {Vector3} origin the origin of the explosion
  84040. * @param {number} radius the explosion radius
  84041. * @param {number} strength the explosion strength
  84042. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84043. */
  84044. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84045. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84046. if (!this._physicsEngine) {
  84047. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84048. return null;
  84049. }
  84050. var impostors = this._physicsEngine.getImpostors();
  84051. if (impostors.length === 0) {
  84052. return null;
  84053. }
  84054. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84055. event.dispose(false);
  84056. return event;
  84057. };
  84058. /**
  84059. * @param {Vector3} origin the origin of the updraft
  84060. * @param {number} radius the radius of the updraft
  84061. * @param {number} strength the strength of the updraft
  84062. * @param {number} height the height of the updraft
  84063. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84064. */
  84065. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84066. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84067. if (!this._physicsEngine) {
  84068. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84069. return null;
  84070. }
  84071. if (this._physicsEngine.getImpostors().length === 0) {
  84072. return null;
  84073. }
  84074. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84075. event.dispose(false);
  84076. return event;
  84077. };
  84078. /**
  84079. * @param {Vector3} origin the of the vortex
  84080. * @param {number} radius the radius of the vortex
  84081. * @param {number} strength the strength of the vortex
  84082. * @param {number} height the height of the vortex
  84083. */
  84084. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84085. if (!this._physicsEngine) {
  84086. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84087. return null;
  84088. }
  84089. if (this._physicsEngine.getImpostors().length === 0) {
  84090. return null;
  84091. }
  84092. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84093. event.dispose(false);
  84094. return event;
  84095. };
  84096. return PhysicsHelper;
  84097. }());
  84098. BABYLON.PhysicsHelper = PhysicsHelper;
  84099. /***** Radial explosion *****/
  84100. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84101. function PhysicsRadialExplosionEvent(scene) {
  84102. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84103. this._rays = [];
  84104. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84105. this._scene = scene;
  84106. }
  84107. /**
  84108. * Returns the data related to the radial explosion event (sphere & rays).
  84109. * @returns {PhysicsRadialExplosionEventData}
  84110. */
  84111. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84112. this._dataFetched = true;
  84113. return {
  84114. sphere: this._sphere,
  84115. rays: this._rays,
  84116. };
  84117. };
  84118. /**
  84119. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84120. * @param impostor
  84121. * @param {Vector3} origin the origin of the explosion
  84122. * @param {number} radius the explosion radius
  84123. * @param {number} strength the explosion strength
  84124. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84125. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84126. */
  84127. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84128. if (impostor.mass === 0) {
  84129. return null;
  84130. }
  84131. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84132. return null;
  84133. }
  84134. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84135. return null;
  84136. }
  84137. var impostorObjectCenter = impostor.getObjectCenter();
  84138. var direction = impostorObjectCenter.subtract(origin);
  84139. var ray = new BABYLON.Ray(origin, direction, radius);
  84140. this._rays.push(ray);
  84141. var hit = ray.intersectsMesh(impostor.object);
  84142. var contactPoint = hit.pickedPoint;
  84143. if (!contactPoint) {
  84144. return null;
  84145. }
  84146. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84147. if (distanceFromOrigin > radius) {
  84148. return null;
  84149. }
  84150. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84151. ? strength
  84152. : strength * (1 - (distanceFromOrigin / radius));
  84153. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84154. return { force: force, contactPoint: contactPoint };
  84155. };
  84156. /**
  84157. * Disposes the sphere.
  84158. * @param {bolean} force
  84159. */
  84160. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84161. var _this = this;
  84162. if (force === void 0) { force = true; }
  84163. if (force) {
  84164. this._sphere.dispose();
  84165. }
  84166. else {
  84167. setTimeout(function () {
  84168. if (!_this._dataFetched) {
  84169. _this._sphere.dispose();
  84170. }
  84171. }, 0);
  84172. }
  84173. };
  84174. /*** Helpers ***/
  84175. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84176. if (!this._sphere) {
  84177. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84178. this._sphere.isVisible = false;
  84179. }
  84180. };
  84181. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84182. var impostorObject = impostor.object;
  84183. this._prepareSphere();
  84184. this._sphere.position = origin;
  84185. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84186. this._sphere._updateBoundingInfo();
  84187. this._sphere.computeWorldMatrix(true);
  84188. return this._sphere.intersectsMesh(impostorObject, true);
  84189. };
  84190. return PhysicsRadialExplosionEvent;
  84191. }());
  84192. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84193. /***** Gravitational Field *****/
  84194. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84195. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84196. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84197. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84198. this._physicsHelper = physicsHelper;
  84199. this._scene = scene;
  84200. this._origin = origin;
  84201. this._radius = radius;
  84202. this._strength = strength;
  84203. this._falloff = falloff;
  84204. this._tickCallback = this._tick.bind(this);
  84205. }
  84206. /**
  84207. * Returns the data related to the gravitational field event (sphere).
  84208. * @returns {PhysicsGravitationalFieldEventData}
  84209. */
  84210. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84211. this._dataFetched = true;
  84212. return {
  84213. sphere: this._sphere,
  84214. };
  84215. };
  84216. /**
  84217. * Enables the gravitational field.
  84218. */
  84219. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84220. this._tickCallback.call(this);
  84221. this._scene.registerBeforeRender(this._tickCallback);
  84222. };
  84223. /**
  84224. * Disables the gravitational field.
  84225. */
  84226. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84227. this._scene.unregisterBeforeRender(this._tickCallback);
  84228. };
  84229. /**
  84230. * Disposes the sphere.
  84231. * @param {bolean} force
  84232. */
  84233. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84234. var _this = this;
  84235. if (force === void 0) { force = true; }
  84236. if (force) {
  84237. this._sphere.dispose();
  84238. }
  84239. else {
  84240. setTimeout(function () {
  84241. if (!_this._dataFetched) {
  84242. _this._sphere.dispose();
  84243. }
  84244. }, 0);
  84245. }
  84246. };
  84247. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84248. // Since the params won't change, we fetch the event only once
  84249. if (this._sphere) {
  84250. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84251. }
  84252. else {
  84253. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84254. if (radialExplosionEvent) {
  84255. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84256. }
  84257. }
  84258. };
  84259. return PhysicsGravitationalFieldEvent;
  84260. }());
  84261. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84262. /***** Updraft *****/
  84263. var PhysicsUpdraftEvent = /** @class */ (function () {
  84264. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84265. this._scene = _scene;
  84266. this._origin = _origin;
  84267. this._radius = _radius;
  84268. this._strength = _strength;
  84269. this._height = _height;
  84270. this._updraftMode = _updraftMode;
  84271. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84272. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84273. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84274. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84275. this._physicsEngine = this._scene.getPhysicsEngine();
  84276. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84277. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84278. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84279. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84280. }
  84281. this._tickCallback = this._tick.bind(this);
  84282. }
  84283. /**
  84284. * Returns the data related to the updraft event (cylinder).
  84285. * @returns {PhysicsUpdraftEventData}
  84286. */
  84287. PhysicsUpdraftEvent.prototype.getData = function () {
  84288. this._dataFetched = true;
  84289. return {
  84290. cylinder: this._cylinder,
  84291. };
  84292. };
  84293. /**
  84294. * Enables the updraft.
  84295. */
  84296. PhysicsUpdraftEvent.prototype.enable = function () {
  84297. this._tickCallback.call(this);
  84298. this._scene.registerBeforeRender(this._tickCallback);
  84299. };
  84300. /**
  84301. * Disables the cortex.
  84302. */
  84303. PhysicsUpdraftEvent.prototype.disable = function () {
  84304. this._scene.unregisterBeforeRender(this._tickCallback);
  84305. };
  84306. /**
  84307. * Disposes the sphere.
  84308. * @param {bolean} force
  84309. */
  84310. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84311. var _this = this;
  84312. if (force === void 0) { force = true; }
  84313. if (force) {
  84314. this._cylinder.dispose();
  84315. }
  84316. else {
  84317. setTimeout(function () {
  84318. if (!_this._dataFetched) {
  84319. _this._cylinder.dispose();
  84320. }
  84321. }, 0);
  84322. }
  84323. };
  84324. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84325. if (impostor.mass === 0) {
  84326. return null;
  84327. }
  84328. if (!this._intersectsWithCylinder(impostor)) {
  84329. return null;
  84330. }
  84331. var impostorObjectCenter = impostor.getObjectCenter();
  84332. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84333. var direction = this._originDirection;
  84334. }
  84335. else {
  84336. var direction = impostorObjectCenter.subtract(this._originTop);
  84337. }
  84338. var multiplier = this._strength * -1;
  84339. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84340. return { force: force, contactPoint: impostorObjectCenter };
  84341. };
  84342. PhysicsUpdraftEvent.prototype._tick = function () {
  84343. var _this = this;
  84344. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84345. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84346. if (!impostorForceAndContactPoint) {
  84347. return;
  84348. }
  84349. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84350. });
  84351. };
  84352. /*** Helpers ***/
  84353. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84354. if (!this._cylinder) {
  84355. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84356. height: this._height,
  84357. diameter: this._radius * 2,
  84358. }, this._scene);
  84359. this._cylinder.isVisible = false;
  84360. }
  84361. };
  84362. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84363. var impostorObject = impostor.object;
  84364. this._prepareCylinder();
  84365. this._cylinder.position = this._cylinderPosition;
  84366. return this._cylinder.intersectsMesh(impostorObject, true);
  84367. };
  84368. return PhysicsUpdraftEvent;
  84369. }());
  84370. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84371. /***** Vortex *****/
  84372. var PhysicsVortexEvent = /** @class */ (function () {
  84373. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84374. this._scene = _scene;
  84375. this._origin = _origin;
  84376. this._radius = _radius;
  84377. this._strength = _strength;
  84378. this._height = _height;
  84379. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84380. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84381. this._updraftMultiplier = 0.02;
  84382. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84383. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84384. this._physicsEngine = this._scene.getPhysicsEngine();
  84385. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84386. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84387. this._tickCallback = this._tick.bind(this);
  84388. }
  84389. /**
  84390. * Returns the data related to the vortex event (cylinder).
  84391. * @returns {PhysicsVortexEventData}
  84392. */
  84393. PhysicsVortexEvent.prototype.getData = function () {
  84394. this._dataFetched = true;
  84395. return {
  84396. cylinder: this._cylinder,
  84397. };
  84398. };
  84399. /**
  84400. * Enables the vortex.
  84401. */
  84402. PhysicsVortexEvent.prototype.enable = function () {
  84403. this._tickCallback.call(this);
  84404. this._scene.registerBeforeRender(this._tickCallback);
  84405. };
  84406. /**
  84407. * Disables the cortex.
  84408. */
  84409. PhysicsVortexEvent.prototype.disable = function () {
  84410. this._scene.unregisterBeforeRender(this._tickCallback);
  84411. };
  84412. /**
  84413. * Disposes the sphere.
  84414. * @param {bolean} force
  84415. */
  84416. PhysicsVortexEvent.prototype.dispose = function (force) {
  84417. var _this = this;
  84418. if (force === void 0) { force = true; }
  84419. if (force) {
  84420. this._cylinder.dispose();
  84421. }
  84422. else {
  84423. setTimeout(function () {
  84424. if (!_this._dataFetched) {
  84425. _this._cylinder.dispose();
  84426. }
  84427. }, 0);
  84428. }
  84429. };
  84430. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84431. if (impostor.mass === 0) {
  84432. return null;
  84433. }
  84434. if (!this._intersectsWithCylinder(impostor)) {
  84435. return null;
  84436. }
  84437. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84438. return null;
  84439. }
  84440. var impostorObjectCenter = impostor.getObjectCenter();
  84441. 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)
  84442. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84443. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84444. var hit = ray.intersectsMesh(impostor.object);
  84445. var contactPoint = hit.pickedPoint;
  84446. if (!contactPoint) {
  84447. return null;
  84448. }
  84449. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84450. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84451. var directionToOrigin = contactPoint.normalize();
  84452. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84453. directionToOrigin = directionToOrigin.negate();
  84454. }
  84455. // TODO: find a more physically based solution
  84456. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84457. var forceX = directionToOrigin.x * this._strength / 8;
  84458. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84459. var forceZ = directionToOrigin.z * this._strength / 8;
  84460. }
  84461. else {
  84462. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84463. var forceY = this._originTop.y * this._updraftMultiplier;
  84464. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84465. }
  84466. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84467. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84468. return { force: force, contactPoint: impostorObjectCenter };
  84469. };
  84470. PhysicsVortexEvent.prototype._tick = function () {
  84471. var _this = this;
  84472. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84473. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84474. if (!impostorForceAndContactPoint) {
  84475. return;
  84476. }
  84477. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84478. });
  84479. };
  84480. /*** Helpers ***/
  84481. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84482. if (!this._cylinder) {
  84483. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84484. height: this._height,
  84485. diameter: this._radius * 2,
  84486. }, this._scene);
  84487. this._cylinder.isVisible = false;
  84488. }
  84489. };
  84490. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84491. var impostorObject = impostor.object;
  84492. this._prepareCylinder();
  84493. this._cylinder.position = this._cylinderPosition;
  84494. return this._cylinder.intersectsMesh(impostorObject, true);
  84495. };
  84496. return PhysicsVortexEvent;
  84497. }());
  84498. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84499. /***** Enums *****/
  84500. /**
  84501. * The strenght of the force in correspondence to the distance of the affected object
  84502. */
  84503. var PhysicsRadialImpulseFalloff;
  84504. (function (PhysicsRadialImpulseFalloff) {
  84505. /** Defines that impulse is constant in strength across it's whole radius */
  84506. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84507. /** DEfines that impulse gets weaker if it's further from the origin */
  84508. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84509. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84510. /**
  84511. * The strenght of the force in correspondence to the distance of the affected object
  84512. */
  84513. var PhysicsUpdraftMode;
  84514. (function (PhysicsUpdraftMode) {
  84515. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84516. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84517. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84518. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84519. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84520. })(BABYLON || (BABYLON = {}));
  84521. //# sourceMappingURL=babylon.physicsHelper.js.map
  84522. var BABYLON;
  84523. (function (BABYLON) {
  84524. var CannonJSPlugin = /** @class */ (function () {
  84525. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84526. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84527. if (iterations === void 0) { iterations = 10; }
  84528. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84529. this.name = "CannonJSPlugin";
  84530. this._physicsMaterials = new Array();
  84531. this._fixedTimeStep = 1 / 60;
  84532. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84533. this.BJSCANNON = CANNON;
  84534. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84535. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84536. this._tmpPosition = BABYLON.Vector3.Zero();
  84537. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84538. this._tmpUnityRotation = new BABYLON.Quaternion();
  84539. if (!this.isSupported()) {
  84540. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84541. return;
  84542. }
  84543. this._extendNamespace();
  84544. this.world = new this.BJSCANNON.World();
  84545. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84546. this.world.solver.iterations = iterations;
  84547. }
  84548. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84549. this.world.gravity.copy(gravity);
  84550. };
  84551. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84552. this._fixedTimeStep = timeStep;
  84553. };
  84554. CannonJSPlugin.prototype.getTimeStep = function () {
  84555. return this._fixedTimeStep;
  84556. };
  84557. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84558. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84559. };
  84560. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84561. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84562. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84563. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84564. };
  84565. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84566. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84567. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84568. impostor.physicsBody.applyForce(impulse, worldPoint);
  84569. };
  84570. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84571. //parent-child relationship. Does this impostor has a parent impostor?
  84572. if (impostor.parent) {
  84573. if (impostor.physicsBody) {
  84574. this.removePhysicsBody(impostor);
  84575. //TODO is that needed?
  84576. impostor.forceUpdate();
  84577. }
  84578. return;
  84579. }
  84580. //should a new body be created for this impostor?
  84581. if (impostor.isBodyInitRequired()) {
  84582. var shape = this._createShape(impostor);
  84583. //unregister events, if body is being changed
  84584. var oldBody = impostor.physicsBody;
  84585. if (oldBody) {
  84586. this.removePhysicsBody(impostor);
  84587. }
  84588. //create the body and material
  84589. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84590. var bodyCreationObject = {
  84591. mass: impostor.getParam("mass"),
  84592. material: material
  84593. };
  84594. // A simple extend, in case native options were used.
  84595. var nativeOptions = impostor.getParam("nativeOptions");
  84596. for (var key in nativeOptions) {
  84597. if (nativeOptions.hasOwnProperty(key)) {
  84598. bodyCreationObject[key] = nativeOptions[key];
  84599. }
  84600. }
  84601. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84602. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84603. this.world.addEventListener("preStep", impostor.beforeStep);
  84604. this.world.addEventListener("postStep", impostor.afterStep);
  84605. impostor.physicsBody.addShape(shape);
  84606. this.world.add(impostor.physicsBody);
  84607. //try to keep the body moving in the right direction by taking old properties.
  84608. //Should be tested!
  84609. if (oldBody) {
  84610. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84611. impostor.physicsBody[param].copy(oldBody[param]);
  84612. });
  84613. }
  84614. this._processChildMeshes(impostor);
  84615. }
  84616. //now update the body's transformation
  84617. this._updatePhysicsBodyTransformation(impostor);
  84618. };
  84619. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84620. var _this = this;
  84621. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84622. var currentRotation = mainImpostor.object.rotationQuaternion;
  84623. if (meshChildren.length) {
  84624. var processMesh = function (localPosition, mesh) {
  84625. if (!currentRotation || !mesh.rotationQuaternion) {
  84626. return;
  84627. }
  84628. var childImpostor = mesh.getPhysicsImpostor();
  84629. if (childImpostor) {
  84630. var parent = childImpostor.parent;
  84631. if (parent !== mainImpostor) {
  84632. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84633. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84634. if (childImpostor.physicsBody) {
  84635. _this.removePhysicsBody(childImpostor);
  84636. childImpostor.physicsBody = null;
  84637. }
  84638. childImpostor.parent = mainImpostor;
  84639. childImpostor.resetUpdateFlags();
  84640. 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));
  84641. //Add the mass of the children.
  84642. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84643. }
  84644. }
  84645. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84646. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84647. };
  84648. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84649. }
  84650. };
  84651. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84652. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84653. this.world.removeEventListener("preStep", impostor.beforeStep);
  84654. this.world.removeEventListener("postStep", impostor.afterStep);
  84655. this.world.remove(impostor.physicsBody);
  84656. };
  84657. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84658. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84659. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84660. if (!mainBody || !connectedBody) {
  84661. return;
  84662. }
  84663. var constraint;
  84664. var jointData = impostorJoint.joint.jointData;
  84665. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84666. var constraintData = {
  84667. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84668. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84669. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84670. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84671. maxForce: jointData.nativeParams.maxForce,
  84672. collideConnected: !!jointData.collision
  84673. };
  84674. switch (impostorJoint.joint.type) {
  84675. case BABYLON.PhysicsJoint.HingeJoint:
  84676. case BABYLON.PhysicsJoint.Hinge2Joint:
  84677. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84678. break;
  84679. case BABYLON.PhysicsJoint.DistanceJoint:
  84680. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84681. break;
  84682. case BABYLON.PhysicsJoint.SpringJoint:
  84683. var springData = jointData;
  84684. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84685. restLength: springData.length,
  84686. stiffness: springData.stiffness,
  84687. damping: springData.damping,
  84688. localAnchorA: constraintData.pivotA,
  84689. localAnchorB: constraintData.pivotB
  84690. });
  84691. break;
  84692. case BABYLON.PhysicsJoint.LockJoint:
  84693. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84694. break;
  84695. case BABYLON.PhysicsJoint.PointToPointJoint:
  84696. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84697. default:
  84698. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84699. break;
  84700. }
  84701. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84702. constraint.collideConnected = !!jointData.collision;
  84703. impostorJoint.joint.physicsJoint = constraint;
  84704. //don't add spring as constraint, as it is not one.
  84705. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84706. this.world.addConstraint(constraint);
  84707. }
  84708. else {
  84709. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84710. constraint.applyForce();
  84711. });
  84712. }
  84713. };
  84714. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84715. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84716. };
  84717. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84718. var index;
  84719. var mat;
  84720. for (index = 0; index < this._physicsMaterials.length; index++) {
  84721. mat = this._physicsMaterials[index];
  84722. if (mat.friction === friction && mat.restitution === restitution) {
  84723. return mat;
  84724. }
  84725. }
  84726. var currentMat = new this.BJSCANNON.Material(name);
  84727. currentMat.friction = friction;
  84728. currentMat.restitution = restitution;
  84729. this._physicsMaterials.push(currentMat);
  84730. return currentMat;
  84731. };
  84732. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84733. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84734. };
  84735. CannonJSPlugin.prototype._createShape = function (impostor) {
  84736. var object = impostor.object;
  84737. var returnValue;
  84738. var extendSize = impostor.getObjectExtendSize();
  84739. switch (impostor.type) {
  84740. case BABYLON.PhysicsImpostor.SphereImpostor:
  84741. var radiusX = extendSize.x;
  84742. var radiusY = extendSize.y;
  84743. var radiusZ = extendSize.z;
  84744. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84745. break;
  84746. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84747. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84748. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84749. break;
  84750. case BABYLON.PhysicsImpostor.BoxImpostor:
  84751. var box = extendSize.scale(0.5);
  84752. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84753. break;
  84754. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84755. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84756. returnValue = new this.BJSCANNON.Plane();
  84757. break;
  84758. case BABYLON.PhysicsImpostor.MeshImpostor:
  84759. // should transform the vertex data to world coordinates!!
  84760. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84761. var rawFaces = object.getIndices ? object.getIndices() : [];
  84762. if (!rawVerts)
  84763. return;
  84764. // get only scale! so the object could transform correctly.
  84765. var oldPosition = object.position.clone();
  84766. var oldRotation = object.rotation && object.rotation.clone();
  84767. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84768. object.position.copyFromFloats(0, 0, 0);
  84769. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84770. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84771. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84772. var transform = object.computeWorldMatrix(true);
  84773. // convert rawVerts to object space
  84774. var temp = new Array();
  84775. var index;
  84776. for (index = 0; index < rawVerts.length; index += 3) {
  84777. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84778. }
  84779. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84780. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84781. //now set back the transformation!
  84782. object.position.copyFrom(oldPosition);
  84783. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84784. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84785. break;
  84786. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84787. var oldPosition2 = object.position.clone();
  84788. var oldRotation2 = object.rotation && object.rotation.clone();
  84789. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84790. object.position.copyFromFloats(0, 0, 0);
  84791. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84792. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84793. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84794. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84795. returnValue = this._createHeightmap(object);
  84796. object.position.copyFrom(oldPosition2);
  84797. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84798. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84799. object.computeWorldMatrix(true);
  84800. break;
  84801. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84802. returnValue = new this.BJSCANNON.Particle();
  84803. break;
  84804. }
  84805. return returnValue;
  84806. };
  84807. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84808. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84809. var transform = object.computeWorldMatrix(true);
  84810. // convert rawVerts to object space
  84811. var temp = new Array();
  84812. var index;
  84813. for (index = 0; index < pos.length; index += 3) {
  84814. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84815. }
  84816. pos = temp;
  84817. var matrix = new Array();
  84818. //For now pointDepth will not be used and will be automatically calculated.
  84819. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84820. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84821. var boundingInfo = object.getBoundingInfo();
  84822. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84823. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84824. var elementSize = dim * 2 / arraySize;
  84825. for (var i = 0; i < pos.length; i = i + 3) {
  84826. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84827. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84828. var y = -pos[i + 2] + minY;
  84829. if (!matrix[x]) {
  84830. matrix[x] = [];
  84831. }
  84832. if (!matrix[x][z]) {
  84833. matrix[x][z] = y;
  84834. }
  84835. matrix[x][z] = Math.max(y, matrix[x][z]);
  84836. }
  84837. for (var x = 0; x <= arraySize; ++x) {
  84838. if (!matrix[x]) {
  84839. var loc = 1;
  84840. while (!matrix[(x + loc) % arraySize]) {
  84841. loc++;
  84842. }
  84843. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84844. //console.log("missing x", x);
  84845. }
  84846. for (var z = 0; z <= arraySize; ++z) {
  84847. if (!matrix[x][z]) {
  84848. var loc = 1;
  84849. var newValue;
  84850. while (newValue === undefined) {
  84851. newValue = matrix[x][(z + loc++) % arraySize];
  84852. }
  84853. matrix[x][z] = newValue;
  84854. }
  84855. }
  84856. }
  84857. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84858. elementSize: elementSize
  84859. });
  84860. //For future reference, needed for body transformation
  84861. shape.minY = minY;
  84862. return shape;
  84863. };
  84864. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84865. var object = impostor.object;
  84866. //make sure it is updated...
  84867. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84868. // The delta between the mesh position and the mesh bounding box center
  84869. var bInfo = object.getBoundingInfo();
  84870. if (!bInfo)
  84871. return;
  84872. var center = impostor.getObjectCenter();
  84873. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84874. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84875. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84876. this._tmpPosition.copyFrom(center);
  84877. var quaternion = object.rotationQuaternion;
  84878. if (!quaternion) {
  84879. return;
  84880. }
  84881. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84882. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84883. //-90 DEG in X, precalculated
  84884. quaternion = quaternion.multiply(this._minus90X);
  84885. //Invert! (Precalculated, 90 deg in X)
  84886. //No need to clone. this will never change.
  84887. impostor.setDeltaRotation(this._plus90X);
  84888. }
  84889. //If it is a heightfield, if should be centered.
  84890. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84891. var mesh = object;
  84892. var boundingInfo = mesh.getBoundingInfo();
  84893. //calculate the correct body position:
  84894. var rotationQuaternion = mesh.rotationQuaternion;
  84895. mesh.rotationQuaternion = this._tmpUnityRotation;
  84896. mesh.computeWorldMatrix(true);
  84897. //get original center with no rotation
  84898. var c = center.clone();
  84899. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84900. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84901. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84902. mesh.setPreTransformMatrix(p);
  84903. mesh.computeWorldMatrix(true);
  84904. //calculate the translation
  84905. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84906. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84907. //add it inverted to the delta
  84908. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84909. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84910. //rotation is back
  84911. mesh.rotationQuaternion = rotationQuaternion;
  84912. mesh.setPreTransformMatrix(oldPivot);
  84913. mesh.computeWorldMatrix(true);
  84914. }
  84915. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84916. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84917. //this._tmpPosition.copyFrom(object.position);
  84918. }
  84919. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84920. //Now update the impostor object
  84921. impostor.physicsBody.position.copy(this._tmpPosition);
  84922. impostor.physicsBody.quaternion.copy(quaternion);
  84923. };
  84924. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84925. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84926. if (impostor.object.rotationQuaternion) {
  84927. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84928. }
  84929. };
  84930. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84931. impostor.physicsBody.position.copy(newPosition);
  84932. impostor.physicsBody.quaternion.copy(newRotation);
  84933. };
  84934. CannonJSPlugin.prototype.isSupported = function () {
  84935. return this.BJSCANNON !== undefined;
  84936. };
  84937. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84938. impostor.physicsBody.velocity.copy(velocity);
  84939. };
  84940. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84941. impostor.physicsBody.angularVelocity.copy(velocity);
  84942. };
  84943. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84944. var v = impostor.physicsBody.velocity;
  84945. if (!v) {
  84946. return null;
  84947. }
  84948. return new BABYLON.Vector3(v.x, v.y, v.z);
  84949. };
  84950. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84951. var v = impostor.physicsBody.angularVelocity;
  84952. if (!v) {
  84953. return null;
  84954. }
  84955. return new BABYLON.Vector3(v.x, v.y, v.z);
  84956. };
  84957. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84958. impostor.physicsBody.mass = mass;
  84959. impostor.physicsBody.updateMassProperties();
  84960. };
  84961. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84962. return impostor.physicsBody.mass;
  84963. };
  84964. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84965. return impostor.physicsBody.material.friction;
  84966. };
  84967. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84968. impostor.physicsBody.material.friction = friction;
  84969. };
  84970. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84971. return impostor.physicsBody.material.restitution;
  84972. };
  84973. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84974. impostor.physicsBody.material.restitution = restitution;
  84975. };
  84976. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84977. impostor.physicsBody.sleep();
  84978. };
  84979. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84980. impostor.physicsBody.wakeUp();
  84981. };
  84982. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84983. joint.physicsJoint.distance = maxDistance;
  84984. };
  84985. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84986. // if (!motorIndex) {
  84987. // joint.physicsJoint.enableMotor();
  84988. // }
  84989. // }
  84990. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84991. // if (!motorIndex) {
  84992. // joint.physicsJoint.disableMotor();
  84993. // }
  84994. // }
  84995. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84996. if (!motorIndex) {
  84997. joint.physicsJoint.enableMotor();
  84998. joint.physicsJoint.setMotorSpeed(speed);
  84999. if (maxForce) {
  85000. this.setLimit(joint, maxForce);
  85001. }
  85002. }
  85003. };
  85004. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85005. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85006. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85007. };
  85008. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85009. var body = impostor.physicsBody;
  85010. mesh.position.x = body.position.x;
  85011. mesh.position.y = body.position.y;
  85012. mesh.position.z = body.position.z;
  85013. if (mesh.rotationQuaternion) {
  85014. mesh.rotationQuaternion.x = body.quaternion.x;
  85015. mesh.rotationQuaternion.y = body.quaternion.y;
  85016. mesh.rotationQuaternion.z = body.quaternion.z;
  85017. mesh.rotationQuaternion.w = body.quaternion.w;
  85018. }
  85019. };
  85020. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85021. var shape = impostor.physicsBody.shapes[0];
  85022. return shape.boundingSphereRadius;
  85023. };
  85024. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85025. var shape = impostor.physicsBody.shapes[0];
  85026. result.x = shape.halfExtents.x * 2;
  85027. result.y = shape.halfExtents.y * 2;
  85028. result.z = shape.halfExtents.z * 2;
  85029. };
  85030. CannonJSPlugin.prototype.dispose = function () {
  85031. };
  85032. CannonJSPlugin.prototype._extendNamespace = function () {
  85033. //this will force cannon to execute at least one step when using interpolation
  85034. var step_tmp1 = new this.BJSCANNON.Vec3();
  85035. var Engine = this.BJSCANNON;
  85036. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85037. maxSubSteps = maxSubSteps || 10;
  85038. timeSinceLastCalled = timeSinceLastCalled || 0;
  85039. if (timeSinceLastCalled === 0) {
  85040. this.internalStep(dt);
  85041. this.time += dt;
  85042. }
  85043. else {
  85044. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85045. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85046. var t0 = performance.now();
  85047. for (var i = 0; i !== internalSteps; i++) {
  85048. this.internalStep(dt);
  85049. if (performance.now() - t0 > dt * 1000) {
  85050. break;
  85051. }
  85052. }
  85053. this.time += timeSinceLastCalled;
  85054. var h = this.time % dt;
  85055. var h_div_dt = h / dt;
  85056. var interpvelo = step_tmp1;
  85057. var bodies = this.bodies;
  85058. for (var j = 0; j !== bodies.length; j++) {
  85059. var b = bodies[j];
  85060. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85061. b.position.vsub(b.previousPosition, interpvelo);
  85062. interpvelo.scale(h_div_dt, interpvelo);
  85063. b.position.vadd(interpvelo, b.interpolatedPosition);
  85064. }
  85065. else {
  85066. b.interpolatedPosition.copy(b.position);
  85067. b.interpolatedQuaternion.copy(b.quaternion);
  85068. }
  85069. }
  85070. }
  85071. };
  85072. };
  85073. return CannonJSPlugin;
  85074. }());
  85075. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85076. })(BABYLON || (BABYLON = {}));
  85077. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85078. var BABYLON;
  85079. (function (BABYLON) {
  85080. var OimoJSPlugin = /** @class */ (function () {
  85081. function OimoJSPlugin(iterations) {
  85082. this.name = "OimoJSPlugin";
  85083. this._tmpImpostorsArray = [];
  85084. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85085. this.BJSOIMO = OIMO;
  85086. this.world = new this.BJSOIMO.World({
  85087. iterations: iterations
  85088. });
  85089. this.world.clear();
  85090. }
  85091. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85092. this.world.gravity.copy(gravity);
  85093. };
  85094. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85095. this.world.timeStep = timeStep;
  85096. };
  85097. OimoJSPlugin.prototype.getTimeStep = function () {
  85098. return this.world.timeStep;
  85099. };
  85100. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85101. var _this = this;
  85102. impostors.forEach(function (impostor) {
  85103. impostor.beforeStep();
  85104. });
  85105. this.world.step();
  85106. impostors.forEach(function (impostor) {
  85107. impostor.afterStep();
  85108. //update the ordered impostors array
  85109. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85110. });
  85111. //check for collisions
  85112. var contact = this.world.contacts;
  85113. while (contact !== null) {
  85114. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85115. contact = contact.next;
  85116. continue;
  85117. }
  85118. //is this body colliding with any other? get the impostor
  85119. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85120. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85121. if (!mainImpostor || !collidingImpostor) {
  85122. contact = contact.next;
  85123. continue;
  85124. }
  85125. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85126. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85127. contact = contact.next;
  85128. }
  85129. };
  85130. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85131. var mass = impostor.physicsBody.mass;
  85132. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85133. };
  85134. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85135. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85136. this.applyImpulse(impostor, force, contactPoint);
  85137. };
  85138. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85139. var _this = this;
  85140. //parent-child relationship. Does this impostor has a parent impostor?
  85141. if (impostor.parent) {
  85142. if (impostor.physicsBody) {
  85143. this.removePhysicsBody(impostor);
  85144. //TODO is that needed?
  85145. impostor.forceUpdate();
  85146. }
  85147. return;
  85148. }
  85149. if (impostor.isBodyInitRequired()) {
  85150. var bodyConfig = {
  85151. name: impostor.uniqueId,
  85152. //Oimo must have mass, also for static objects.
  85153. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85154. size: [],
  85155. type: [],
  85156. pos: [],
  85157. posShape: [],
  85158. rot: [],
  85159. rotShape: [],
  85160. move: impostor.getParam("mass") !== 0,
  85161. density: impostor.getParam("mass"),
  85162. friction: impostor.getParam("friction"),
  85163. restitution: impostor.getParam("restitution"),
  85164. //Supporting older versions of Oimo
  85165. world: this.world
  85166. };
  85167. var impostors = [impostor];
  85168. var addToArray = function (parent) {
  85169. if (!parent.getChildMeshes)
  85170. return;
  85171. parent.getChildMeshes().forEach(function (m) {
  85172. if (m.physicsImpostor) {
  85173. impostors.push(m.physicsImpostor);
  85174. //m.physicsImpostor._init();
  85175. }
  85176. });
  85177. };
  85178. addToArray(impostor.object);
  85179. var checkWithEpsilon_1 = function (value) {
  85180. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85181. };
  85182. impostors.forEach(function (i) {
  85183. if (!i.object.rotationQuaternion) {
  85184. return;
  85185. }
  85186. //get the correct bounding box
  85187. var oldQuaternion = i.object.rotationQuaternion;
  85188. var rot = oldQuaternion.toEulerAngles();
  85189. var extendSize = i.getObjectExtendSize();
  85190. var radToDeg = 57.295779513082320876;
  85191. if (i === impostor) {
  85192. var center = impostor.getObjectCenter();
  85193. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85194. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85195. //Can also use Array.prototype.push.apply
  85196. bodyConfig.pos.push(center.x);
  85197. bodyConfig.pos.push(center.y);
  85198. bodyConfig.pos.push(center.z);
  85199. bodyConfig.posShape.push(0, 0, 0);
  85200. //tmp solution
  85201. bodyConfig.rot.push(rot.x * radToDeg);
  85202. bodyConfig.rot.push(rot.y * radToDeg);
  85203. bodyConfig.rot.push(rot.z * radToDeg);
  85204. bodyConfig.rotShape.push(0, 0, 0);
  85205. }
  85206. else {
  85207. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85208. bodyConfig.posShape.push(localPosition.x);
  85209. bodyConfig.posShape.push(localPosition.y);
  85210. bodyConfig.posShape.push(localPosition.z);
  85211. bodyConfig.pos.push(0, 0, 0);
  85212. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85213. bodyConfig.rot.push(0);
  85214. bodyConfig.rot.push(0);
  85215. bodyConfig.rot.push(0);
  85216. bodyConfig.rotShape.push(rot.x * radToDeg);
  85217. bodyConfig.rotShape.push(rot.y * radToDeg);
  85218. bodyConfig.rotShape.push(rot.z * radToDeg);
  85219. }
  85220. // register mesh
  85221. switch (i.type) {
  85222. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85223. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85224. case BABYLON.PhysicsImpostor.SphereImpostor:
  85225. var radiusX = extendSize.x;
  85226. var radiusY = extendSize.y;
  85227. var radiusZ = extendSize.z;
  85228. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85229. bodyConfig.type.push('sphere');
  85230. //due to the way oimo works with compounds, add 3 times
  85231. bodyConfig.size.push(size);
  85232. bodyConfig.size.push(size);
  85233. bodyConfig.size.push(size);
  85234. break;
  85235. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85236. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85237. var sizeY = checkWithEpsilon_1(extendSize.y);
  85238. bodyConfig.type.push('cylinder');
  85239. bodyConfig.size.push(sizeX);
  85240. bodyConfig.size.push(sizeY);
  85241. //due to the way oimo works with compounds, add one more value.
  85242. bodyConfig.size.push(sizeY);
  85243. break;
  85244. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85245. case BABYLON.PhysicsImpostor.BoxImpostor:
  85246. default:
  85247. var sizeX = checkWithEpsilon_1(extendSize.x);
  85248. var sizeY = checkWithEpsilon_1(extendSize.y);
  85249. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85250. bodyConfig.type.push('box');
  85251. //if (i === impostor) {
  85252. bodyConfig.size.push(sizeX);
  85253. bodyConfig.size.push(sizeY);
  85254. bodyConfig.size.push(sizeZ);
  85255. //} else {
  85256. // bodyConfig.size.push(0,0,0);
  85257. //}
  85258. break;
  85259. }
  85260. //actually not needed, but hey...
  85261. i.object.rotationQuaternion = oldQuaternion;
  85262. });
  85263. impostor.physicsBody = this.world.add(bodyConfig);
  85264. }
  85265. else {
  85266. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85267. }
  85268. impostor.setDeltaPosition(this._tmpPositionVector);
  85269. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85270. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85271. };
  85272. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85273. //impostor.physicsBody.dispose();
  85274. //Same as : (older oimo versions)
  85275. this.world.removeRigidBody(impostor.physicsBody);
  85276. };
  85277. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85278. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85279. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85280. if (!mainBody || !connectedBody) {
  85281. return;
  85282. }
  85283. var jointData = impostorJoint.joint.jointData;
  85284. var options = jointData.nativeParams || {};
  85285. var type;
  85286. var nativeJointData = {
  85287. body1: mainBody,
  85288. body2: connectedBody,
  85289. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85290. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85291. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85292. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85293. min: options.min,
  85294. max: options.max,
  85295. collision: options.collision || jointData.collision,
  85296. spring: options.spring,
  85297. //supporting older version of Oimo
  85298. world: this.world
  85299. };
  85300. switch (impostorJoint.joint.type) {
  85301. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85302. type = "jointBall";
  85303. break;
  85304. case BABYLON.PhysicsJoint.SpringJoint:
  85305. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85306. var springData = jointData;
  85307. nativeJointData.min = springData.length || nativeJointData.min;
  85308. //Max should also be set, just make sure it is at least min
  85309. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85310. case BABYLON.PhysicsJoint.DistanceJoint:
  85311. type = "jointDistance";
  85312. nativeJointData.max = jointData.maxDistance;
  85313. break;
  85314. case BABYLON.PhysicsJoint.PrismaticJoint:
  85315. type = "jointPrisme";
  85316. break;
  85317. case BABYLON.PhysicsJoint.SliderJoint:
  85318. type = "jointSlide";
  85319. break;
  85320. case BABYLON.PhysicsJoint.WheelJoint:
  85321. type = "jointWheel";
  85322. break;
  85323. case BABYLON.PhysicsJoint.HingeJoint:
  85324. default:
  85325. type = "jointHinge";
  85326. break;
  85327. }
  85328. nativeJointData.type = type;
  85329. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85330. };
  85331. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85332. //Bug in Oimo prevents us from disposing a joint in the playground
  85333. //joint.joint.physicsJoint.dispose();
  85334. //So we will bruteforce it!
  85335. try {
  85336. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85337. }
  85338. catch (e) {
  85339. BABYLON.Tools.Warn(e);
  85340. }
  85341. };
  85342. OimoJSPlugin.prototype.isSupported = function () {
  85343. return this.BJSOIMO !== undefined;
  85344. };
  85345. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85346. if (!impostor.physicsBody.sleeping) {
  85347. //TODO check that
  85348. /*if (impostor.physicsBody.shapes.next) {
  85349. var parentShape = this._getLastShape(impostor.physicsBody);
  85350. impostor.object.position.copyFrom(parentShape.position);
  85351. console.log(parentShape.position);
  85352. } else {*/
  85353. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85354. //}
  85355. if (impostor.object.rotationQuaternion) {
  85356. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85357. }
  85358. }
  85359. };
  85360. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85361. var body = impostor.physicsBody;
  85362. body.position.copy(newPosition);
  85363. body.orientation.copy(newRotation);
  85364. body.syncShapes();
  85365. body.awake();
  85366. };
  85367. /*private _getLastShape(body: any): any {
  85368. var lastShape = body.shapes;
  85369. while (lastShape.next) {
  85370. lastShape = lastShape.next;
  85371. }
  85372. return lastShape;
  85373. }*/
  85374. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85375. impostor.physicsBody.linearVelocity.copy(velocity);
  85376. };
  85377. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85378. impostor.physicsBody.angularVelocity.copy(velocity);
  85379. };
  85380. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85381. var v = impostor.physicsBody.linearVelocity;
  85382. if (!v) {
  85383. return null;
  85384. }
  85385. return new BABYLON.Vector3(v.x, v.y, v.z);
  85386. };
  85387. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85388. var v = impostor.physicsBody.angularVelocity;
  85389. if (!v) {
  85390. return null;
  85391. }
  85392. return new BABYLON.Vector3(v.x, v.y, v.z);
  85393. };
  85394. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85395. var staticBody = mass === 0;
  85396. //this will actually set the body's density and not its mass.
  85397. //But this is how oimo treats the mass variable.
  85398. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85399. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85400. };
  85401. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85402. return impostor.physicsBody.shapes.density;
  85403. };
  85404. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85405. return impostor.physicsBody.shapes.friction;
  85406. };
  85407. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85408. impostor.physicsBody.shapes.friction = friction;
  85409. };
  85410. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85411. return impostor.physicsBody.shapes.restitution;
  85412. };
  85413. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85414. impostor.physicsBody.shapes.restitution = restitution;
  85415. };
  85416. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85417. impostor.physicsBody.sleep();
  85418. };
  85419. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85420. impostor.physicsBody.awake();
  85421. };
  85422. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85423. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85424. if (minDistance !== void 0) {
  85425. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85426. }
  85427. };
  85428. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85429. //TODO separate rotational and transational motors.
  85430. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85431. if (motor) {
  85432. motor.setMotor(speed, maxForce);
  85433. }
  85434. };
  85435. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85436. //TODO separate rotational and transational motors.
  85437. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85438. if (motor) {
  85439. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85440. }
  85441. };
  85442. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85443. var body = impostor.physicsBody;
  85444. mesh.position.x = body.position.x;
  85445. mesh.position.y = body.position.y;
  85446. mesh.position.z = body.position.z;
  85447. if (mesh.rotationQuaternion) {
  85448. mesh.rotationQuaternion.x = body.orientation.x;
  85449. mesh.rotationQuaternion.y = body.orientation.y;
  85450. mesh.rotationQuaternion.z = body.orientation.z;
  85451. mesh.rotationQuaternion.w = body.orientation.s;
  85452. }
  85453. };
  85454. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85455. return impostor.physicsBody.shapes.radius;
  85456. };
  85457. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85458. var shape = impostor.physicsBody.shapes;
  85459. result.x = shape.halfWidth * 2;
  85460. result.y = shape.halfHeight * 2;
  85461. result.z = shape.halfDepth * 2;
  85462. };
  85463. OimoJSPlugin.prototype.dispose = function () {
  85464. this.world.clear();
  85465. };
  85466. return OimoJSPlugin;
  85467. }());
  85468. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85469. })(BABYLON || (BABYLON = {}));
  85470. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85471. var BABYLON;
  85472. (function (BABYLON) {
  85473. /*
  85474. * Based on jsTGALoader - Javascript loader for TGA file
  85475. * By Vincent Thibault
  85476. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85477. */
  85478. var TGATools = /** @class */ (function () {
  85479. function TGATools() {
  85480. }
  85481. TGATools.GetTGAHeader = function (data) {
  85482. var offset = 0;
  85483. var header = {
  85484. id_length: data[offset++],
  85485. colormap_type: data[offset++],
  85486. image_type: data[offset++],
  85487. colormap_index: data[offset++] | data[offset++] << 8,
  85488. colormap_length: data[offset++] | data[offset++] << 8,
  85489. colormap_size: data[offset++],
  85490. origin: [
  85491. data[offset++] | data[offset++] << 8,
  85492. data[offset++] | data[offset++] << 8
  85493. ],
  85494. width: data[offset++] | data[offset++] << 8,
  85495. height: data[offset++] | data[offset++] << 8,
  85496. pixel_size: data[offset++],
  85497. flags: data[offset++]
  85498. };
  85499. return header;
  85500. };
  85501. TGATools.UploadContent = function (gl, data) {
  85502. // Not enough data to contain header ?
  85503. if (data.length < 19) {
  85504. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85505. return;
  85506. }
  85507. // Read Header
  85508. var offset = 18;
  85509. var header = TGATools.GetTGAHeader(data);
  85510. // Assume it's a valid Targa file.
  85511. if (header.id_length + offset > data.length) {
  85512. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85513. return;
  85514. }
  85515. // Skip not needed data
  85516. offset += header.id_length;
  85517. var use_rle = false;
  85518. var use_pal = false;
  85519. var use_grey = false;
  85520. // Get some informations.
  85521. switch (header.image_type) {
  85522. case TGATools._TYPE_RLE_INDEXED:
  85523. use_rle = true;
  85524. case TGATools._TYPE_INDEXED:
  85525. use_pal = true;
  85526. break;
  85527. case TGATools._TYPE_RLE_RGB:
  85528. use_rle = true;
  85529. case TGATools._TYPE_RGB:
  85530. // use_rgb = true;
  85531. break;
  85532. case TGATools._TYPE_RLE_GREY:
  85533. use_rle = true;
  85534. case TGATools._TYPE_GREY:
  85535. use_grey = true;
  85536. break;
  85537. }
  85538. var pixel_data;
  85539. // var numAlphaBits = header.flags & 0xf;
  85540. var pixel_size = header.pixel_size >> 3;
  85541. var pixel_total = header.width * header.height * pixel_size;
  85542. // Read palettes
  85543. var palettes;
  85544. if (use_pal) {
  85545. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85546. }
  85547. // Read LRE
  85548. if (use_rle) {
  85549. pixel_data = new Uint8Array(pixel_total);
  85550. var c, count, i;
  85551. var localOffset = 0;
  85552. var pixels = new Uint8Array(pixel_size);
  85553. while (offset < pixel_total && localOffset < pixel_total) {
  85554. c = data[offset++];
  85555. count = (c & 0x7f) + 1;
  85556. // RLE pixels
  85557. if (c & 0x80) {
  85558. // Bind pixel tmp array
  85559. for (i = 0; i < pixel_size; ++i) {
  85560. pixels[i] = data[offset++];
  85561. }
  85562. // Copy pixel array
  85563. for (i = 0; i < count; ++i) {
  85564. pixel_data.set(pixels, localOffset + i * pixel_size);
  85565. }
  85566. localOffset += pixel_size * count;
  85567. }
  85568. // Raw pixels
  85569. else {
  85570. count *= pixel_size;
  85571. for (i = 0; i < count; ++i) {
  85572. pixel_data[localOffset + i] = data[offset++];
  85573. }
  85574. localOffset += count;
  85575. }
  85576. }
  85577. }
  85578. // RAW Pixels
  85579. else {
  85580. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85581. }
  85582. // Load to texture
  85583. var x_start, y_start, x_step, y_step, y_end, x_end;
  85584. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85585. default:
  85586. case TGATools._ORIGIN_UL:
  85587. x_start = 0;
  85588. x_step = 1;
  85589. x_end = header.width;
  85590. y_start = 0;
  85591. y_step = 1;
  85592. y_end = header.height;
  85593. break;
  85594. case TGATools._ORIGIN_BL:
  85595. x_start = 0;
  85596. x_step = 1;
  85597. x_end = header.width;
  85598. y_start = header.height - 1;
  85599. y_step = -1;
  85600. y_end = -1;
  85601. break;
  85602. case TGATools._ORIGIN_UR:
  85603. x_start = header.width - 1;
  85604. x_step = -1;
  85605. x_end = -1;
  85606. y_start = 0;
  85607. y_step = 1;
  85608. y_end = header.height;
  85609. break;
  85610. case TGATools._ORIGIN_BR:
  85611. x_start = header.width - 1;
  85612. x_step = -1;
  85613. x_end = -1;
  85614. y_start = header.height - 1;
  85615. y_step = -1;
  85616. y_end = -1;
  85617. break;
  85618. }
  85619. // Load the specify method
  85620. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85621. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85622. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85623. };
  85624. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85625. var image = pixel_data, colormap = palettes;
  85626. var width = header.width, height = header.height;
  85627. var color, i = 0, x, y;
  85628. var imageData = new Uint8Array(width * height * 4);
  85629. for (y = y_start; y !== y_end; y += y_step) {
  85630. for (x = x_start; x !== x_end; x += x_step, i++) {
  85631. color = image[i];
  85632. imageData[(x + width * y) * 4 + 3] = 255;
  85633. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85634. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85635. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85636. }
  85637. }
  85638. return imageData;
  85639. };
  85640. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85641. var image = pixel_data;
  85642. var width = header.width, height = header.height;
  85643. var color, i = 0, x, y;
  85644. var imageData = new Uint8Array(width * height * 4);
  85645. for (y = y_start; y !== y_end; y += y_step) {
  85646. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85647. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85648. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85649. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85650. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85651. imageData[(x + width * y) * 4 + 0] = r;
  85652. imageData[(x + width * y) * 4 + 1] = g;
  85653. imageData[(x + width * y) * 4 + 2] = b;
  85654. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85655. }
  85656. }
  85657. return imageData;
  85658. };
  85659. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85660. var image = pixel_data;
  85661. var width = header.width, height = header.height;
  85662. var i = 0, x, y;
  85663. var imageData = new Uint8Array(width * height * 4);
  85664. for (y = y_start; y !== y_end; y += y_step) {
  85665. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85666. imageData[(x + width * y) * 4 + 3] = 255;
  85667. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85668. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85669. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85670. }
  85671. }
  85672. return imageData;
  85673. };
  85674. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85675. var image = pixel_data;
  85676. var width = header.width, height = header.height;
  85677. var i = 0, x, y;
  85678. var imageData = new Uint8Array(width * height * 4);
  85679. for (y = y_start; y !== y_end; y += y_step) {
  85680. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85681. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85682. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85683. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85684. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85685. }
  85686. }
  85687. return imageData;
  85688. };
  85689. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85690. var image = pixel_data;
  85691. var width = header.width, height = header.height;
  85692. var color, i = 0, x, y;
  85693. var imageData = new Uint8Array(width * height * 4);
  85694. for (y = y_start; y !== y_end; y += y_step) {
  85695. for (x = x_start; x !== x_end; x += x_step, i++) {
  85696. color = image[i];
  85697. imageData[(x + width * y) * 4 + 0] = color;
  85698. imageData[(x + width * y) * 4 + 1] = color;
  85699. imageData[(x + width * y) * 4 + 2] = color;
  85700. imageData[(x + width * y) * 4 + 3] = 255;
  85701. }
  85702. }
  85703. return imageData;
  85704. };
  85705. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85706. var image = pixel_data;
  85707. var width = header.width, height = header.height;
  85708. var i = 0, x, y;
  85709. var imageData = new Uint8Array(width * height * 4);
  85710. for (y = y_start; y !== y_end; y += y_step) {
  85711. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85712. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85713. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85714. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85715. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85716. }
  85717. }
  85718. return imageData;
  85719. };
  85720. //private static _TYPE_NO_DATA = 0;
  85721. TGATools._TYPE_INDEXED = 1;
  85722. TGATools._TYPE_RGB = 2;
  85723. TGATools._TYPE_GREY = 3;
  85724. TGATools._TYPE_RLE_INDEXED = 9;
  85725. TGATools._TYPE_RLE_RGB = 10;
  85726. TGATools._TYPE_RLE_GREY = 11;
  85727. TGATools._ORIGIN_MASK = 0x30;
  85728. TGATools._ORIGIN_SHIFT = 0x04;
  85729. TGATools._ORIGIN_BL = 0x00;
  85730. TGATools._ORIGIN_BR = 0x01;
  85731. TGATools._ORIGIN_UL = 0x02;
  85732. TGATools._ORIGIN_UR = 0x03;
  85733. return TGATools;
  85734. }());
  85735. BABYLON.TGATools = TGATools;
  85736. })(BABYLON || (BABYLON = {}));
  85737. //# sourceMappingURL=babylon.tga.js.map
  85738. var BABYLON;
  85739. (function (BABYLON) {
  85740. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85741. // All values and structures referenced from:
  85742. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85743. var DDS_MAGIC = 0x20534444;
  85744. var
  85745. //DDSD_CAPS = 0x1,
  85746. //DDSD_HEIGHT = 0x2,
  85747. //DDSD_WIDTH = 0x4,
  85748. //DDSD_PITCH = 0x8,
  85749. //DDSD_PIXELFORMAT = 0x1000,
  85750. DDSD_MIPMAPCOUNT = 0x20000;
  85751. //DDSD_LINEARSIZE = 0x80000,
  85752. //DDSD_DEPTH = 0x800000;
  85753. // var DDSCAPS_COMPLEX = 0x8,
  85754. // DDSCAPS_MIPMAP = 0x400000,
  85755. // DDSCAPS_TEXTURE = 0x1000;
  85756. var DDSCAPS2_CUBEMAP = 0x200;
  85757. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85758. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85759. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85760. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85761. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85762. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85763. // DDSCAPS2_VOLUME = 0x200000;
  85764. var
  85765. //DDPF_ALPHAPIXELS = 0x1,
  85766. //DDPF_ALPHA = 0x2,
  85767. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85768. //DDPF_YUV = 0x200,
  85769. DDPF_LUMINANCE = 0x20000;
  85770. function FourCCToInt32(value) {
  85771. return value.charCodeAt(0) +
  85772. (value.charCodeAt(1) << 8) +
  85773. (value.charCodeAt(2) << 16) +
  85774. (value.charCodeAt(3) << 24);
  85775. }
  85776. function Int32ToFourCC(value) {
  85777. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85778. }
  85779. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85780. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85781. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85782. var FOURCC_DX10 = FourCCToInt32("DX10");
  85783. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85784. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85785. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85786. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85787. var headerLengthInt = 31; // The header length in 32 bit ints
  85788. // Offsets into the header array
  85789. var off_magic = 0;
  85790. var off_size = 1;
  85791. var off_flags = 2;
  85792. var off_height = 3;
  85793. var off_width = 4;
  85794. var off_mipmapCount = 7;
  85795. var off_pfFlags = 20;
  85796. var off_pfFourCC = 21;
  85797. var off_RGBbpp = 22;
  85798. var off_RMask = 23;
  85799. var off_GMask = 24;
  85800. var off_BMask = 25;
  85801. var off_AMask = 26;
  85802. // var off_caps1 = 27;
  85803. var off_caps2 = 28;
  85804. // var off_caps3 = 29;
  85805. // var off_caps4 = 30;
  85806. var off_dxgiFormat = 32;
  85807. ;
  85808. var DDSTools = /** @class */ (function () {
  85809. function DDSTools() {
  85810. }
  85811. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85812. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85813. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85814. var mipmapCount = 1;
  85815. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85816. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85817. }
  85818. var fourCC = header[off_pfFourCC];
  85819. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85820. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85821. switch (fourCC) {
  85822. case FOURCC_D3DFMT_R16G16B16A16F:
  85823. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85824. break;
  85825. case FOURCC_D3DFMT_R32G32B32A32F:
  85826. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85827. break;
  85828. case FOURCC_DX10:
  85829. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85830. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85831. break;
  85832. }
  85833. }
  85834. return {
  85835. width: header[off_width],
  85836. height: header[off_height],
  85837. mipmapCount: mipmapCount,
  85838. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85839. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85840. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85841. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85842. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85843. dxgiFormat: dxgiFormat,
  85844. textureType: textureType
  85845. };
  85846. };
  85847. DDSTools._ToHalfFloat = function (value) {
  85848. if (!DDSTools._FloatView) {
  85849. DDSTools._FloatView = new Float32Array(1);
  85850. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85851. }
  85852. DDSTools._FloatView[0] = value;
  85853. var x = DDSTools._Int32View[0];
  85854. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85855. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85856. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85857. /* If zero, or denormal, or exponent underflows too much for a denormal
  85858. * half, return signed zero. */
  85859. if (e < 103) {
  85860. return bits;
  85861. }
  85862. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85863. if (e > 142) {
  85864. bits |= 0x7c00;
  85865. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85866. * not Inf, so make sure we set one mantissa bit too. */
  85867. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85868. return bits;
  85869. }
  85870. /* If exponent underflows but not too much, return a denormal */
  85871. if (e < 113) {
  85872. m |= 0x0800;
  85873. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85874. * to 1, which is OK. */
  85875. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85876. return bits;
  85877. }
  85878. bits |= ((e - 112) << 10) | (m >> 1);
  85879. bits += m & 1;
  85880. return bits;
  85881. };
  85882. DDSTools._FromHalfFloat = function (value) {
  85883. var s = (value & 0x8000) >> 15;
  85884. var e = (value & 0x7C00) >> 10;
  85885. var f = value & 0x03FF;
  85886. if (e === 0) {
  85887. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85888. }
  85889. else if (e == 0x1F) {
  85890. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85891. }
  85892. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85893. };
  85894. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85895. var destArray = new Float32Array(dataLength);
  85896. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85897. var index = 0;
  85898. for (var y = 0; y < height; y++) {
  85899. for (var x = 0; x < width; x++) {
  85900. var srcPos = (x + y * width) * 4;
  85901. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85902. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85903. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85904. if (DDSTools.StoreLODInAlphaChannel) {
  85905. destArray[index + 3] = lod;
  85906. }
  85907. else {
  85908. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85909. }
  85910. index += 4;
  85911. }
  85912. }
  85913. return destArray;
  85914. };
  85915. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85916. if (DDSTools.StoreLODInAlphaChannel) {
  85917. var destArray = new Uint16Array(dataLength);
  85918. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85919. var index = 0;
  85920. for (var y = 0; y < height; y++) {
  85921. for (var x = 0; x < width; x++) {
  85922. var srcPos = (x + y * width) * 4;
  85923. destArray[index] = srcData[srcPos];
  85924. destArray[index + 1] = srcData[srcPos + 1];
  85925. destArray[index + 2] = srcData[srcPos + 2];
  85926. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85927. index += 4;
  85928. }
  85929. }
  85930. return destArray;
  85931. }
  85932. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85933. };
  85934. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85935. if (DDSTools.StoreLODInAlphaChannel) {
  85936. var destArray = new Float32Array(dataLength);
  85937. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85938. var index = 0;
  85939. for (var y = 0; y < height; y++) {
  85940. for (var x = 0; x < width; x++) {
  85941. var srcPos = (x + y * width) * 4;
  85942. destArray[index] = srcData[srcPos];
  85943. destArray[index + 1] = srcData[srcPos + 1];
  85944. destArray[index + 2] = srcData[srcPos + 2];
  85945. destArray[index + 3] = lod;
  85946. index += 4;
  85947. }
  85948. }
  85949. return destArray;
  85950. }
  85951. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85952. };
  85953. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85954. var destArray = new Uint8Array(dataLength);
  85955. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85956. var index = 0;
  85957. for (var y = 0; y < height; y++) {
  85958. for (var x = 0; x < width; x++) {
  85959. var srcPos = (x + y * width) * 4;
  85960. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85961. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85962. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85963. if (DDSTools.StoreLODInAlphaChannel) {
  85964. destArray[index + 3] = lod;
  85965. }
  85966. else {
  85967. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85968. }
  85969. index += 4;
  85970. }
  85971. }
  85972. return destArray;
  85973. };
  85974. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85975. var destArray = new Uint8Array(dataLength);
  85976. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85977. var index = 0;
  85978. for (var y = 0; y < height; y++) {
  85979. for (var x = 0; x < width; x++) {
  85980. var srcPos = (x + y * width) * 4;
  85981. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85982. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85983. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85984. if (DDSTools.StoreLODInAlphaChannel) {
  85985. destArray[index + 3] = lod;
  85986. }
  85987. else {
  85988. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85989. }
  85990. index += 4;
  85991. }
  85992. }
  85993. return destArray;
  85994. };
  85995. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85996. var byteArray = new Uint8Array(dataLength);
  85997. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85998. var index = 0;
  85999. for (var y = 0; y < height; y++) {
  86000. for (var x = 0; x < width; x++) {
  86001. var srcPos = (x + y * width) * 4;
  86002. byteArray[index] = srcData[srcPos + rOffset];
  86003. byteArray[index + 1] = srcData[srcPos + gOffset];
  86004. byteArray[index + 2] = srcData[srcPos + bOffset];
  86005. byteArray[index + 3] = srcData[srcPos + aOffset];
  86006. index += 4;
  86007. }
  86008. }
  86009. return byteArray;
  86010. };
  86011. DDSTools._ExtractLongWordOrder = function (value) {
  86012. if (value === 0 || value === 255 || value === -16777216) {
  86013. return 0;
  86014. }
  86015. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86016. };
  86017. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86018. var byteArray = new Uint8Array(dataLength);
  86019. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86020. var index = 0;
  86021. for (var y = 0; y < height; y++) {
  86022. for (var x = 0; x < width; x++) {
  86023. var srcPos = (x + y * width) * 3;
  86024. byteArray[index] = srcData[srcPos + rOffset];
  86025. byteArray[index + 1] = srcData[srcPos + gOffset];
  86026. byteArray[index + 2] = srcData[srcPos + bOffset];
  86027. index += 3;
  86028. }
  86029. }
  86030. return byteArray;
  86031. };
  86032. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86033. var byteArray = new Uint8Array(dataLength);
  86034. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86035. var index = 0;
  86036. for (var y = 0; y < height; y++) {
  86037. for (var x = 0; x < width; x++) {
  86038. var srcPos = (x + y * width);
  86039. byteArray[index] = srcData[srcPos];
  86040. index++;
  86041. }
  86042. }
  86043. return byteArray;
  86044. };
  86045. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86046. if (lodIndex === void 0) { lodIndex = -1; }
  86047. var sphericalPolynomialFaces = null;
  86048. if (info.sphericalPolynomial) {
  86049. sphericalPolynomialFaces = new Array();
  86050. }
  86051. var ext = engine.getCaps().s3tc;
  86052. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86053. var fourCC, width, height, dataLength = 0, dataOffset;
  86054. var byteArray, mipmapCount, mip;
  86055. var internalFormat = 0;
  86056. var format = 0;
  86057. var blockBytes = 1;
  86058. if (header[off_magic] !== DDS_MAGIC) {
  86059. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86060. return;
  86061. }
  86062. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86063. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86064. return;
  86065. }
  86066. if (info.isCompressed && !ext) {
  86067. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86068. return;
  86069. }
  86070. var bpp = header[off_RGBbpp];
  86071. dataOffset = header[off_size] + 4;
  86072. var computeFormats = false;
  86073. if (info.isFourCC) {
  86074. fourCC = header[off_pfFourCC];
  86075. switch (fourCC) {
  86076. case FOURCC_DXT1:
  86077. blockBytes = 8;
  86078. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86079. break;
  86080. case FOURCC_DXT3:
  86081. blockBytes = 16;
  86082. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86083. break;
  86084. case FOURCC_DXT5:
  86085. blockBytes = 16;
  86086. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86087. break;
  86088. case FOURCC_D3DFMT_R16G16B16A16F:
  86089. computeFormats = true;
  86090. break;
  86091. case FOURCC_D3DFMT_R32G32B32A32F:
  86092. computeFormats = true;
  86093. break;
  86094. case FOURCC_DX10:
  86095. // There is an additionnal header so dataOffset need to be changed
  86096. dataOffset += 5 * 4; // 5 uints
  86097. var supported = false;
  86098. switch (info.dxgiFormat) {
  86099. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86100. computeFormats = true;
  86101. supported = true;
  86102. break;
  86103. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86104. info.isRGB = true;
  86105. info.isFourCC = false;
  86106. bpp = 32;
  86107. supported = true;
  86108. break;
  86109. }
  86110. if (supported) {
  86111. break;
  86112. }
  86113. default:
  86114. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86115. return;
  86116. }
  86117. }
  86118. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86119. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86120. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86121. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86122. if (computeFormats) {
  86123. format = engine._getWebGLTextureType(info.textureType);
  86124. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86125. }
  86126. mipmapCount = 1;
  86127. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86128. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86129. }
  86130. for (var face = 0; face < faces; face++) {
  86131. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86132. width = header[off_width];
  86133. height = header[off_height];
  86134. for (mip = 0; mip < mipmapCount; ++mip) {
  86135. if (lodIndex === -1 || lodIndex === mip) {
  86136. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86137. var i = (lodIndex === -1) ? mip : 0;
  86138. if (!info.isCompressed && info.isFourCC) {
  86139. dataLength = width * height * 4;
  86140. var floatArray = null;
  86141. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86142. if (bpp === 128) {
  86143. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86144. if (sphericalPolynomialFaces && i == 0) {
  86145. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86146. }
  86147. }
  86148. else if (bpp === 64) {
  86149. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86150. if (sphericalPolynomialFaces && i == 0) {
  86151. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86152. }
  86153. }
  86154. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86155. format = engine._getWebGLTextureType(info.textureType);
  86156. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86157. }
  86158. else {
  86159. if (bpp === 128) {
  86160. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86161. if (sphericalPolynomialFaces && i == 0) {
  86162. sphericalPolynomialFaces.push(floatArray);
  86163. }
  86164. }
  86165. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86166. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86167. if (sphericalPolynomialFaces && i == 0) {
  86168. sphericalPolynomialFaces.push(floatArray);
  86169. }
  86170. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86171. format = engine._getWebGLTextureType(info.textureType);
  86172. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86173. }
  86174. else { // 64
  86175. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86176. if (sphericalPolynomialFaces && i == 0) {
  86177. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86178. }
  86179. }
  86180. }
  86181. if (floatArray) {
  86182. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86183. }
  86184. }
  86185. else if (info.isRGB) {
  86186. if (bpp === 24) {
  86187. dataLength = width * height * 3;
  86188. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86189. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86190. }
  86191. else { // 32
  86192. dataLength = width * height * 4;
  86193. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86194. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86195. }
  86196. }
  86197. else if (info.isLuminance) {
  86198. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86199. var unpaddedRowSize = width;
  86200. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86201. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86202. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86203. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86204. }
  86205. else {
  86206. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86207. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86208. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86209. }
  86210. }
  86211. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86212. width *= 0.5;
  86213. height *= 0.5;
  86214. width = Math.max(1.0, width);
  86215. height = Math.max(1.0, height);
  86216. }
  86217. if (currentFace !== undefined) {
  86218. // Loading a single face
  86219. break;
  86220. }
  86221. }
  86222. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86223. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86224. size: header[off_width],
  86225. right: sphericalPolynomialFaces[0],
  86226. left: sphericalPolynomialFaces[1],
  86227. up: sphericalPolynomialFaces[2],
  86228. down: sphericalPolynomialFaces[3],
  86229. front: sphericalPolynomialFaces[4],
  86230. back: sphericalPolynomialFaces[5],
  86231. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86232. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86233. gammaSpace: false,
  86234. });
  86235. }
  86236. else {
  86237. info.sphericalPolynomial = undefined;
  86238. }
  86239. };
  86240. DDSTools.StoreLODInAlphaChannel = false;
  86241. return DDSTools;
  86242. }());
  86243. BABYLON.DDSTools = DDSTools;
  86244. })(BABYLON || (BABYLON = {}));
  86245. //# sourceMappingURL=babylon.dds.js.map
  86246. var BABYLON;
  86247. (function (BABYLON) {
  86248. /**
  86249. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86250. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86251. */
  86252. var KhronosTextureContainer = /** @class */ (function () {
  86253. /**
  86254. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86255. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86256. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86257. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86258. */
  86259. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86260. this.arrayBuffer = arrayBuffer;
  86261. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86262. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86263. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86264. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86265. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86266. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86267. BABYLON.Tools.Error("texture missing KTX identifier");
  86268. return;
  86269. }
  86270. // load the reset of the header in native 32 bit int
  86271. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86272. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86273. var oppositeEndianess = header[0] === 0x01020304;
  86274. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86275. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86276. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86277. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86278. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86279. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86280. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86281. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86282. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86283. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86284. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86285. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86286. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86287. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86288. if (this.glType !== 0) {
  86289. BABYLON.Tools.Error("only compressed formats currently supported");
  86290. return;
  86291. }
  86292. else {
  86293. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86294. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86295. }
  86296. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86297. BABYLON.Tools.Error("only 2D textures currently supported");
  86298. return;
  86299. }
  86300. if (this.numberOfArrayElements !== 0) {
  86301. BABYLON.Tools.Error("texture arrays not currently supported");
  86302. return;
  86303. }
  86304. if (this.numberOfFaces !== facesExpected) {
  86305. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86306. return;
  86307. }
  86308. // we now have a completely validated file, so could use existence of loadType as success
  86309. // would need to make this more elaborate & adjust checks above to support more than one load type
  86310. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86311. }
  86312. // not as fast hardware based, but will probably never need to use
  86313. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86314. return ((val & 0xFF) << 24)
  86315. | ((val & 0xFF00) << 8)
  86316. | ((val >> 8) & 0xFF00)
  86317. | ((val >> 24) & 0xFF);
  86318. };
  86319. /**
  86320. * It is assumed that the texture has already been created & is currently bound
  86321. */
  86322. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86323. switch (this.loadType) {
  86324. case KhronosTextureContainer.COMPRESSED_2D:
  86325. this._upload2DCompressedLevels(gl, loadMipmaps);
  86326. break;
  86327. case KhronosTextureContainer.TEX_2D:
  86328. case KhronosTextureContainer.COMPRESSED_3D:
  86329. case KhronosTextureContainer.TEX_3D:
  86330. }
  86331. };
  86332. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86333. // initialize width & height for level 1
  86334. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86335. var width = this.pixelWidth;
  86336. var height = this.pixelHeight;
  86337. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86338. for (var level = 0; level < mipmapCount; level++) {
  86339. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86340. for (var face = 0; face < this.numberOfFaces; face++) {
  86341. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86342. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86343. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86344. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86345. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86346. }
  86347. width = Math.max(1.0, width * 0.5);
  86348. height = Math.max(1.0, height * 0.5);
  86349. }
  86350. };
  86351. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86352. // load types
  86353. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86354. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86355. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86356. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86357. return KhronosTextureContainer;
  86358. }());
  86359. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86360. })(BABYLON || (BABYLON = {}));
  86361. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86362. var BABYLON;
  86363. (function (BABYLON) {
  86364. var Debug;
  86365. (function (Debug) {
  86366. /**
  86367. * Class used to render a debug view of a given skeleton
  86368. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86369. */
  86370. var SkeletonViewer = /** @class */ (function () {
  86371. /**
  86372. * Creates a new SkeletonViewer
  86373. * @param skeleton defines the skeleton to render
  86374. * @param mesh defines the mesh attached to the skeleton
  86375. * @param scene defines the hosting scene
  86376. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86377. * @param renderingGroupId defines the rendering group id to use with the viewer
  86378. */
  86379. function SkeletonViewer(
  86380. /** defines the skeleton to render */
  86381. skeleton,
  86382. /** defines the mesh attached to the skeleton */
  86383. mesh, scene,
  86384. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86385. autoUpdateBonesMatrices,
  86386. /** defines the rendering group id to use with the viewer */
  86387. renderingGroupId) {
  86388. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86389. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86390. this.skeleton = skeleton;
  86391. this.mesh = mesh;
  86392. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86393. this.renderingGroupId = renderingGroupId;
  86394. /** Gets or sets the color used to render the skeleton */
  86395. this.color = BABYLON.Color3.White();
  86396. this._debugLines = new Array();
  86397. this._isEnabled = false;
  86398. this._scene = scene;
  86399. this.update();
  86400. this._renderFunction = this.update.bind(this);
  86401. }
  86402. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86403. get: function () {
  86404. return this._isEnabled;
  86405. },
  86406. /** Gets or sets a boolean indicating if the viewer is enabled */
  86407. set: function (value) {
  86408. if (this._isEnabled === value) {
  86409. return;
  86410. }
  86411. this._isEnabled = value;
  86412. if (value) {
  86413. this._scene.registerBeforeRender(this._renderFunction);
  86414. }
  86415. else {
  86416. this._scene.unregisterBeforeRender(this._renderFunction);
  86417. }
  86418. },
  86419. enumerable: true,
  86420. configurable: true
  86421. });
  86422. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86423. if (x === void 0) { x = 0; }
  86424. if (y === void 0) { y = 0; }
  86425. if (z === void 0) { z = 0; }
  86426. var tmat = BABYLON.Tmp.Matrix[0];
  86427. var parentBone = bone.getParent();
  86428. tmat.copyFrom(bone.getLocalMatrix());
  86429. if (x !== 0 || y !== 0 || z !== 0) {
  86430. var tmat2 = BABYLON.Tmp.Matrix[1];
  86431. BABYLON.Matrix.IdentityToRef(tmat2);
  86432. tmat2.m[12] = x;
  86433. tmat2.m[13] = y;
  86434. tmat2.m[14] = z;
  86435. tmat2.multiplyToRef(tmat, tmat);
  86436. }
  86437. if (parentBone) {
  86438. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86439. }
  86440. tmat.multiplyToRef(meshMat, tmat);
  86441. position.x = tmat.m[12];
  86442. position.y = tmat.m[13];
  86443. position.z = tmat.m[14];
  86444. };
  86445. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86446. var len = bones.length;
  86447. var meshPos = this.mesh.position;
  86448. for (var i = 0; i < len; i++) {
  86449. var bone = bones[i];
  86450. var points = this._debugLines[i];
  86451. if (!points) {
  86452. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86453. this._debugLines[i] = points;
  86454. }
  86455. this._getBonePosition(points[0], bone, meshMat);
  86456. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86457. points[0].subtractInPlace(meshPos);
  86458. points[1].subtractInPlace(meshPos);
  86459. }
  86460. };
  86461. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86462. var len = bones.length;
  86463. var boneNum = 0;
  86464. var meshPos = this.mesh.position;
  86465. for (var i = len - 1; i >= 0; i--) {
  86466. var childBone = bones[i];
  86467. var parentBone = childBone.getParent();
  86468. if (!parentBone) {
  86469. continue;
  86470. }
  86471. var points = this._debugLines[boneNum];
  86472. if (!points) {
  86473. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86474. this._debugLines[boneNum] = points;
  86475. }
  86476. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86477. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86478. points[0].subtractInPlace(meshPos);
  86479. points[1].subtractInPlace(meshPos);
  86480. boneNum++;
  86481. }
  86482. };
  86483. /** Update the viewer to sync with current skeleton state */
  86484. SkeletonViewer.prototype.update = function () {
  86485. if (this.autoUpdateBonesMatrices) {
  86486. this.skeleton.computeAbsoluteTransforms();
  86487. }
  86488. if (this.skeleton.bones[0].length === undefined) {
  86489. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86490. }
  86491. else {
  86492. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86493. }
  86494. if (!this._debugMesh) {
  86495. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86496. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86497. }
  86498. else {
  86499. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86500. }
  86501. this._debugMesh.position.copyFrom(this.mesh.position);
  86502. this._debugMesh.color = this.color;
  86503. };
  86504. /** Release associated resources */
  86505. SkeletonViewer.prototype.dispose = function () {
  86506. if (this._debugMesh) {
  86507. this.isEnabled = false;
  86508. this._debugMesh.dispose();
  86509. this._debugMesh = null;
  86510. }
  86511. };
  86512. return SkeletonViewer;
  86513. }());
  86514. Debug.SkeletonViewer = SkeletonViewer;
  86515. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86516. })(BABYLON || (BABYLON = {}));
  86517. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86518. /**
  86519. * Module Debug contains the (visual) components to debug a scene correctly
  86520. */
  86521. var BABYLON;
  86522. (function (BABYLON) {
  86523. var Debug;
  86524. (function (Debug) {
  86525. /**
  86526. * The Axes viewer will show 3 axes in a specific point in space
  86527. */
  86528. var AxesViewer = /** @class */ (function () {
  86529. /**
  86530. * Creates a new AxesViewer
  86531. * @param scene defines the hosting scene
  86532. * @param scaleLines defines a number used to scale line length (1 by default)
  86533. */
  86534. function AxesViewer(scene, scaleLines) {
  86535. if (scaleLines === void 0) { scaleLines = 1; }
  86536. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86537. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86538. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86539. /**
  86540. * Gets or sets a number used to scale line length
  86541. */
  86542. this.scaleLines = 1;
  86543. this.scaleLines = scaleLines;
  86544. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86545. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86546. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86547. this._xmesh.renderingGroupId = 2;
  86548. this._ymesh.renderingGroupId = 2;
  86549. this._zmesh.renderingGroupId = 2;
  86550. this._xmesh.material.checkReadyOnlyOnce = true;
  86551. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86552. this._ymesh.material.checkReadyOnlyOnce = true;
  86553. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86554. this._zmesh.material.checkReadyOnlyOnce = true;
  86555. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86556. this.scene = scene;
  86557. }
  86558. /**
  86559. * Force the viewer to update
  86560. * @param position defines the position of the viewer
  86561. * @param xaxis defines the x axis of the viewer
  86562. * @param yaxis defines the y axis of the viewer
  86563. * @param zaxis defines the z axis of the viewer
  86564. */
  86565. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86566. var scaleLines = this.scaleLines;
  86567. if (this._xmesh) {
  86568. this._xmesh.position.copyFrom(position);
  86569. }
  86570. if (this._ymesh) {
  86571. this._ymesh.position.copyFrom(position);
  86572. }
  86573. if (this._zmesh) {
  86574. this._zmesh.position.copyFrom(position);
  86575. }
  86576. var point2 = this._xline[1];
  86577. point2.x = xaxis.x * scaleLines;
  86578. point2.y = xaxis.y * scaleLines;
  86579. point2.z = xaxis.z * scaleLines;
  86580. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86581. point2 = this._yline[1];
  86582. point2.x = yaxis.x * scaleLines;
  86583. point2.y = yaxis.y * scaleLines;
  86584. point2.z = yaxis.z * scaleLines;
  86585. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86586. point2 = this._zline[1];
  86587. point2.x = zaxis.x * scaleLines;
  86588. point2.y = zaxis.y * scaleLines;
  86589. point2.z = zaxis.z * scaleLines;
  86590. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86591. };
  86592. /** Releases resources */
  86593. AxesViewer.prototype.dispose = function () {
  86594. if (this._xmesh) {
  86595. this._xmesh.dispose();
  86596. }
  86597. if (this._ymesh) {
  86598. this._ymesh.dispose();
  86599. }
  86600. if (this._zmesh) {
  86601. this._zmesh.dispose();
  86602. }
  86603. this._xmesh = null;
  86604. this._ymesh = null;
  86605. this._zmesh = null;
  86606. this.scene = null;
  86607. };
  86608. return AxesViewer;
  86609. }());
  86610. Debug.AxesViewer = AxesViewer;
  86611. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86612. })(BABYLON || (BABYLON = {}));
  86613. //# sourceMappingURL=babylon.axesViewer.js.map
  86614. var BABYLON;
  86615. (function (BABYLON) {
  86616. var Debug;
  86617. (function (Debug) {
  86618. /**
  86619. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86620. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86621. */
  86622. var BoneAxesViewer = /** @class */ (function (_super) {
  86623. __extends(BoneAxesViewer, _super);
  86624. /**
  86625. * Creates a new BoneAxesViewer
  86626. * @param scene defines the hosting scene
  86627. * @param bone defines the target bone
  86628. * @param mesh defines the target mesh
  86629. * @param scaleLines defines a scaling factor for line length (1 by default)
  86630. */
  86631. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86632. if (scaleLines === void 0) { scaleLines = 1; }
  86633. var _this = _super.call(this, scene, scaleLines) || this;
  86634. /** Gets current position */
  86635. _this.pos = BABYLON.Vector3.Zero();
  86636. /** Gets direction of X axis */
  86637. _this.xaxis = BABYLON.Vector3.Zero();
  86638. /** Gets direction of Y axis */
  86639. _this.yaxis = BABYLON.Vector3.Zero();
  86640. /** Gets direction of Z axis */
  86641. _this.zaxis = BABYLON.Vector3.Zero();
  86642. _this.mesh = mesh;
  86643. _this.bone = bone;
  86644. return _this;
  86645. }
  86646. /**
  86647. * Force the viewer to update
  86648. */
  86649. BoneAxesViewer.prototype.update = function () {
  86650. if (!this.mesh || !this.bone) {
  86651. return;
  86652. }
  86653. var bone = this.bone;
  86654. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86655. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86656. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86657. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86658. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86659. };
  86660. /** Releases resources */
  86661. BoneAxesViewer.prototype.dispose = function () {
  86662. if (this.mesh) {
  86663. this.mesh = null;
  86664. this.bone = null;
  86665. _super.prototype.dispose.call(this);
  86666. }
  86667. };
  86668. return BoneAxesViewer;
  86669. }(Debug.AxesViewer));
  86670. Debug.BoneAxesViewer = BoneAxesViewer;
  86671. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86672. })(BABYLON || (BABYLON = {}));
  86673. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86674. var BABYLON;
  86675. (function (BABYLON) {
  86676. var RayHelper = /** @class */ (function () {
  86677. function RayHelper(ray) {
  86678. this.ray = ray;
  86679. }
  86680. RayHelper.CreateAndShow = function (ray, scene, color) {
  86681. var helper = new RayHelper(ray);
  86682. helper.show(scene, color);
  86683. return helper;
  86684. };
  86685. RayHelper.prototype.show = function (scene, color) {
  86686. if (!this._renderFunction && this.ray) {
  86687. var ray = this.ray;
  86688. this._renderFunction = this._render.bind(this);
  86689. this._scene = scene;
  86690. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86691. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86692. if (this._renderFunction) {
  86693. this._scene.registerBeforeRender(this._renderFunction);
  86694. }
  86695. }
  86696. if (color && this._renderLine) {
  86697. this._renderLine.color.copyFrom(color);
  86698. }
  86699. };
  86700. RayHelper.prototype.hide = function () {
  86701. if (this._renderFunction && this._scene) {
  86702. this._scene.unregisterBeforeRender(this._renderFunction);
  86703. this._scene = null;
  86704. this._renderFunction = null;
  86705. if (this._renderLine) {
  86706. this._renderLine.dispose();
  86707. this._renderLine = null;
  86708. }
  86709. this._renderPoints = [];
  86710. }
  86711. };
  86712. RayHelper.prototype._render = function () {
  86713. var ray = this.ray;
  86714. if (!ray) {
  86715. return;
  86716. }
  86717. var point = this._renderPoints[1];
  86718. var len = Math.min(ray.length, 1000000);
  86719. point.copyFrom(ray.direction);
  86720. point.scaleInPlace(len);
  86721. point.addInPlace(ray.origin);
  86722. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86723. };
  86724. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86725. this._attachedToMesh = mesh;
  86726. var ray = this.ray;
  86727. if (!ray) {
  86728. return;
  86729. }
  86730. if (!ray.direction) {
  86731. ray.direction = BABYLON.Vector3.Zero();
  86732. }
  86733. if (!ray.origin) {
  86734. ray.origin = BABYLON.Vector3.Zero();
  86735. }
  86736. if (length) {
  86737. ray.length = length;
  86738. }
  86739. if (!meshSpaceOrigin) {
  86740. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86741. }
  86742. if (!meshSpaceDirection) {
  86743. // -1 so that this will work with Mesh.lookAt
  86744. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86745. }
  86746. if (!this._meshSpaceDirection) {
  86747. this._meshSpaceDirection = meshSpaceDirection.clone();
  86748. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86749. }
  86750. else {
  86751. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86752. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86753. }
  86754. if (!this._updateToMeshFunction) {
  86755. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86756. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86757. }
  86758. this._updateToMesh();
  86759. };
  86760. RayHelper.prototype.detachFromMesh = function () {
  86761. if (this._attachedToMesh) {
  86762. if (this._updateToMeshFunction) {
  86763. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86764. }
  86765. this._attachedToMesh = null;
  86766. this._updateToMeshFunction = null;
  86767. }
  86768. };
  86769. RayHelper.prototype._updateToMesh = function () {
  86770. var ray = this.ray;
  86771. if (!this._attachedToMesh || !ray) {
  86772. return;
  86773. }
  86774. if (this._attachedToMesh._isDisposed) {
  86775. this.detachFromMesh();
  86776. return;
  86777. }
  86778. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86779. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86780. };
  86781. RayHelper.prototype.dispose = function () {
  86782. this.hide();
  86783. this.detachFromMesh();
  86784. this.ray = null;
  86785. };
  86786. return RayHelper;
  86787. }());
  86788. BABYLON.RayHelper = RayHelper;
  86789. })(BABYLON || (BABYLON = {}));
  86790. //# sourceMappingURL=babylon.rayHelper.js.map
  86791. var BABYLON;
  86792. (function (BABYLON) {
  86793. // load the inspector using require, if not present in the global namespace.
  86794. var DebugLayer = /** @class */ (function () {
  86795. function DebugLayer(scene) {
  86796. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86797. this._scene = scene;
  86798. // load inspector using require, if it doesn't exist on the global namespace.
  86799. this.onGlobalPropertyChange = new Array();
  86800. }
  86801. /** Creates the inspector window. */
  86802. DebugLayer.prototype._createInspector = function (config) {
  86803. if (config === void 0) { config = {}; }
  86804. var popup = config.popup || false;
  86805. var initialTab = config.initialTab || 0;
  86806. var parentElement = config.parentElement || null;
  86807. if (!this._inspector) {
  86808. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86809. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86810. } // else nothing to do,; instance is already existing
  86811. };
  86812. DebugLayer.prototype.isVisible = function () {
  86813. if (!this._inspector) {
  86814. return false;
  86815. }
  86816. return true;
  86817. };
  86818. DebugLayer.prototype.hide = function () {
  86819. if (this._inspector) {
  86820. try {
  86821. this._inspector.dispose();
  86822. }
  86823. catch (e) {
  86824. // If the inspector has been removed directly from the inspector tool
  86825. }
  86826. this._inspector = null;
  86827. }
  86828. };
  86829. /**
  86830. *
  86831. * Launch the debugLayer.
  86832. *
  86833. * initialTab:
  86834. * | Value | Tab Name |
  86835. * | --- | --- |
  86836. * | 0 | Scene |
  86837. * | 1 | Console |
  86838. * | 2 | Stats |
  86839. * | 3 | Textures |
  86840. * | 4 | Mesh |
  86841. * | 5 | Light |
  86842. * | 6 | Material |
  86843. * | 7 | GLTF |
  86844. * | 8 | GUI |
  86845. * | 9 | Physics |
  86846. * | 10 | Camera |
  86847. * | 11 | Audio |
  86848. *
  86849. */
  86850. DebugLayer.prototype.show = function (config) {
  86851. if (config === void 0) { config = {}; }
  86852. if (typeof this.BJSINSPECTOR == 'undefined') {
  86853. // Load inspector and add it to the DOM
  86854. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86855. }
  86856. else {
  86857. // Otherwise creates the inspector
  86858. this._createInspector(config);
  86859. }
  86860. };
  86861. /**
  86862. * Gets the active tab
  86863. * @return the index of the active tab or -1 if the inspector is hidden
  86864. */
  86865. DebugLayer.prototype.getActiveTab = function () {
  86866. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86867. };
  86868. DebugLayer.prototype.onGlobalPropertyChangeCallback = function (result) {
  86869. this.onGlobalPropertyChange.forEach(function (callback) {
  86870. callback(result);
  86871. });
  86872. };
  86873. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86874. return DebugLayer;
  86875. }());
  86876. BABYLON.DebugLayer = DebugLayer;
  86877. })(BABYLON || (BABYLON = {}));
  86878. //# sourceMappingURL=babylon.debugLayer.js.map
  86879. var BABYLON;
  86880. (function (BABYLON) {
  86881. var Debug;
  86882. (function (Debug) {
  86883. /**
  86884. * Used to show the physics impostor around the specific mesh
  86885. */
  86886. var PhysicsViewer = /** @class */ (function () {
  86887. /**
  86888. * Creates a new PhysicsViewer
  86889. * @param scene defines the hosting scene
  86890. */
  86891. function PhysicsViewer(scene) {
  86892. /** @hidden */
  86893. this._impostors = [];
  86894. /** @hidden */
  86895. this._meshes = [];
  86896. /** @hidden */
  86897. this._numMeshes = 0;
  86898. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86899. var physicEngine = this._scene.getPhysicsEngine();
  86900. if (physicEngine) {
  86901. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86902. }
  86903. }
  86904. /** @hidden */
  86905. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86906. var plugin = this._physicsEnginePlugin;
  86907. for (var i = 0; i < this._numMeshes; i++) {
  86908. var impostor = this._impostors[i];
  86909. if (!impostor) {
  86910. continue;
  86911. }
  86912. if (impostor.isDisposed) {
  86913. this.hideImpostor(this._impostors[i--]);
  86914. }
  86915. else {
  86916. var mesh = this._meshes[i];
  86917. if (mesh && plugin) {
  86918. plugin.syncMeshWithImpostor(mesh, impostor);
  86919. }
  86920. }
  86921. }
  86922. };
  86923. /**
  86924. * Renders a specified physic impostor
  86925. * @param impostor defines the impostor to render
  86926. */
  86927. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86928. if (!this._scene) {
  86929. return;
  86930. }
  86931. for (var i = 0; i < this._numMeshes; i++) {
  86932. if (this._impostors[i] == impostor) {
  86933. return;
  86934. }
  86935. }
  86936. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86937. if (debugMesh) {
  86938. this._impostors[this._numMeshes] = impostor;
  86939. this._meshes[this._numMeshes] = debugMesh;
  86940. if (this._numMeshes === 0) {
  86941. this._renderFunction = this._updateDebugMeshes.bind(this);
  86942. this._scene.registerBeforeRender(this._renderFunction);
  86943. }
  86944. this._numMeshes++;
  86945. }
  86946. };
  86947. /**
  86948. * Hides a specified physic impostor
  86949. * @param impostor defines the impostor to hide
  86950. */
  86951. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86952. if (!impostor || !this._scene) {
  86953. return;
  86954. }
  86955. var removed = false;
  86956. for (var i = 0; i < this._numMeshes; i++) {
  86957. if (this._impostors[i] == impostor) {
  86958. var mesh = this._meshes[i];
  86959. if (!mesh) {
  86960. continue;
  86961. }
  86962. this._scene.removeMesh(mesh);
  86963. mesh.dispose();
  86964. this._numMeshes--;
  86965. if (this._numMeshes > 0) {
  86966. this._meshes[i] = this._meshes[this._numMeshes];
  86967. this._impostors[i] = this._impostors[this._numMeshes];
  86968. this._meshes[this._numMeshes] = null;
  86969. this._impostors[this._numMeshes] = null;
  86970. }
  86971. else {
  86972. this._meshes[0] = null;
  86973. this._impostors[0] = null;
  86974. }
  86975. removed = true;
  86976. break;
  86977. }
  86978. }
  86979. if (removed && this._numMeshes === 0) {
  86980. this._scene.unregisterBeforeRender(this._renderFunction);
  86981. }
  86982. };
  86983. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86984. if (!this._debugMaterial) {
  86985. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86986. this._debugMaterial.wireframe = true;
  86987. }
  86988. return this._debugMaterial;
  86989. };
  86990. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86991. if (!this._debugBoxMesh) {
  86992. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86993. this._debugBoxMesh.renderingGroupId = 1;
  86994. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86995. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86996. scene.removeMesh(this._debugBoxMesh);
  86997. }
  86998. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86999. };
  87000. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87001. if (!this._debugSphereMesh) {
  87002. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87003. this._debugSphereMesh.renderingGroupId = 1;
  87004. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87005. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87006. scene.removeMesh(this._debugSphereMesh);
  87007. }
  87008. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87009. };
  87010. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87011. var mesh = null;
  87012. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87013. mesh = this._getDebugBoxMesh(scene);
  87014. impostor.getBoxSizeToRef(mesh.scaling);
  87015. }
  87016. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87017. mesh = this._getDebugSphereMesh(scene);
  87018. var radius = impostor.getRadius();
  87019. mesh.scaling.x = radius * 2;
  87020. mesh.scaling.y = radius * 2;
  87021. mesh.scaling.z = radius * 2;
  87022. }
  87023. return mesh;
  87024. };
  87025. /** Releases all resources */
  87026. PhysicsViewer.prototype.dispose = function () {
  87027. for (var i = 0; i < this._numMeshes; i++) {
  87028. this.hideImpostor(this._impostors[i]);
  87029. }
  87030. if (this._debugBoxMesh) {
  87031. this._debugBoxMesh.dispose();
  87032. }
  87033. if (this._debugSphereMesh) {
  87034. this._debugSphereMesh.dispose();
  87035. }
  87036. if (this._debugMaterial) {
  87037. this._debugMaterial.dispose();
  87038. }
  87039. this._impostors.length = 0;
  87040. this._scene = null;
  87041. this._physicsEnginePlugin = null;
  87042. };
  87043. return PhysicsViewer;
  87044. }());
  87045. Debug.PhysicsViewer = PhysicsViewer;
  87046. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87047. })(BABYLON || (BABYLON = {}));
  87048. //# sourceMappingURL=babylon.physicsViewer.js.map
  87049. var BABYLON;
  87050. (function (BABYLON) {
  87051. var BoundingBoxRenderer = /** @class */ (function () {
  87052. function BoundingBoxRenderer(scene) {
  87053. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87054. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87055. this.showBackLines = true;
  87056. this.renderList = new BABYLON.SmartArray(32);
  87057. this._vertexBuffers = {};
  87058. this._scene = scene;
  87059. }
  87060. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87061. if (this._colorShader) {
  87062. return;
  87063. }
  87064. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87065. attributes: [BABYLON.VertexBuffer.PositionKind],
  87066. uniforms: ["world", "viewProjection", "color"]
  87067. });
  87068. var engine = this._scene.getEngine();
  87069. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87070. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87071. this._createIndexBuffer();
  87072. };
  87073. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87074. var engine = this._scene.getEngine();
  87075. 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]);
  87076. };
  87077. BoundingBoxRenderer.prototype._rebuild = function () {
  87078. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87079. if (vb) {
  87080. vb._rebuild();
  87081. }
  87082. this._createIndexBuffer();
  87083. };
  87084. BoundingBoxRenderer.prototype.reset = function () {
  87085. this.renderList.reset();
  87086. };
  87087. BoundingBoxRenderer.prototype.render = function () {
  87088. if (this.renderList.length === 0) {
  87089. return;
  87090. }
  87091. this._prepareRessources();
  87092. if (!this._colorShader.isReady()) {
  87093. return;
  87094. }
  87095. var engine = this._scene.getEngine();
  87096. engine.setDepthWrite(false);
  87097. this._colorShader._preBind();
  87098. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87099. var boundingBox = this.renderList.data[boundingBoxIndex];
  87100. var min = boundingBox.minimum;
  87101. var max = boundingBox.maximum;
  87102. var diff = max.subtract(min);
  87103. var median = min.add(diff.scale(0.5));
  87104. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87105. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87106. .multiply(boundingBox.getWorldMatrix());
  87107. // VBOs
  87108. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87109. if (this.showBackLines) {
  87110. // Back
  87111. engine.setDepthFunctionToGreaterOrEqual();
  87112. this._scene.resetCachedMaterial();
  87113. this._colorShader.setColor4("color", this.backColor.toColor4());
  87114. this._colorShader.bind(worldMatrix);
  87115. // Draw order
  87116. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87117. }
  87118. // Front
  87119. engine.setDepthFunctionToLess();
  87120. this._scene.resetCachedMaterial();
  87121. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87122. this._colorShader.bind(worldMatrix);
  87123. // Draw order
  87124. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87125. }
  87126. this._colorShader.unbind();
  87127. engine.setDepthFunctionToLessOrEqual();
  87128. engine.setDepthWrite(true);
  87129. };
  87130. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87131. this._prepareRessources();
  87132. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87133. return;
  87134. }
  87135. var engine = this._scene.getEngine();
  87136. engine.setDepthWrite(false);
  87137. engine.setColorWrite(false);
  87138. this._colorShader._preBind();
  87139. var boundingBox = mesh._boundingInfo.boundingBox;
  87140. var min = boundingBox.minimum;
  87141. var max = boundingBox.maximum;
  87142. var diff = max.subtract(min);
  87143. var median = min.add(diff.scale(0.5));
  87144. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87145. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87146. .multiply(boundingBox.getWorldMatrix());
  87147. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87148. engine.setDepthFunctionToLess();
  87149. this._scene.resetCachedMaterial();
  87150. this._colorShader.bind(worldMatrix);
  87151. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87152. this._colorShader.unbind();
  87153. engine.setDepthFunctionToLessOrEqual();
  87154. engine.setDepthWrite(true);
  87155. engine.setColorWrite(true);
  87156. };
  87157. BoundingBoxRenderer.prototype.dispose = function () {
  87158. if (!this._colorShader) {
  87159. return;
  87160. }
  87161. this.renderList.dispose();
  87162. this._colorShader.dispose();
  87163. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87164. if (buffer) {
  87165. buffer.dispose();
  87166. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87167. }
  87168. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87169. };
  87170. return BoundingBoxRenderer;
  87171. }());
  87172. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87173. })(BABYLON || (BABYLON = {}));
  87174. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87175. var BABYLON;
  87176. (function (BABYLON) {
  87177. /**
  87178. * Renders a layer on top of an existing scene
  87179. */
  87180. var UtilityLayerRenderer = /** @class */ (function () {
  87181. /**
  87182. * Instantiates a UtilityLayerRenderer
  87183. * @param originalScene the original scene that will be rendered on top of
  87184. */
  87185. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87186. var _this = this;
  87187. this.originalScene = originalScene;
  87188. this._pointerCaptures = {};
  87189. this._lastPointerEvents = {};
  87190. /**
  87191. * If the utility layer should automatically be rendered on top of existing scene
  87192. */
  87193. this.shouldRender = true;
  87194. /**
  87195. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87196. */
  87197. this.onlyCheckPointerDownEvents = true;
  87198. /**
  87199. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87200. */
  87201. this.processAllEvents = false;
  87202. /**
  87203. * Observable raised when the pointer move from the utility layer scene to the main scene
  87204. */
  87205. this.onPointerOutObservable = new BABYLON.Observable();
  87206. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87207. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87208. originalScene.getEngine().scenes.pop();
  87209. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87210. this.utilityLayerScene.detachControl();
  87211. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87212. if (!_this.processAllEvents) {
  87213. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87214. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87215. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87216. return;
  87217. }
  87218. }
  87219. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87220. if (!prePointerInfo.ray && utilityScenePick) {
  87221. prePointerInfo.ray = utilityScenePick.ray;
  87222. }
  87223. // always fire the prepointer oversvable
  87224. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87225. // allow every non pointer down event to flow to the utility layer
  87226. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87227. if (!prePointerInfo.skipOnPointerObservable) {
  87228. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87229. }
  87230. var pointerEvent = (prePointerInfo.event);
  87231. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87232. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87233. }
  87234. return;
  87235. }
  87236. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87237. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87238. if (utilityScenePick && utilityScenePick.hit) {
  87239. if (!prePointerInfo.skipOnPointerObservable) {
  87240. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87241. }
  87242. prePointerInfo.skipOnPointerObservable = true;
  87243. }
  87244. }
  87245. else {
  87246. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87247. var pointerEvent = (prePointerInfo.event);
  87248. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87249. if (originalScenePick && utilityScenePick) {
  87250. if (utilityScenePick.distance === 0) {
  87251. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87252. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87253. }
  87254. }
  87255. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87256. if (!prePointerInfo.skipOnPointerObservable) {
  87257. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87258. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87259. }
  87260. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87261. }
  87262. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87263. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87264. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87265. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87266. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87267. }
  87268. }
  87269. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87270. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87271. }
  87272. }
  87273. }
  87274. });
  87275. // Render directly on top of existing scene without clearing
  87276. this.utilityLayerScene.autoClear = false;
  87277. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87278. if (_this.shouldRender) {
  87279. _this.render();
  87280. }
  87281. });
  87282. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87283. _this.dispose();
  87284. });
  87285. this._updateCamera();
  87286. }
  87287. /**
  87288. * Renders the utility layers scene on top of the original scene
  87289. */
  87290. UtilityLayerRenderer.prototype.render = function () {
  87291. this._updateCamera();
  87292. this.utilityLayerScene.render(false);
  87293. };
  87294. /**
  87295. * Disposes of the renderer
  87296. */
  87297. UtilityLayerRenderer.prototype.dispose = function () {
  87298. this.onPointerOutObservable.clear();
  87299. if (this._afterRenderObserver) {
  87300. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87301. }
  87302. if (this._sceneDisposeObserver) {
  87303. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87304. }
  87305. if (this._originalPointerObserver) {
  87306. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87307. }
  87308. this.utilityLayerScene.dispose();
  87309. };
  87310. UtilityLayerRenderer.prototype._updateCamera = function () {
  87311. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87312. };
  87313. return UtilityLayerRenderer;
  87314. }());
  87315. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87316. })(BABYLON || (BABYLON = {}));
  87317. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87318. //# sourceMappingURL=babylon.behavior.js.map
  87319. var BABYLON;
  87320. (function (BABYLON) {
  87321. /**
  87322. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87323. */
  87324. var PointerDragBehavior = /** @class */ (function () {
  87325. /**
  87326. * Creates a pointer drag behavior that can be attached to a mesh
  87327. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  87328. */
  87329. function PointerDragBehavior(options) {
  87330. this.options = options;
  87331. this._draggingID = -1;
  87332. // Debug mode will display drag planes to help visualize behavior
  87333. this._debugMode = false;
  87334. this._maxDragAngle = Math.PI / 5;
  87335. /**
  87336. * Fires each time the attached mesh is dragged with the pointer
  87337. * * delta between last drag position and current drag position in world space
  87338. * * dragDistance along the drag axis
  87339. * * dragPlaneNormal normal of the current drag plane used during the drag
  87340. * * dragPlanePoint in world space where the drag intersects the drag plane
  87341. */
  87342. this.onDragObservable = new BABYLON.Observable();
  87343. /**
  87344. * Fires each time a drag begins (eg. mouse down on mesh)
  87345. */
  87346. this.onDragStartObservable = new BABYLON.Observable();
  87347. /**
  87348. * Fires each time a drag ends (eg. mouse release after drag)
  87349. */
  87350. this.onDragEndObservable = new BABYLON.Observable();
  87351. /**
  87352. * If the attached mesh should be moved when dragged
  87353. */
  87354. this.moveAttached = true;
  87355. /**
  87356. * Mesh with the position where the drag plane should be placed
  87357. */
  87358. this._dragPlaneParent = null;
  87359. /**
  87360. * If the drag behavior will react to drag events
  87361. */
  87362. this.enabled = true;
  87363. var optionCount = 0;
  87364. if (options === undefined) {
  87365. options = {};
  87366. }
  87367. if (options.dragAxis) {
  87368. optionCount++;
  87369. }
  87370. if (options.dragPlaneNormal) {
  87371. optionCount++;
  87372. }
  87373. if (optionCount > 1) {
  87374. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87375. }
  87376. }
  87377. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87378. /**
  87379. * The name of the behavior
  87380. */
  87381. get: function () {
  87382. return "PointerDrag";
  87383. },
  87384. enumerable: true,
  87385. configurable: true
  87386. });
  87387. /**
  87388. * Initializes the behavior
  87389. */
  87390. PointerDragBehavior.prototype.init = function () { };
  87391. /**
  87392. * Attaches the drag behavior the passed in mesh
  87393. * @param ownerNode The mesh that will be dragged around once attached
  87394. */
  87395. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87396. var _this = this;
  87397. this._scene = ownerNode.getScene();
  87398. this._attachedNode = ownerNode;
  87399. // Initialize drag plane to not interfere with existing scene
  87400. if (!PointerDragBehavior._planeScene) {
  87401. if (this._debugMode) {
  87402. PointerDragBehavior._planeScene = this._scene;
  87403. }
  87404. else {
  87405. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87406. this._scene.getEngine().scenes.pop();
  87407. }
  87408. }
  87409. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87410. // State of the drag
  87411. var dragging = false;
  87412. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87413. var delta = new BABYLON.Vector3(0, 0, 0);
  87414. var dragLength = 0;
  87415. var pickPredicate = function (m) {
  87416. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87417. };
  87418. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87419. if (!_this.enabled) {
  87420. return;
  87421. }
  87422. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87423. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87424. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87425. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87426. if (pickedPoint) {
  87427. dragging = true;
  87428. _this._draggingID = pointerInfo.event.pointerId;
  87429. lastPosition.copyFrom(pickedPoint);
  87430. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87431. }
  87432. }
  87433. }
  87434. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87435. if (_this._draggingID == pointerInfo.event.pointerId) {
  87436. dragging = false;
  87437. _this._draggingID = -1;
  87438. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87439. }
  87440. }
  87441. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87442. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87443. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87444. // Get angle between drag plane and ray. Only update the drag plane at non steep angles to avoid jumps in delta position
  87445. var angle = Math.acos(BABYLON.Vector3.Dot(_this._dragPlane.forward, pointerInfo.pickInfo.ray.direction));
  87446. if (angle < _this._maxDragAngle) {
  87447. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87448. }
  87449. if (pickedPoint) {
  87450. // depending on the drag mode option drag accordingly
  87451. if (_this.options.dragAxis) {
  87452. // Convert local drag axis to world
  87453. var worldDragAxis = BABYLON.Vector3.TransformCoordinates(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix());
  87454. // Project delta drag from the drag plane onto the drag axis
  87455. dragLength = BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), worldDragAxis);
  87456. worldDragAxis.scaleToRef(dragLength, delta);
  87457. }
  87458. else {
  87459. dragLength = delta.length();
  87460. pickedPoint.subtractToRef(lastPosition, delta);
  87461. }
  87462. if (_this.moveAttached) {
  87463. _this._attachedNode.position.addInPlace(delta);
  87464. }
  87465. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward });
  87466. lastPosition.copyFrom(pickedPoint);
  87467. }
  87468. }
  87469. }
  87470. });
  87471. };
  87472. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87473. var _this = this;
  87474. if (!ray) {
  87475. return null;
  87476. }
  87477. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87478. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87479. return pickResult.pickedPoint;
  87480. }
  87481. else {
  87482. return null;
  87483. }
  87484. };
  87485. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87486. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87487. var pointA = this._dragPlaneParent ? this._dragPlaneParent.absolutePosition : this._attachedNode.absolutePosition;
  87488. if (this.options.dragAxis) {
  87489. var localAxis = BABYLON.Vector3.TransformCoordinates(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix());
  87490. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87491. var pointB = pointA.add(localAxis); // towards drag axis
  87492. var pointC = pointA.add(ray.origin.subtract(pointA).normalize()); // towards camera
  87493. // Get perpendicular line from direction to camera and drag axis
  87494. var lineA = pointB.subtract(pointA);
  87495. var lineB = pointC.subtract(pointA);
  87496. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87497. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87498. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87499. this._dragPlane.position.copyFrom(pointA);
  87500. this._dragPlane.lookAt(pointA.subtract(norm));
  87501. }
  87502. else if (this.options.dragPlaneNormal) {
  87503. this._dragPlane.position.copyFrom(pointA);
  87504. this._dragPlane.lookAt(pointA.subtract(this.options.dragPlaneNormal));
  87505. }
  87506. else {
  87507. this._dragPlane.position.copyFrom(pointA);
  87508. this._dragPlane.lookAt(ray.origin);
  87509. }
  87510. this._dragPlane.computeWorldMatrix(true);
  87511. };
  87512. /**
  87513. * Detaches the behavior from the mesh
  87514. */
  87515. PointerDragBehavior.prototype.detach = function () {
  87516. if (this._pointerObserver) {
  87517. this._scene.onPointerObservable.remove(this._pointerObserver);
  87518. }
  87519. };
  87520. return PointerDragBehavior;
  87521. }());
  87522. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87523. })(BABYLON || (BABYLON = {}));
  87524. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87525. var BABYLON;
  87526. (function (BABYLON) {
  87527. /**
  87528. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87529. */
  87530. var Gizmo = /** @class */ (function () {
  87531. /**
  87532. * Creates a gizmo
  87533. * @param gizmoLayer The utility layer the gizmo will be added to
  87534. */
  87535. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87536. var _this = this;
  87537. this.gizmoLayer = gizmoLayer;
  87538. /**
  87539. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  87540. */
  87541. this._updateScale = true;
  87542. this._interactionsEnabled = true;
  87543. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87544. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87545. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87546. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87547. _this._rootMesh.scaling.set(dist, dist, dist);
  87548. }
  87549. if (_this.attachedMesh) {
  87550. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87551. }
  87552. });
  87553. }
  87554. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87555. };
  87556. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87557. get: function () {
  87558. return this._interactionsEnabled;
  87559. },
  87560. /**
  87561. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87562. */
  87563. set: function (value) {
  87564. this._interactionsEnabled = value;
  87565. this._onInteractionsEnabledChanged(value);
  87566. },
  87567. enumerable: true,
  87568. configurable: true
  87569. });
  87570. /**
  87571. * Disposes of the gizmo
  87572. */
  87573. Gizmo.prototype.dispose = function () {
  87574. this._rootMesh.dispose();
  87575. if (this._beforeRenderObserver) {
  87576. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87577. }
  87578. };
  87579. return Gizmo;
  87580. }());
  87581. BABYLON.Gizmo = Gizmo;
  87582. })(BABYLON || (BABYLON = {}));
  87583. //# sourceMappingURL=babylon.gizmo.js.map
  87584. var BABYLON;
  87585. (function (BABYLON) {
  87586. /**
  87587. * Single axis drag gizmo
  87588. */
  87589. var AxisDragGizmo = /** @class */ (function (_super) {
  87590. __extends(AxisDragGizmo, _super);
  87591. /**
  87592. * Creates an AxisDragGizmo
  87593. * @param gizmoLayer The utility layer the gizmo will be added to
  87594. * @param dragAxis The axis which the gizmo will be able to drag on
  87595. * @param color The color of the gizmo
  87596. */
  87597. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87598. var _this = _super.call(this, gizmoLayer) || this;
  87599. // Create Material
  87600. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87601. coloredMaterial.disableLighting = true;
  87602. coloredMaterial.emissiveColor = color;
  87603. // Build mesh on root node
  87604. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87605. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87606. _this._rootMesh.addChild(arrowMesh);
  87607. _this._rootMesh.addChild(arrowTail);
  87608. // Position arrow pointing in its drag axis
  87609. arrowMesh.scaling.scaleInPlace(0.1);
  87610. arrowMesh.material = coloredMaterial;
  87611. arrowMesh.rotation.x = Math.PI / 2;
  87612. arrowMesh.position.z += 0.3;
  87613. arrowTail.rotation.x = Math.PI / 2;
  87614. arrowTail.material = coloredMaterial;
  87615. arrowTail.position.z += 0.2;
  87616. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87617. // Add drag behavior to handle events when the gizmo is dragged
  87618. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  87619. _this._dragBehavior.moveAttached = false;
  87620. _this._rootMesh.addBehavior(_this._dragBehavior);
  87621. _this._dragBehavior.onDragObservable.add(function (event) {
  87622. if (!_this.interactionsEnabled) {
  87623. return;
  87624. }
  87625. if (_this.attachedMesh) {
  87626. _this.attachedMesh.position.addInPlace(event.delta);
  87627. }
  87628. });
  87629. return _this;
  87630. }
  87631. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87632. this._dragBehavior.enabled = value;
  87633. };
  87634. /**
  87635. * Disposes of the gizmo
  87636. */
  87637. AxisDragGizmo.prototype.dispose = function () {
  87638. this._dragBehavior.detach();
  87639. _super.prototype.dispose.call(this);
  87640. };
  87641. return AxisDragGizmo;
  87642. }(BABYLON.Gizmo));
  87643. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87644. })(BABYLON || (BABYLON = {}));
  87645. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87646. var BABYLON;
  87647. (function (BABYLON) {
  87648. /**
  87649. * Single axis scale gizmo
  87650. */
  87651. var AxisScaleGizmo = /** @class */ (function (_super) {
  87652. __extends(AxisScaleGizmo, _super);
  87653. /**
  87654. * Creates an AxisScaleGizmo
  87655. * @param gizmoLayer The utility layer the gizmo will be added to
  87656. * @param dragAxis The axis which the gizmo will be able to scale on
  87657. * @param color The color of the gizmo
  87658. */
  87659. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87660. var _this = _super.call(this, gizmoLayer) || this;
  87661. // Create Material
  87662. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87663. coloredMaterial.disableLighting = true;
  87664. coloredMaterial.emissiveColor = color;
  87665. // Build mesh on root node
  87666. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87667. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87668. _this._rootMesh.addChild(arrowMesh);
  87669. _this._rootMesh.addChild(arrowTail);
  87670. // Position arrow pointing in its drag axis
  87671. arrowMesh.scaling.scaleInPlace(0.1);
  87672. arrowMesh.material = coloredMaterial;
  87673. arrowMesh.rotation.x = Math.PI / 2;
  87674. arrowMesh.position.z += 0.3;
  87675. arrowTail.rotation.x = Math.PI / 2;
  87676. arrowTail.material = coloredMaterial;
  87677. arrowTail.position.z += 0.2;
  87678. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87679. // Add drag behavior to handle events when the gizmo is dragged
  87680. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  87681. _this._dragBehavior.moveAttached = false;
  87682. _this._rootMesh.addBehavior(_this._dragBehavior);
  87683. _this._dragBehavior.onDragObservable.add(function (event) {
  87684. if (!_this.interactionsEnabled) {
  87685. return;
  87686. }
  87687. if (_this.attachedMesh) {
  87688. _this.attachedMesh.scaling.addInPlace(event.delta);
  87689. }
  87690. });
  87691. return _this;
  87692. }
  87693. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87694. this._dragBehavior.enabled = value;
  87695. };
  87696. /**
  87697. * Disposes of the gizmo
  87698. */
  87699. AxisScaleGizmo.prototype.dispose = function () {
  87700. this._dragBehavior.detach();
  87701. _super.prototype.dispose.call(this);
  87702. };
  87703. return AxisScaleGizmo;
  87704. }(BABYLON.Gizmo));
  87705. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87706. })(BABYLON || (BABYLON = {}));
  87707. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87708. var BABYLON;
  87709. (function (BABYLON) {
  87710. /**
  87711. * Single plane rotation gizmo
  87712. */
  87713. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87714. __extends(PlaneRotationGizmo, _super);
  87715. /**
  87716. * Creates a PlaneRotationGizmo
  87717. * @param gizmoLayer The utility layer the gizmo will be added to
  87718. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87719. * @param color The color of the gizmo
  87720. */
  87721. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87722. var _this = _super.call(this, gizmoLayer) || this;
  87723. // Create Material
  87724. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87725. coloredMaterial.disableLighting = true;
  87726. coloredMaterial.emissiveColor = color;
  87727. // Build mesh on root node
  87728. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87729. _this._rootMesh.addChild(rotationMesh);
  87730. // Position arrow pointing in its drag axis
  87731. rotationMesh.scaling.scaleInPlace(0.1);
  87732. rotationMesh.material = coloredMaterial;
  87733. rotationMesh.rotation.x = Math.PI / 2;
  87734. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87735. // Add drag behavior to handle events when the gizmo is dragged
  87736. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87737. _this._dragBehavior.moveAttached = false;
  87738. _this._rootMesh.addBehavior(_this._dragBehavior);
  87739. var lastDragPosition = null;
  87740. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87741. if (!_this.interactionsEnabled) {
  87742. return;
  87743. }
  87744. lastDragPosition = e.dragPlanePoint;
  87745. });
  87746. _this._dragBehavior.onDragObservable.add(function (event) {
  87747. if (!_this.interactionsEnabled) {
  87748. return;
  87749. }
  87750. if (_this.attachedMesh && lastDragPosition) {
  87751. if (!_this.attachedMesh.rotationQuaternion) {
  87752. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87753. }
  87754. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87755. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87756. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87757. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87758. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87759. var angle = Math.atan2(cross.length(), dot);
  87760. var up = planeNormal.clone();
  87761. // Flip up vector depending on which side the camera is on
  87762. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87763. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87764. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87765. up.scaleInPlace(-1);
  87766. }
  87767. }
  87768. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87769. if (halfCircleSide)
  87770. angle = -angle;
  87771. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87772. var quaternionCoefficient = Math.sin(angle / 2);
  87773. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87774. // Rotate selected mesh quaternion over fixed axis
  87775. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87776. lastDragPosition = event.dragPlanePoint;
  87777. }
  87778. });
  87779. return _this;
  87780. }
  87781. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87782. this._dragBehavior.enabled = value;
  87783. };
  87784. /**
  87785. * Disposes of the gizmo
  87786. */
  87787. PlaneRotationGizmo.prototype.dispose = function () {
  87788. this._dragBehavior.detach();
  87789. _super.prototype.dispose.call(this);
  87790. };
  87791. return PlaneRotationGizmo;
  87792. }(BABYLON.Gizmo));
  87793. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87794. })(BABYLON || (BABYLON = {}));
  87795. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87796. var BABYLON;
  87797. (function (BABYLON) {
  87798. /**
  87799. * Gizmo that enables dragging a mesh along 3 axis
  87800. */
  87801. var PositionGizmo = /** @class */ (function (_super) {
  87802. __extends(PositionGizmo, _super);
  87803. /**
  87804. * Creates a PositionGizmo
  87805. * @param gizmoLayer The utility layer the gizmo will be added to
  87806. */
  87807. function PositionGizmo(gizmoLayer) {
  87808. var _this = _super.call(this, gizmoLayer) || this;
  87809. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87810. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87811. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87812. return _this;
  87813. }
  87814. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87815. set: function (mesh) {
  87816. this._xDrag.attachedMesh = mesh;
  87817. this._yDrag.attachedMesh = mesh;
  87818. this._zDrag.attachedMesh = mesh;
  87819. },
  87820. enumerable: true,
  87821. configurable: true
  87822. });
  87823. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87824. this._xDrag.interactionsEnabled = value;
  87825. this._yDrag.interactionsEnabled = value;
  87826. this._zDrag.interactionsEnabled = value;
  87827. };
  87828. /**
  87829. * Disposes of the gizmo
  87830. */
  87831. PositionGizmo.prototype.dispose = function () {
  87832. this._xDrag.dispose();
  87833. this._yDrag.dispose();
  87834. this._zDrag.dispose();
  87835. };
  87836. return PositionGizmo;
  87837. }(BABYLON.Gizmo));
  87838. BABYLON.PositionGizmo = PositionGizmo;
  87839. })(BABYLON || (BABYLON = {}));
  87840. //# sourceMappingURL=babylon.positionGizmo.js.map
  87841. var BABYLON;
  87842. (function (BABYLON) {
  87843. /**
  87844. * Gizmo that enables rotating a mesh along 3 axis
  87845. */
  87846. var RotationGizmo = /** @class */ (function (_super) {
  87847. __extends(RotationGizmo, _super);
  87848. /**
  87849. * Creates a RotationGizmo
  87850. * @param gizmoLayer The utility layer the gizmo will be added to
  87851. */
  87852. function RotationGizmo(gizmoLayer) {
  87853. var _this = _super.call(this, gizmoLayer) || this;
  87854. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87855. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87856. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87857. return _this;
  87858. }
  87859. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87860. set: function (mesh) {
  87861. this._xDrag.attachedMesh = mesh;
  87862. this._yDrag.attachedMesh = mesh;
  87863. this._zDrag.attachedMesh = mesh;
  87864. },
  87865. enumerable: true,
  87866. configurable: true
  87867. });
  87868. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87869. this._xDrag.interactionsEnabled = value;
  87870. this._yDrag.interactionsEnabled = value;
  87871. this._zDrag.interactionsEnabled = value;
  87872. };
  87873. /**
  87874. * Disposes of the gizmo
  87875. */
  87876. RotationGizmo.prototype.dispose = function () {
  87877. this._xDrag.dispose();
  87878. this._yDrag.dispose();
  87879. this._zDrag.dispose();
  87880. };
  87881. return RotationGizmo;
  87882. }(BABYLON.Gizmo));
  87883. BABYLON.RotationGizmo = RotationGizmo;
  87884. })(BABYLON || (BABYLON = {}));
  87885. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87886. var BABYLON;
  87887. (function (BABYLON) {
  87888. /**
  87889. * Gizmo that enables scaling a mesh along 3 axis
  87890. */
  87891. var ScaleGizmo = /** @class */ (function (_super) {
  87892. __extends(ScaleGizmo, _super);
  87893. /**
  87894. * Creates a ScaleGizmo
  87895. * @param gizmoLayer The utility layer the gizmo will be added to
  87896. */
  87897. function ScaleGizmo(gizmoLayer) {
  87898. var _this = _super.call(this, gizmoLayer) || this;
  87899. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87900. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87901. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87902. return _this;
  87903. }
  87904. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87905. set: function (mesh) {
  87906. this._xDrag.attachedMesh = mesh;
  87907. this._yDrag.attachedMesh = mesh;
  87908. this._zDrag.attachedMesh = mesh;
  87909. },
  87910. enumerable: true,
  87911. configurable: true
  87912. });
  87913. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87914. this._xDrag.interactionsEnabled = value;
  87915. this._yDrag.interactionsEnabled = value;
  87916. this._zDrag.interactionsEnabled = value;
  87917. };
  87918. /**
  87919. * Disposes of the gizmo
  87920. */
  87921. ScaleGizmo.prototype.dispose = function () {
  87922. this._xDrag.dispose();
  87923. this._yDrag.dispose();
  87924. this._zDrag.dispose();
  87925. };
  87926. return ScaleGizmo;
  87927. }(BABYLON.Gizmo));
  87928. BABYLON.ScaleGizmo = ScaleGizmo;
  87929. })(BABYLON || (BABYLON = {}));
  87930. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87931. var BABYLON;
  87932. (function (BABYLON) {
  87933. /**
  87934. * Bounding box gizmo
  87935. */
  87936. var BoundingBoxGizmo = /** @class */ (function (_super) {
  87937. __extends(BoundingBoxGizmo, _super);
  87938. /**
  87939. * Creates an BoundingBoxGizmo
  87940. * @param gizmoLayer The utility layer the gizmo will be added to
  87941. * @param color The color of the gizmo
  87942. */
  87943. function BoundingBoxGizmo(gizmoLayer, color) {
  87944. var _this = _super.call(this, gizmoLayer) || this;
  87945. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  87946. _this._renderObserver = null;
  87947. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  87948. _this._updateScale = false;
  87949. // Create Material
  87950. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87951. coloredMaterial.disableLighting = true;
  87952. coloredMaterial.emissiveColor = color;
  87953. // Build bounding box out of lines
  87954. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87955. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  87956. var lines = [];
  87957. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  87958. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87959. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87960. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87961. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87962. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87963. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87964. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87965. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87966. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87967. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  87968. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  87969. lines.forEach(function (l) {
  87970. l.color = color;
  87971. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  87972. l.isPickable = false;
  87973. _this._lineBoundingBox.addChild(l);
  87974. });
  87975. _this._rootMesh.addChild(_this._lineBoundingBox);
  87976. // Create rotation spheres
  87977. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  87978. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  87979. var _loop_1 = function (i_1) {
  87980. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  87981. sphere.rotationQuaternion = new BABYLON.Quaternion();
  87982. sphere.material = coloredMaterial;
  87983. // Drag behavior
  87984. _dragBehavior = new BABYLON.PointerDragBehavior({});
  87985. _dragBehavior.moveAttached = false;
  87986. sphere.addBehavior(_dragBehavior);
  87987. _dragBehavior.onDragObservable.add(function (event) {
  87988. if (_this.attachedMesh) {
  87989. var worldDragDirection = sphere.forward;
  87990. // Project the world right on to the drag plane
  87991. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  87992. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  87993. // project drag delta on to the resulting drag axis and rotate based on that
  87994. var projectDist = BABYLON.Vector3.Dot(dragAxis, event.delta);
  87995. // Rotate based on axis
  87996. if (i_1 >= 8) {
  87997. _this.attachedMesh.rotation.z -= projectDist;
  87998. }
  87999. else if (i_1 >= 4) {
  88000. _this.attachedMesh.rotation.y -= projectDist;
  88001. }
  88002. else {
  88003. _this.attachedMesh.rotation.x -= projectDist;
  88004. }
  88005. }
  88006. });
  88007. // Selection/deselection
  88008. _dragBehavior.onDragStartObservable.add(function () {
  88009. _this._selectNode(sphere);
  88010. });
  88011. _dragBehavior.onDragEndObservable.add(function () {
  88012. _this._selectNode(null);
  88013. });
  88014. this_1._rotateSpheresParent.addChild(sphere);
  88015. };
  88016. var this_1 = this, _dragBehavior;
  88017. for (var i_1 = 0; i_1 < 12; i_1++) {
  88018. _loop_1(i_1);
  88019. }
  88020. _this._rootMesh.addChild(_this._rotateSpheresParent);
  88021. // Create scale cubes
  88022. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88023. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  88024. for (var i = 0; i < 2; i++) {
  88025. for (var j = 0; j < 2; j++) {
  88026. var _loop_2 = function () {
  88027. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  88028. box.material = coloredMaterial;
  88029. // Dragging logic
  88030. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  88031. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88032. _dragBehavior.moveAttached = false;
  88033. box.addBehavior(_dragBehavior);
  88034. _dragBehavior.onDragObservable.add(function (event) {
  88035. if (_this.attachedMesh) {
  88036. // Current boudning box dimensions
  88037. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  88038. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  88039. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  88040. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  88041. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  88042. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  88043. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  88044. // Update scale and position
  88045. _this.attachedMesh.scaling.addInPlace(deltaScale);
  88046. _this.attachedMesh.position.addInPlace(worldMoveDirection);
  88047. }
  88048. });
  88049. // Selection/deselection
  88050. _dragBehavior.onDragStartObservable.add(function () {
  88051. _this._selectNode(box);
  88052. });
  88053. _dragBehavior.onDragEndObservable.add(function () {
  88054. _this._selectNode(null);
  88055. });
  88056. this_2._scaleBoxesParent.addChild(box);
  88057. };
  88058. var this_2 = this, _dragBehavior;
  88059. for (var k = 0; k < 2; k++) {
  88060. _loop_2();
  88061. }
  88062. }
  88063. }
  88064. _this._rootMesh.addChild(_this._scaleBoxesParent);
  88065. // Update bounding box positions
  88066. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  88067. _this._updateBoundingBox();
  88068. });
  88069. _this._updateBoundingBox();
  88070. return _this;
  88071. }
  88072. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  88073. this._rotateSpheresParent.getChildMeshes()
  88074. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  88075. m.isVisible = (!selectedMesh || m == selectedMesh);
  88076. });
  88077. };
  88078. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  88079. if (this.attachedMesh) {
  88080. // Update bounding dimensions/positions
  88081. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  88082. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  88083. this._boundingDimensions.copyFrom(boundBoxDimensions);
  88084. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  88085. if (!this.attachedMesh.rotationQuaternion) {
  88086. this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88087. }
  88088. this._lineBoundingBox.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88089. this._rotateSpheresParent.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88090. this._scaleBoxesParent.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  88091. }
  88092. // Update rotation sphere locations
  88093. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  88094. for (var i = 0; i < 3; i++) {
  88095. for (var j = 0; j < 2; j++) {
  88096. for (var k = 0; k < 2; k++) {
  88097. var index = ((i * 4) + (j * 2)) + k;
  88098. if (i == 0) {
  88099. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88100. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88101. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88102. }
  88103. if (i == 1) {
  88104. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  88105. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88106. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88107. }
  88108. if (i == 2) {
  88109. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  88110. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88111. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  88112. }
  88113. }
  88114. }
  88115. }
  88116. // Update scale box locations
  88117. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  88118. for (var i = 0; i < 2; i++) {
  88119. for (var j = 0; j < 2; j++) {
  88120. for (var k = 0; k < 2; k++) {
  88121. var index = ((i * 4) + (j * 2)) + k;
  88122. if (scaleBoxes[index]) {
  88123. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  88124. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  88125. }
  88126. }
  88127. }
  88128. }
  88129. };
  88130. /**
  88131. * Disposes of the gizmo
  88132. */
  88133. BoundingBoxGizmo.prototype.dispose = function () {
  88134. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  88135. this._lineBoundingBox.dispose();
  88136. this._rotateSpheresParent.dispose();
  88137. this._scaleBoxesParent.dispose();
  88138. _super.prototype.dispose.call(this);
  88139. };
  88140. return BoundingBoxGizmo;
  88141. }(BABYLON.Gizmo));
  88142. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  88143. })(BABYLON || (BABYLON = {}));
  88144. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  88145. var BABYLON;
  88146. (function (BABYLON) {
  88147. /**
  88148. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  88149. */
  88150. var GizmoManager = /** @class */ (function () {
  88151. /**
  88152. * Instatiates a gizmo manager
  88153. * @param scene the scene to overlay the gizmos on top of
  88154. * @param options If only a single gizmo should exist at one time
  88155. */
  88156. function GizmoManager(scene, options) {
  88157. var _this = this;
  88158. this.scene = scene;
  88159. // Set of gizmos that are currently in the scene for each mesh
  88160. this._gizmoSet = {};
  88161. this._pointerObserver = null;
  88162. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  88163. // Options parsing
  88164. if (!options) {
  88165. options = {};
  88166. }
  88167. if (options.singleGizmo === undefined) {
  88168. options.singleGizmo = true;
  88169. }
  88170. // Instatiate/dispose gizmos based on pointer actions
  88171. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  88172. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88173. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  88174. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  88175. if (options.singleGizmo) {
  88176. _this._clearGizmos();
  88177. }
  88178. // Enable gizmo when mesh is selected
  88179. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  88180. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88181. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  88182. }
  88183. else {
  88184. if (!options.singleGizmo) {
  88185. // Disable gizmo when clicked again
  88186. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  88187. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  88188. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  88189. }
  88190. }
  88191. }
  88192. else {
  88193. if (options.singleGizmo) {
  88194. // Disable gizmo when clicked away
  88195. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88196. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  88197. if (gizmoPick && !gizmoPick.hit) {
  88198. _this._clearGizmos();
  88199. }
  88200. }
  88201. }
  88202. }
  88203. }
  88204. });
  88205. }
  88206. /**
  88207. * Disposes of the gizmo manager
  88208. */
  88209. GizmoManager.prototype.dispose = function () {
  88210. this.scene.onPointerObservable.remove(this._pointerObserver);
  88211. this._clearGizmos();
  88212. this._gizmoLayer.dispose();
  88213. };
  88214. GizmoManager.prototype._clearGizmos = function () {
  88215. for (var key in this._gizmoSet) {
  88216. if (this._gizmoSet.hasOwnProperty(key)) {
  88217. this._gizmoSet[key].positionGizmo.dispose();
  88218. this._gizmoSet[key].rotationGizmo.dispose();
  88219. delete this._gizmoSet[key];
  88220. }
  88221. }
  88222. };
  88223. return GizmoManager;
  88224. }());
  88225. BABYLON.GizmoManager = GizmoManager;
  88226. })(BABYLON || (BABYLON = {}));
  88227. //# sourceMappingURL=babylon.gizmoManager.js.map
  88228. var BABYLON;
  88229. (function (BABYLON) {
  88230. /**
  88231. * Defines a target to use with MorphTargetManager
  88232. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88233. */
  88234. var MorphTarget = /** @class */ (function () {
  88235. /**
  88236. * Creates a new MorphTarget
  88237. * @param name defines the name of the target
  88238. * @param influence defines the influence to use
  88239. */
  88240. function MorphTarget(
  88241. /** defines the name of the target */
  88242. name, influence, scene) {
  88243. if (influence === void 0) { influence = 0; }
  88244. if (scene === void 0) { scene = null; }
  88245. this.name = name;
  88246. /**
  88247. * Gets or sets the list of animations
  88248. */
  88249. this.animations = new Array();
  88250. this._positions = null;
  88251. this._normals = null;
  88252. this._tangents = null;
  88253. /**
  88254. * Observable raised when the influence changes
  88255. */
  88256. this.onInfluenceChanged = new BABYLON.Observable();
  88257. this._animationPropertiesOverride = null;
  88258. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88259. this.influence = influence;
  88260. }
  88261. Object.defineProperty(MorphTarget.prototype, "influence", {
  88262. /**
  88263. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  88264. */
  88265. get: function () {
  88266. return this._influence;
  88267. },
  88268. set: function (influence) {
  88269. if (this._influence === influence) {
  88270. return;
  88271. }
  88272. var previous = this._influence;
  88273. this._influence = influence;
  88274. if (this.onInfluenceChanged.hasObservers) {
  88275. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  88276. }
  88277. },
  88278. enumerable: true,
  88279. configurable: true
  88280. });
  88281. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  88282. /**
  88283. * Gets or sets the animation properties override
  88284. */
  88285. get: function () {
  88286. if (!this._animationPropertiesOverride && this._scene) {
  88287. return this._scene.animationPropertiesOverride;
  88288. }
  88289. return this._animationPropertiesOverride;
  88290. },
  88291. set: function (value) {
  88292. this._animationPropertiesOverride = value;
  88293. },
  88294. enumerable: true,
  88295. configurable: true
  88296. });
  88297. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  88298. /**
  88299. * Gets a boolean defining if the target contains position data
  88300. */
  88301. get: function () {
  88302. return !!this._positions;
  88303. },
  88304. enumerable: true,
  88305. configurable: true
  88306. });
  88307. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  88308. /**
  88309. * Gets a boolean defining if the target contains normal data
  88310. */
  88311. get: function () {
  88312. return !!this._normals;
  88313. },
  88314. enumerable: true,
  88315. configurable: true
  88316. });
  88317. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  88318. /**
  88319. * Gets a boolean defining if the target contains tangent data
  88320. */
  88321. get: function () {
  88322. return !!this._tangents;
  88323. },
  88324. enumerable: true,
  88325. configurable: true
  88326. });
  88327. /**
  88328. * Affects position data to this target
  88329. * @param data defines the position data to use
  88330. */
  88331. MorphTarget.prototype.setPositions = function (data) {
  88332. this._positions = data;
  88333. };
  88334. /**
  88335. * Gets the position data stored in this target
  88336. * @returns a FloatArray containing the position data (or null if not present)
  88337. */
  88338. MorphTarget.prototype.getPositions = function () {
  88339. return this._positions;
  88340. };
  88341. /**
  88342. * Affects normal data to this target
  88343. * @param data defines the normal data to use
  88344. */
  88345. MorphTarget.prototype.setNormals = function (data) {
  88346. this._normals = data;
  88347. };
  88348. /**
  88349. * Gets the normal data stored in this target
  88350. * @returns a FloatArray containing the normal data (or null if not present)
  88351. */
  88352. MorphTarget.prototype.getNormals = function () {
  88353. return this._normals;
  88354. };
  88355. /**
  88356. * Affects tangent data to this target
  88357. * @param data defines the tangent data to use
  88358. */
  88359. MorphTarget.prototype.setTangents = function (data) {
  88360. this._tangents = data;
  88361. };
  88362. /**
  88363. * Gets the tangent data stored in this target
  88364. * @returns a FloatArray containing the tangent data (or null if not present)
  88365. */
  88366. MorphTarget.prototype.getTangents = function () {
  88367. return this._tangents;
  88368. };
  88369. /**
  88370. * Serializes the current target into a Serialization object
  88371. * @returns the serialized object
  88372. */
  88373. MorphTarget.prototype.serialize = function () {
  88374. var serializationObject = {};
  88375. serializationObject.name = this.name;
  88376. serializationObject.influence = this.influence;
  88377. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  88378. if (this.hasNormals) {
  88379. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  88380. }
  88381. if (this.hasTangents) {
  88382. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  88383. }
  88384. // Animations
  88385. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  88386. return serializationObject;
  88387. };
  88388. // Statics
  88389. /**
  88390. * Creates a new target from serialized data
  88391. * @param serializationObject defines the serialized data to use
  88392. * @returns a new MorphTarget
  88393. */
  88394. MorphTarget.Parse = function (serializationObject) {
  88395. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  88396. result.setPositions(serializationObject.positions);
  88397. if (serializationObject.normals) {
  88398. result.setNormals(serializationObject.normals);
  88399. }
  88400. if (serializationObject.tangents) {
  88401. result.setTangents(serializationObject.tangents);
  88402. }
  88403. // Animations
  88404. if (serializationObject.animations) {
  88405. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  88406. var parsedAnimation = serializationObject.animations[animationIndex];
  88407. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  88408. }
  88409. }
  88410. return result;
  88411. };
  88412. /**
  88413. * Creates a MorphTarget from mesh data
  88414. * @param mesh defines the source mesh
  88415. * @param name defines the name to use for the new target
  88416. * @param influence defines the influence to attach to the target
  88417. * @returns a new MorphTarget
  88418. */
  88419. MorphTarget.FromMesh = function (mesh, name, influence) {
  88420. if (!name) {
  88421. name = mesh.name;
  88422. }
  88423. var result = new MorphTarget(name, influence, mesh.getScene());
  88424. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88425. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88426. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  88427. }
  88428. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  88429. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  88430. }
  88431. return result;
  88432. };
  88433. return MorphTarget;
  88434. }());
  88435. BABYLON.MorphTarget = MorphTarget;
  88436. })(BABYLON || (BABYLON = {}));
  88437. //# sourceMappingURL=babylon.morphTarget.js.map
  88438. var BABYLON;
  88439. (function (BABYLON) {
  88440. /**
  88441. * This class is used to deform meshes using morphing between different targets
  88442. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  88443. */
  88444. var MorphTargetManager = /** @class */ (function () {
  88445. /**
  88446. * Creates a new MorphTargetManager
  88447. * @param scene defines the current scene
  88448. */
  88449. function MorphTargetManager(scene) {
  88450. if (scene === void 0) { scene = null; }
  88451. this._targets = new Array();
  88452. this._targetObservable = new Array();
  88453. this._activeTargets = new BABYLON.SmartArray(16);
  88454. this._supportsNormals = false;
  88455. this._supportsTangents = false;
  88456. this._vertexCount = 0;
  88457. this._uniqueId = 0;
  88458. this._tempInfluences = new Array();
  88459. if (!scene) {
  88460. scene = BABYLON.Engine.LastCreatedScene;
  88461. }
  88462. this._scene = scene;
  88463. if (this._scene) {
  88464. this._scene.morphTargetManagers.push(this);
  88465. this._uniqueId = this._scene.getUniqueId();
  88466. }
  88467. }
  88468. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88469. /**
  88470. * Gets the unique ID of this manager
  88471. */
  88472. get: function () {
  88473. return this._uniqueId;
  88474. },
  88475. enumerable: true,
  88476. configurable: true
  88477. });
  88478. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88479. /**
  88480. * Gets the number of vertices handled by this manager
  88481. */
  88482. get: function () {
  88483. return this._vertexCount;
  88484. },
  88485. enumerable: true,
  88486. configurable: true
  88487. });
  88488. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88489. /**
  88490. * Gets a boolean indicating if this manager supports morphing of normals
  88491. */
  88492. get: function () {
  88493. return this._supportsNormals;
  88494. },
  88495. enumerable: true,
  88496. configurable: true
  88497. });
  88498. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88499. /**
  88500. * Gets a boolean indicating if this manager supports morphing of tangents
  88501. */
  88502. get: function () {
  88503. return this._supportsTangents;
  88504. },
  88505. enumerable: true,
  88506. configurable: true
  88507. });
  88508. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88509. /**
  88510. * Gets the number of targets stored in this manager
  88511. */
  88512. get: function () {
  88513. return this._targets.length;
  88514. },
  88515. enumerable: true,
  88516. configurable: true
  88517. });
  88518. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88519. /**
  88520. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88521. */
  88522. get: function () {
  88523. return this._activeTargets.length;
  88524. },
  88525. enumerable: true,
  88526. configurable: true
  88527. });
  88528. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88529. /**
  88530. * Gets the list of influences (one per target)
  88531. */
  88532. get: function () {
  88533. return this._influences;
  88534. },
  88535. enumerable: true,
  88536. configurable: true
  88537. });
  88538. /**
  88539. * Gets the active target at specified index. An active target is a target with an influence > 0
  88540. * @param index defines the index to check
  88541. * @returns the requested target
  88542. */
  88543. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88544. return this._activeTargets.data[index];
  88545. };
  88546. /**
  88547. * Gets the target at specified index
  88548. * @param index defines the index to check
  88549. * @returns the requested target
  88550. */
  88551. MorphTargetManager.prototype.getTarget = function (index) {
  88552. return this._targets[index];
  88553. };
  88554. /**
  88555. * Add a new target to this manager
  88556. * @param target defines the target to add
  88557. */
  88558. MorphTargetManager.prototype.addTarget = function (target) {
  88559. var _this = this;
  88560. this._targets.push(target);
  88561. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88562. _this._syncActiveTargets(needUpdate);
  88563. }));
  88564. this._syncActiveTargets(true);
  88565. };
  88566. /**
  88567. * Removes a target from the manager
  88568. * @param target defines the target to remove
  88569. */
  88570. MorphTargetManager.prototype.removeTarget = function (target) {
  88571. var index = this._targets.indexOf(target);
  88572. if (index >= 0) {
  88573. this._targets.splice(index, 1);
  88574. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88575. this._syncActiveTargets(true);
  88576. }
  88577. };
  88578. /**
  88579. * Serializes the current manager into a Serialization object
  88580. * @returns the serialized object
  88581. */
  88582. MorphTargetManager.prototype.serialize = function () {
  88583. var serializationObject = {};
  88584. serializationObject.id = this.uniqueId;
  88585. serializationObject.targets = [];
  88586. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88587. var target = _a[_i];
  88588. serializationObject.targets.push(target.serialize());
  88589. }
  88590. return serializationObject;
  88591. };
  88592. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88593. var influenceCount = 0;
  88594. this._activeTargets.reset();
  88595. this._supportsNormals = true;
  88596. this._supportsTangents = true;
  88597. this._vertexCount = 0;
  88598. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88599. var target = _a[_i];
  88600. this._activeTargets.push(target);
  88601. this._tempInfluences[influenceCount++] = target.influence;
  88602. var positions = target.getPositions();
  88603. if (positions) {
  88604. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88605. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88606. var vertexCount = positions.length / 3;
  88607. if (this._vertexCount === 0) {
  88608. this._vertexCount = vertexCount;
  88609. }
  88610. else if (this._vertexCount !== vertexCount) {
  88611. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88612. return;
  88613. }
  88614. }
  88615. }
  88616. if (!this._influences || this._influences.length !== influenceCount) {
  88617. this._influences = new Float32Array(influenceCount);
  88618. }
  88619. for (var index = 0; index < influenceCount; index++) {
  88620. this._influences[index] = this._tempInfluences[index];
  88621. }
  88622. if (needUpdate) {
  88623. this.synchronize();
  88624. }
  88625. };
  88626. /**
  88627. * Syncrhonize the targets with all the meshes using this morph target manager
  88628. */
  88629. MorphTargetManager.prototype.synchronize = function () {
  88630. if (!this._scene) {
  88631. return;
  88632. }
  88633. // Flag meshes as dirty to resync with the active targets
  88634. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88635. var mesh = _a[_i];
  88636. if (mesh.morphTargetManager === this) {
  88637. mesh._syncGeometryWithMorphTargetManager();
  88638. }
  88639. }
  88640. };
  88641. // Statics
  88642. /**
  88643. * Creates a new MorphTargetManager from serialized data
  88644. * @param serializationObject defines the serialized data
  88645. * @param scene defines the hosting scene
  88646. * @returns the new MorphTargetManager
  88647. */
  88648. MorphTargetManager.Parse = function (serializationObject, scene) {
  88649. var result = new MorphTargetManager(scene);
  88650. result._uniqueId = serializationObject.id;
  88651. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88652. var targetData = _a[_i];
  88653. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88654. }
  88655. return result;
  88656. };
  88657. return MorphTargetManager;
  88658. }());
  88659. BABYLON.MorphTargetManager = MorphTargetManager;
  88660. })(BABYLON || (BABYLON = {}));
  88661. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88662. var BABYLON;
  88663. (function (BABYLON) {
  88664. var Octree = /** @class */ (function () {
  88665. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88666. if (maxDepth === void 0) { maxDepth = 2; }
  88667. this.maxDepth = maxDepth;
  88668. this.dynamicContent = new Array();
  88669. this._maxBlockCapacity = maxBlockCapacity || 64;
  88670. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88671. this._creationFunc = creationFunc;
  88672. }
  88673. // Methods
  88674. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88675. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88676. };
  88677. Octree.prototype.addMesh = function (entry) {
  88678. for (var index = 0; index < this.blocks.length; index++) {
  88679. var block = this.blocks[index];
  88680. block.addEntry(entry);
  88681. }
  88682. };
  88683. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88684. this._selectionContent.reset();
  88685. for (var index = 0; index < this.blocks.length; index++) {
  88686. var block = this.blocks[index];
  88687. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88688. }
  88689. if (allowDuplicate) {
  88690. this._selectionContent.concat(this.dynamicContent);
  88691. }
  88692. else {
  88693. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88694. }
  88695. return this._selectionContent;
  88696. };
  88697. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88698. this._selectionContent.reset();
  88699. for (var index = 0; index < this.blocks.length; index++) {
  88700. var block = this.blocks[index];
  88701. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88702. }
  88703. if (allowDuplicate) {
  88704. this._selectionContent.concat(this.dynamicContent);
  88705. }
  88706. else {
  88707. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88708. }
  88709. return this._selectionContent;
  88710. };
  88711. Octree.prototype.intersectsRay = function (ray) {
  88712. this._selectionContent.reset();
  88713. for (var index = 0; index < this.blocks.length; index++) {
  88714. var block = this.blocks[index];
  88715. block.intersectsRay(ray, this._selectionContent);
  88716. }
  88717. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88718. return this._selectionContent;
  88719. };
  88720. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88721. target.blocks = new Array();
  88722. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88723. // Segmenting space
  88724. for (var x = 0; x < 2; x++) {
  88725. for (var y = 0; y < 2; y++) {
  88726. for (var z = 0; z < 2; z++) {
  88727. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88728. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88729. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88730. block.addEntries(entries);
  88731. target.blocks.push(block);
  88732. }
  88733. }
  88734. }
  88735. };
  88736. Octree.CreationFuncForMeshes = function (entry, block) {
  88737. var boundingInfo = entry.getBoundingInfo();
  88738. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88739. block.entries.push(entry);
  88740. }
  88741. };
  88742. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88743. var boundingInfo = entry.getBoundingInfo();
  88744. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88745. block.entries.push(entry);
  88746. }
  88747. };
  88748. return Octree;
  88749. }());
  88750. BABYLON.Octree = Octree;
  88751. })(BABYLON || (BABYLON = {}));
  88752. //# sourceMappingURL=babylon.octree.js.map
  88753. var BABYLON;
  88754. (function (BABYLON) {
  88755. var OctreeBlock = /** @class */ (function () {
  88756. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88757. this.entries = new Array();
  88758. this._boundingVectors = new Array();
  88759. this._capacity = capacity;
  88760. this._depth = depth;
  88761. this._maxDepth = maxDepth;
  88762. this._creationFunc = creationFunc;
  88763. this._minPoint = minPoint;
  88764. this._maxPoint = maxPoint;
  88765. this._boundingVectors.push(minPoint.clone());
  88766. this._boundingVectors.push(maxPoint.clone());
  88767. this._boundingVectors.push(minPoint.clone());
  88768. this._boundingVectors[2].x = maxPoint.x;
  88769. this._boundingVectors.push(minPoint.clone());
  88770. this._boundingVectors[3].y = maxPoint.y;
  88771. this._boundingVectors.push(minPoint.clone());
  88772. this._boundingVectors[4].z = maxPoint.z;
  88773. this._boundingVectors.push(maxPoint.clone());
  88774. this._boundingVectors[5].z = minPoint.z;
  88775. this._boundingVectors.push(maxPoint.clone());
  88776. this._boundingVectors[6].x = minPoint.x;
  88777. this._boundingVectors.push(maxPoint.clone());
  88778. this._boundingVectors[7].y = minPoint.y;
  88779. }
  88780. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88781. // Property
  88782. get: function () {
  88783. return this._capacity;
  88784. },
  88785. enumerable: true,
  88786. configurable: true
  88787. });
  88788. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88789. get: function () {
  88790. return this._minPoint;
  88791. },
  88792. enumerable: true,
  88793. configurable: true
  88794. });
  88795. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88796. get: function () {
  88797. return this._maxPoint;
  88798. },
  88799. enumerable: true,
  88800. configurable: true
  88801. });
  88802. // Methods
  88803. OctreeBlock.prototype.addEntry = function (entry) {
  88804. if (this.blocks) {
  88805. for (var index = 0; index < this.blocks.length; index++) {
  88806. var block = this.blocks[index];
  88807. block.addEntry(entry);
  88808. }
  88809. return;
  88810. }
  88811. this._creationFunc(entry, this);
  88812. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88813. this.createInnerBlocks();
  88814. }
  88815. };
  88816. OctreeBlock.prototype.addEntries = function (entries) {
  88817. for (var index = 0; index < entries.length; index++) {
  88818. var mesh = entries[index];
  88819. this.addEntry(mesh);
  88820. }
  88821. };
  88822. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88823. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88824. if (this.blocks) {
  88825. for (var index = 0; index < this.blocks.length; index++) {
  88826. var block = this.blocks[index];
  88827. block.select(frustumPlanes, selection, allowDuplicate);
  88828. }
  88829. return;
  88830. }
  88831. if (allowDuplicate) {
  88832. selection.concat(this.entries);
  88833. }
  88834. else {
  88835. selection.concatWithNoDuplicate(this.entries);
  88836. }
  88837. }
  88838. };
  88839. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88840. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88841. if (this.blocks) {
  88842. for (var index = 0; index < this.blocks.length; index++) {
  88843. var block = this.blocks[index];
  88844. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88845. }
  88846. return;
  88847. }
  88848. if (allowDuplicate) {
  88849. selection.concat(this.entries);
  88850. }
  88851. else {
  88852. selection.concatWithNoDuplicate(this.entries);
  88853. }
  88854. }
  88855. };
  88856. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88857. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88858. if (this.blocks) {
  88859. for (var index = 0; index < this.blocks.length; index++) {
  88860. var block = this.blocks[index];
  88861. block.intersectsRay(ray, selection);
  88862. }
  88863. return;
  88864. }
  88865. selection.concatWithNoDuplicate(this.entries);
  88866. }
  88867. };
  88868. OctreeBlock.prototype.createInnerBlocks = function () {
  88869. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88870. };
  88871. return OctreeBlock;
  88872. }());
  88873. BABYLON.OctreeBlock = OctreeBlock;
  88874. })(BABYLON || (BABYLON = {}));
  88875. //# sourceMappingURL=babylon.octreeBlock.js.map
  88876. var BABYLON;
  88877. (function (BABYLON) {
  88878. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88879. __extends(VRDistortionCorrectionPostProcess, _super);
  88880. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88881. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88882. 'LensCenter',
  88883. 'Scale',
  88884. 'ScaleIn',
  88885. 'HmdWarpParam'
  88886. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88887. _this._isRightEye = isRightEye;
  88888. _this._distortionFactors = vrMetrics.distortionK;
  88889. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88890. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88891. _this.adaptScaleToCurrentViewport = true;
  88892. _this.onSizeChangedObservable.add(function () {
  88893. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88894. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88895. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88896. });
  88897. _this.onApplyObservable.add(function (effect) {
  88898. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88899. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88900. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88901. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88902. });
  88903. return _this;
  88904. }
  88905. return VRDistortionCorrectionPostProcess;
  88906. }(BABYLON.PostProcess));
  88907. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88908. })(BABYLON || (BABYLON = {}));
  88909. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88910. var BABYLON;
  88911. (function (BABYLON) {
  88912. /**
  88913. * Postprocess used to generate anaglyphic rendering
  88914. */
  88915. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88916. __extends(AnaglyphPostProcess, _super);
  88917. /**
  88918. * Creates a new AnaglyphPostProcess
  88919. * @param name defines postprocess name
  88920. * @param options defines creation options or target ratio scale
  88921. * @param rigCameras defines cameras using this postprocess
  88922. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88923. * @param engine defines hosting engine
  88924. * @param reusable defines if the postprocess will be reused multiple times per frame
  88925. */
  88926. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88927. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88928. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88929. _this.onApplyObservable.add(function (effect) {
  88930. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88931. });
  88932. return _this;
  88933. }
  88934. return AnaglyphPostProcess;
  88935. }(BABYLON.PostProcess));
  88936. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88937. })(BABYLON || (BABYLON = {}));
  88938. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88939. var BABYLON;
  88940. (function (BABYLON) {
  88941. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88942. __extends(StereoscopicInterlacePostProcess, _super);
  88943. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88944. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88945. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88946. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88947. _this.onSizeChangedObservable.add(function () {
  88948. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88949. });
  88950. _this.onApplyObservable.add(function (effect) {
  88951. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88952. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88953. });
  88954. return _this;
  88955. }
  88956. return StereoscopicInterlacePostProcess;
  88957. }(BABYLON.PostProcess));
  88958. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88959. })(BABYLON || (BABYLON = {}));
  88960. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88961. var BABYLON;
  88962. (function (BABYLON) {
  88963. /**
  88964. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88965. * Screen rotation is taken into account.
  88966. */
  88967. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88968. function FreeCameraDeviceOrientationInput() {
  88969. var _this = this;
  88970. this._screenOrientationAngle = 0;
  88971. this._screenQuaternion = new BABYLON.Quaternion();
  88972. this._alpha = 0;
  88973. this._beta = 0;
  88974. this._gamma = 0;
  88975. this._orientationChanged = function () {
  88976. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88977. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88978. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88979. };
  88980. this._deviceOrientation = function (evt) {
  88981. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88982. _this._beta = evt.beta !== null ? evt.beta : 0;
  88983. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88984. };
  88985. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88986. this._orientationChanged();
  88987. }
  88988. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88989. get: function () {
  88990. return this._camera;
  88991. },
  88992. set: function (camera) {
  88993. this._camera = camera;
  88994. if (this._camera != null && !this._camera.rotationQuaternion) {
  88995. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88996. }
  88997. },
  88998. enumerable: true,
  88999. configurable: true
  89000. });
  89001. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  89002. window.addEventListener("orientationchange", this._orientationChanged);
  89003. window.addEventListener("deviceorientation", this._deviceOrientation);
  89004. //In certain cases, the attach control is called AFTER orientation was changed,
  89005. //So this is needed.
  89006. this._orientationChanged();
  89007. };
  89008. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  89009. window.removeEventListener("orientationchange", this._orientationChanged);
  89010. window.removeEventListener("deviceorientation", this._deviceOrientation);
  89011. };
  89012. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  89013. //if no device orientation provided, don't update the rotation.
  89014. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  89015. if (!this._alpha)
  89016. return;
  89017. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  89018. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  89019. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  89020. //Mirror on XY Plane
  89021. this._camera.rotationQuaternion.z *= -1;
  89022. this._camera.rotationQuaternion.w *= -1;
  89023. };
  89024. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  89025. return "FreeCameraDeviceOrientationInput";
  89026. };
  89027. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  89028. return "deviceOrientation";
  89029. };
  89030. return FreeCameraDeviceOrientationInput;
  89031. }());
  89032. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  89033. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  89034. })(BABYLON || (BABYLON = {}));
  89035. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  89036. var BABYLON;
  89037. (function (BABYLON) {
  89038. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  89039. function ArcRotateCameraVRDeviceOrientationInput() {
  89040. this.alphaCorrection = 1;
  89041. this.betaCorrection = 1;
  89042. this.gammaCorrection = 1;
  89043. this._alpha = 0;
  89044. this._gamma = 0;
  89045. this._dirty = false;
  89046. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  89047. }
  89048. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  89049. this.camera.attachControl(element, noPreventDefault);
  89050. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  89051. };
  89052. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  89053. if (evt.alpha !== null) {
  89054. this._alpha = +evt.alpha | 0;
  89055. }
  89056. if (evt.gamma !== null) {
  89057. this._gamma = +evt.gamma | 0;
  89058. }
  89059. this._dirty = true;
  89060. };
  89061. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  89062. if (this._dirty) {
  89063. this._dirty = false;
  89064. if (this._gamma < 0) {
  89065. this._gamma = 180 + this._gamma;
  89066. }
  89067. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  89068. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  89069. }
  89070. };
  89071. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  89072. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  89073. };
  89074. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  89075. return "ArcRotateCameraVRDeviceOrientationInput";
  89076. };
  89077. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  89078. return "VRDeviceOrientation";
  89079. };
  89080. return ArcRotateCameraVRDeviceOrientationInput;
  89081. }());
  89082. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  89083. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  89084. })(BABYLON || (BABYLON = {}));
  89085. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  89086. var BABYLON;
  89087. (function (BABYLON) {
  89088. var VRCameraMetrics = /** @class */ (function () {
  89089. function VRCameraMetrics() {
  89090. this.compensateDistortion = true;
  89091. }
  89092. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  89093. get: function () {
  89094. return this.hResolution / (2 * this.vResolution);
  89095. },
  89096. enumerable: true,
  89097. configurable: true
  89098. });
  89099. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  89100. get: function () {
  89101. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  89102. },
  89103. enumerable: true,
  89104. configurable: true
  89105. });
  89106. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  89107. get: function () {
  89108. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89109. var h = (4 * meters) / this.hScreenSize;
  89110. return BABYLON.Matrix.Translation(h, 0, 0);
  89111. },
  89112. enumerable: true,
  89113. configurable: true
  89114. });
  89115. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  89116. get: function () {
  89117. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  89118. var h = (4 * meters) / this.hScreenSize;
  89119. return BABYLON.Matrix.Translation(-h, 0, 0);
  89120. },
  89121. enumerable: true,
  89122. configurable: true
  89123. });
  89124. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  89125. get: function () {
  89126. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  89127. },
  89128. enumerable: true,
  89129. configurable: true
  89130. });
  89131. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  89132. get: function () {
  89133. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  89134. },
  89135. enumerable: true,
  89136. configurable: true
  89137. });
  89138. VRCameraMetrics.GetDefault = function () {
  89139. var result = new VRCameraMetrics();
  89140. result.hResolution = 1280;
  89141. result.vResolution = 800;
  89142. result.hScreenSize = 0.149759993;
  89143. result.vScreenSize = 0.0935999975;
  89144. result.vScreenCenter = 0.0467999987;
  89145. result.eyeToScreenDistance = 0.0410000011;
  89146. result.lensSeparationDistance = 0.0635000020;
  89147. result.interpupillaryDistance = 0.0640000030;
  89148. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  89149. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  89150. result.postProcessScaleFactor = 1.714605507808412;
  89151. result.lensCenterOffset = 0.151976421;
  89152. return result;
  89153. };
  89154. return VRCameraMetrics;
  89155. }());
  89156. BABYLON.VRCameraMetrics = VRCameraMetrics;
  89157. })(BABYLON || (BABYLON = {}));
  89158. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  89159. var BABYLON;
  89160. (function (BABYLON) {
  89161. /**
  89162. * This represents a WebVR camera.
  89163. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  89164. * @example http://doc.babylonjs.com/how_to/webvr_camera
  89165. */
  89166. var WebVRFreeCamera = /** @class */ (function (_super) {
  89167. __extends(WebVRFreeCamera, _super);
  89168. /**
  89169. * Instantiates a WebVRFreeCamera.
  89170. * @param name The name of the WebVRFreeCamera
  89171. * @param position The starting anchor position for the camera
  89172. * @param scene The scene the camera belongs to
  89173. * @param webVROptions a set of customizable options for the webVRCamera
  89174. */
  89175. function WebVRFreeCamera(name, position, scene, webVROptions) {
  89176. if (webVROptions === void 0) { webVROptions = {}; }
  89177. var _this = _super.call(this, name, position, scene) || this;
  89178. _this.webVROptions = webVROptions;
  89179. /**
  89180. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  89181. */
  89182. _this._vrDevice = null;
  89183. /**
  89184. * The rawPose of the vrDevice.
  89185. */
  89186. _this.rawPose = null;
  89187. _this._specsVersion = "1.1";
  89188. _this._attached = false;
  89189. _this._descendants = [];
  89190. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  89191. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  89192. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  89193. _this._standingMatrix = null;
  89194. /**
  89195. * Represents device position in babylon space.
  89196. */
  89197. _this.devicePosition = BABYLON.Vector3.Zero();
  89198. /**
  89199. * Represents device rotation in babylon space.
  89200. */
  89201. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  89202. /**
  89203. * The scale of the device to be used when translating from device space to babylon space.
  89204. */
  89205. _this.deviceScaleFactor = 1;
  89206. _this._deviceToWorld = BABYLON.Matrix.Identity();
  89207. _this._worldToDevice = BABYLON.Matrix.Identity();
  89208. /**
  89209. * References to the webVR controllers for the vrDevice.
  89210. */
  89211. _this.controllers = [];
  89212. /**
  89213. * Emits an event when a controller is attached.
  89214. */
  89215. _this.onControllersAttachedObservable = new BABYLON.Observable();
  89216. /**
  89217. * Emits an event when a controller's mesh has been loaded;
  89218. */
  89219. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89220. /**
  89221. * If the rig cameras be used as parent instead of this camera.
  89222. */
  89223. _this.rigParenting = true;
  89224. _this._defaultHeight = undefined;
  89225. _this._workingVector = BABYLON.Vector3.Zero();
  89226. _this._oneVector = BABYLON.Vector3.One();
  89227. _this._workingMatrix = BABYLON.Matrix.Identity();
  89228. _this._cache.position = BABYLON.Vector3.Zero();
  89229. if (webVROptions.defaultHeight) {
  89230. _this._defaultHeight = webVROptions.defaultHeight;
  89231. _this.position.y = _this._defaultHeight;
  89232. }
  89233. _this.minZ = 0.1;
  89234. //legacy support - the compensation boolean was removed.
  89235. if (arguments.length === 5) {
  89236. _this.webVROptions = arguments[4];
  89237. }
  89238. // default webVR options
  89239. if (_this.webVROptions.trackPosition == undefined) {
  89240. _this.webVROptions.trackPosition = true;
  89241. }
  89242. if (_this.webVROptions.controllerMeshes == undefined) {
  89243. _this.webVROptions.controllerMeshes = true;
  89244. }
  89245. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  89246. _this.webVROptions.defaultLightingOnControllers = true;
  89247. }
  89248. _this.rotationQuaternion = new BABYLON.Quaternion();
  89249. if (_this.webVROptions && _this.webVROptions.positionScale) {
  89250. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  89251. }
  89252. //enable VR
  89253. var engine = _this.getEngine();
  89254. _this._onVREnabled = function (success) { if (success) {
  89255. _this.initControllers();
  89256. } };
  89257. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  89258. engine.initWebVR().add(function (event) {
  89259. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  89260. return;
  89261. }
  89262. _this._vrDevice = event.vrDisplay;
  89263. //reset the rig parameters.
  89264. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  89265. if (_this._attached) {
  89266. _this.getEngine().enableVR();
  89267. }
  89268. });
  89269. if (typeof (VRFrameData) !== "undefined")
  89270. _this._frameData = new VRFrameData();
  89271. /**
  89272. * The idea behind the following lines:
  89273. * objects that have the camera as parent should actually have the rig cameras as a parent.
  89274. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  89275. * the second will not show it correctly.
  89276. *
  89277. * To solve this - each object that has the camera as parent will be added to a protected array.
  89278. * When the rig camera renders, it will take this array and set all of those to be its children.
  89279. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  89280. * Amazing!
  89281. */
  89282. scene.onBeforeCameraRenderObservable.add(function (camera) {
  89283. if (camera.parent === _this && _this.rigParenting) {
  89284. _this._descendants = _this.getDescendants(true, function (n) {
  89285. // don't take the cameras or the controllers!
  89286. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  89287. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  89288. return !isController && !isRigCamera;
  89289. });
  89290. _this._descendants.forEach(function (node) {
  89291. node.parent = camera;
  89292. });
  89293. }
  89294. });
  89295. scene.onAfterCameraRenderObservable.add(function (camera) {
  89296. if (camera.parent === _this && _this.rigParenting) {
  89297. _this._descendants.forEach(function (node) {
  89298. node.parent = _this;
  89299. });
  89300. }
  89301. });
  89302. return _this;
  89303. }
  89304. /**
  89305. * Gets the device distance from the ground in meters.
  89306. * @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.
  89307. */
  89308. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  89309. if (this._standingMatrix) {
  89310. // Add standing matrix offset to get real offset from ground in room
  89311. this._standingMatrix.getTranslationToRef(this._workingVector);
  89312. return this._deviceRoomPosition.y + this._workingVector.y;
  89313. }
  89314. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  89315. return this._defaultHeight || 0;
  89316. };
  89317. /**
  89318. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89319. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  89320. */
  89321. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  89322. var _this = this;
  89323. if (callback === void 0) { callback = function (bool) { }; }
  89324. // Use standing matrix if available
  89325. this.getEngine().initWebVRAsync().then(function (result) {
  89326. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  89327. callback(false);
  89328. }
  89329. else {
  89330. _this._standingMatrix = new BABYLON.Matrix();
  89331. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  89332. if (!_this.getScene().useRightHandedSystem) {
  89333. [2, 6, 8, 9, 14].forEach(function (num) {
  89334. if (_this._standingMatrix) {
  89335. _this._standingMatrix.m[num] *= -1;
  89336. }
  89337. });
  89338. }
  89339. callback(true);
  89340. }
  89341. });
  89342. };
  89343. /**
  89344. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  89345. * @returns A promise with a boolean set to if the standing matrix is supported.
  89346. */
  89347. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  89348. var _this = this;
  89349. return new Promise(function (res, rej) {
  89350. _this.useStandingMatrix(function (supported) {
  89351. res(supported);
  89352. });
  89353. });
  89354. };
  89355. /**
  89356. * Disposes the camera
  89357. */
  89358. WebVRFreeCamera.prototype.dispose = function () {
  89359. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  89360. _super.prototype.dispose.call(this);
  89361. };
  89362. /**
  89363. * Gets a vrController by name.
  89364. * @param name The name of the controller to retreive
  89365. * @returns the controller matching the name specified or null if not found
  89366. */
  89367. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  89368. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  89369. var gp = _a[_i];
  89370. if (gp.hand === name) {
  89371. return gp;
  89372. }
  89373. }
  89374. return null;
  89375. };
  89376. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  89377. /**
  89378. * The controller corrisponding to the users left hand.
  89379. */
  89380. get: function () {
  89381. if (!this._leftController) {
  89382. this._leftController = this.getControllerByName("left");
  89383. }
  89384. return this._leftController;
  89385. },
  89386. enumerable: true,
  89387. configurable: true
  89388. });
  89389. ;
  89390. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  89391. /**
  89392. * The controller corrisponding to the users right hand.
  89393. */
  89394. get: function () {
  89395. if (!this._rightController) {
  89396. this._rightController = this.getControllerByName("right");
  89397. }
  89398. return this._rightController;
  89399. },
  89400. enumerable: true,
  89401. configurable: true
  89402. });
  89403. ;
  89404. /**
  89405. * Casts a ray forward from the vrCamera's gaze.
  89406. * @param length Length of the ray (default: 100)
  89407. * @returns the ray corrisponding to the gaze
  89408. */
  89409. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  89410. if (length === void 0) { length = 100; }
  89411. if (this.leftCamera) {
  89412. // Use left eye to avoid computation to compute center on every call
  89413. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  89414. }
  89415. else {
  89416. return _super.prototype.getForwardRay.call(this, length);
  89417. }
  89418. };
  89419. /**
  89420. * Updates the camera based on device's frame data
  89421. */
  89422. WebVRFreeCamera.prototype._checkInputs = function () {
  89423. if (this._vrDevice && this._vrDevice.isPresenting) {
  89424. this._vrDevice.getFrameData(this._frameData);
  89425. this.updateFromDevice(this._frameData.pose);
  89426. }
  89427. _super.prototype._checkInputs.call(this);
  89428. };
  89429. /**
  89430. * Updates the poseControlled values based on the input device pose.
  89431. * @param poseData Pose coming from the device
  89432. */
  89433. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  89434. if (poseData && poseData.orientation) {
  89435. this.rawPose = poseData;
  89436. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  89437. if (this.getScene().useRightHandedSystem) {
  89438. this._deviceRoomRotationQuaternion.z *= -1;
  89439. this._deviceRoomRotationQuaternion.w *= -1;
  89440. }
  89441. if (this.webVROptions.trackPosition && this.rawPose.position) {
  89442. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  89443. if (this.getScene().useRightHandedSystem) {
  89444. this._deviceRoomPosition.z *= -1;
  89445. }
  89446. }
  89447. }
  89448. };
  89449. /**
  89450. * WebVR's attach control will start broadcasting frames to the device.
  89451. * Note that in certain browsers (chrome for example) this function must be called
  89452. * within a user-interaction callback. Example:
  89453. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  89454. *
  89455. * @param element html element to attach the vrDevice to
  89456. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  89457. */
  89458. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  89459. _super.prototype.attachControl.call(this, element, noPreventDefault);
  89460. this._attached = true;
  89461. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  89462. if (this._vrDevice) {
  89463. this.getEngine().enableVR();
  89464. }
  89465. };
  89466. /**
  89467. * Detaches the camera from the html element and disables VR
  89468. *
  89469. * @param element html element to detach from
  89470. */
  89471. WebVRFreeCamera.prototype.detachControl = function (element) {
  89472. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89473. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89474. _super.prototype.detachControl.call(this, element);
  89475. this._attached = false;
  89476. this.getEngine().disableVR();
  89477. };
  89478. /**
  89479. * @returns the name of this class
  89480. */
  89481. WebVRFreeCamera.prototype.getClassName = function () {
  89482. return "WebVRFreeCamera";
  89483. };
  89484. /**
  89485. * Calls resetPose on the vrDisplay
  89486. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89487. */
  89488. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89489. //uses the vrDisplay's "resetPose()".
  89490. //pitch and roll won't be affected.
  89491. this._vrDevice.resetPose();
  89492. };
  89493. /**
  89494. * Updates the rig cameras (left and right eye)
  89495. */
  89496. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89497. var camLeft = this._rigCameras[0];
  89498. var camRight = this._rigCameras[1];
  89499. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89500. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89501. camLeft.position.copyFrom(this._deviceRoomPosition);
  89502. camRight.position.copyFrom(this._deviceRoomPosition);
  89503. };
  89504. /**
  89505. * Updates the cached values of the camera
  89506. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89507. */
  89508. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89509. var _this = this;
  89510. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89511. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89512. if (!this.updateCacheCalled) {
  89513. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89514. this.updateCacheCalled = true;
  89515. this.update();
  89516. }
  89517. // Set working vector to the device position in room space rotated by the new rotation
  89518. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89519. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89520. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89521. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89522. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89523. // Add translation from anchor position
  89524. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89525. this._workingVector.addInPlace(this.position);
  89526. this._workingVector.subtractInPlace(this._cache.position);
  89527. this._deviceToWorld.setTranslation(this._workingVector);
  89528. // Set an inverted matrix to be used when updating the camera
  89529. this._deviceToWorld.invertToRef(this._worldToDevice);
  89530. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89531. this.controllers.forEach(function (controller) {
  89532. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89533. controller.update();
  89534. });
  89535. }
  89536. if (!ignoreParentClass) {
  89537. _super.prototype._updateCache.call(this);
  89538. }
  89539. this.updateCacheCalled = false;
  89540. };
  89541. /**
  89542. * Updates the current device position and rotation in the babylon world
  89543. */
  89544. WebVRFreeCamera.prototype.update = function () {
  89545. // Get current device position in babylon world
  89546. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89547. // Get current device rotation in babylon world
  89548. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89549. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89550. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89551. _super.prototype.update.call(this);
  89552. };
  89553. /**
  89554. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89555. * @returns an identity matrix
  89556. */
  89557. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89558. return BABYLON.Matrix.Identity();
  89559. };
  89560. /**
  89561. * This function is called by the two RIG cameras.
  89562. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89563. */
  89564. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89565. var _this = this;
  89566. // Update the parent camera prior to using a child camera to avoid desynchronization
  89567. var parentCamera = this._cameraRigParams["parentCamera"];
  89568. parentCamera._updateCache();
  89569. //WebVR 1.1
  89570. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89571. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89572. if (!this.getScene().useRightHandedSystem) {
  89573. [2, 6, 8, 9, 14].forEach(function (num) {
  89574. _this._webvrViewMatrix.m[num] *= -1;
  89575. });
  89576. }
  89577. // update the camera rotation matrix
  89578. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89579. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89580. // Computing target and final matrix
  89581. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89582. // should the view matrix be updated with scale and position offset?
  89583. if (parentCamera.deviceScaleFactor !== 1) {
  89584. this._webvrViewMatrix.invert();
  89585. // scale the position, if set
  89586. if (parentCamera.deviceScaleFactor) {
  89587. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89588. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89589. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89590. }
  89591. this._webvrViewMatrix.invert();
  89592. }
  89593. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89594. // Compute global position
  89595. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89596. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89597. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89598. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89599. this._markSyncedWithParent();
  89600. return this._webvrViewMatrix;
  89601. };
  89602. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89603. var _this = this;
  89604. var parentCamera = this.parent;
  89605. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89606. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89607. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89608. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89609. //babylon compatible matrix
  89610. if (!this.getScene().useRightHandedSystem) {
  89611. [8, 9, 10, 11].forEach(function (num) {
  89612. _this._projectionMatrix.m[num] *= -1;
  89613. });
  89614. }
  89615. return this._projectionMatrix;
  89616. };
  89617. /**
  89618. * Initializes the controllers and their meshes
  89619. */
  89620. WebVRFreeCamera.prototype.initControllers = function () {
  89621. var _this = this;
  89622. this.controllers = [];
  89623. var manager = this.getScene().gamepadManager;
  89624. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89625. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89626. var webVrController = gamepad;
  89627. if (webVrController.defaultModel) {
  89628. webVrController.defaultModel.setEnabled(false);
  89629. }
  89630. if (webVrController.hand === "right") {
  89631. _this._rightController = null;
  89632. }
  89633. if (webVrController.hand === "left") {
  89634. _this._leftController = null;
  89635. }
  89636. var controllerIndex = _this.controllers.indexOf(webVrController);
  89637. if (controllerIndex !== -1) {
  89638. _this.controllers.splice(controllerIndex, 1);
  89639. }
  89640. }
  89641. });
  89642. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89643. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89644. var webVrController_1 = gamepad;
  89645. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89646. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89647. if (_this.webVROptions.controllerMeshes) {
  89648. if (webVrController_1.defaultModel) {
  89649. webVrController_1.defaultModel.setEnabled(true);
  89650. }
  89651. else {
  89652. // Load the meshes
  89653. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89654. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89655. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89656. if (_this.webVROptions.defaultLightingOnControllers) {
  89657. if (!_this._lightOnControllers) {
  89658. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89659. }
  89660. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89661. var children = mesh.getChildren();
  89662. if (children.length !== 0) {
  89663. children.forEach(function (mesh) {
  89664. light.includedOnlyMeshes.push(mesh);
  89665. activateLightOnSubMeshes_1(mesh, light);
  89666. });
  89667. }
  89668. };
  89669. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89670. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89671. }
  89672. });
  89673. }
  89674. }
  89675. webVrController_1.attachToPoseControlledCamera(_this);
  89676. // since this is async - sanity check. Is the controller already stored?
  89677. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89678. //add to the controllers array
  89679. _this.controllers.push(webVrController_1);
  89680. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89681. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89682. // So we're overriding setting left & right manually to be sure
  89683. var firstViveWandDetected = false;
  89684. for (var i = 0; i < _this.controllers.length; i++) {
  89685. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89686. if (!firstViveWandDetected) {
  89687. firstViveWandDetected = true;
  89688. _this.controllers[i].hand = "left";
  89689. }
  89690. else {
  89691. _this.controllers[i].hand = "right";
  89692. }
  89693. }
  89694. }
  89695. //did we find enough controllers? Great! let the developer know.
  89696. if (_this.controllers.length >= 2) {
  89697. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89698. }
  89699. }
  89700. }
  89701. });
  89702. };
  89703. return WebVRFreeCamera;
  89704. }(BABYLON.FreeCamera));
  89705. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89706. })(BABYLON || (BABYLON = {}));
  89707. //# sourceMappingURL=babylon.webVRCamera.js.map
  89708. var BABYLON;
  89709. (function (BABYLON) {
  89710. // We're mainly based on the logic defined into the FreeCamera code
  89711. /**
  89712. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89713. * being tilted forward or back and left or right.
  89714. */
  89715. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89716. __extends(DeviceOrientationCamera, _super);
  89717. /**
  89718. * Creates a new device orientation camera
  89719. * @param name The name of the camera
  89720. * @param position The start position camera
  89721. * @param scene The scene the camera belongs to
  89722. */
  89723. function DeviceOrientationCamera(name, position, scene) {
  89724. var _this = _super.call(this, name, position, scene) || this;
  89725. _this._quaternionCache = new BABYLON.Quaternion();
  89726. _this.inputs.addDeviceOrientation();
  89727. return _this;
  89728. }
  89729. /**
  89730. * Gets the current instance class name ("DeviceOrientationCamera").
  89731. * This helps avoiding instanceof at run time.
  89732. * @returns the class name
  89733. */
  89734. DeviceOrientationCamera.prototype.getClassName = function () {
  89735. return "DeviceOrientationCamera";
  89736. };
  89737. /**
  89738. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89739. */
  89740. DeviceOrientationCamera.prototype._checkInputs = function () {
  89741. _super.prototype._checkInputs.call(this);
  89742. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89743. if (this._initialQuaternion) {
  89744. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89745. }
  89746. };
  89747. /**
  89748. * Reset the camera to its default orientation on the specified axis only.
  89749. * @param axis The axis to reset
  89750. */
  89751. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89752. var _this = this;
  89753. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89754. //can only work if this camera has a rotation quaternion already.
  89755. if (!this.rotationQuaternion)
  89756. return;
  89757. if (!this._initialQuaternion) {
  89758. this._initialQuaternion = new BABYLON.Quaternion();
  89759. }
  89760. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89761. ['x', 'y', 'z'].forEach(function (axisName) {
  89762. if (!axis[axisName]) {
  89763. _this._initialQuaternion[axisName] = 0;
  89764. }
  89765. else {
  89766. _this._initialQuaternion[axisName] *= -1;
  89767. }
  89768. });
  89769. this._initialQuaternion.normalize();
  89770. //force rotation update
  89771. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89772. };
  89773. return DeviceOrientationCamera;
  89774. }(BABYLON.FreeCamera));
  89775. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89776. })(BABYLON || (BABYLON = {}));
  89777. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89778. var BABYLON;
  89779. (function (BABYLON) {
  89780. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89781. __extends(VRDeviceOrientationFreeCamera, _super);
  89782. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89783. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89784. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89785. var _this = _super.call(this, name, position, scene) || this;
  89786. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89787. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89788. return _this;
  89789. }
  89790. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89791. return "VRDeviceOrientationFreeCamera";
  89792. };
  89793. return VRDeviceOrientationFreeCamera;
  89794. }(BABYLON.DeviceOrientationCamera));
  89795. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89796. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89797. __extends(VRDeviceOrientationGamepadCamera, _super);
  89798. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89799. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89800. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89801. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89802. _this.inputs.addGamepad();
  89803. return _this;
  89804. }
  89805. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89806. return "VRDeviceOrientationGamepadCamera";
  89807. };
  89808. return VRDeviceOrientationGamepadCamera;
  89809. }(VRDeviceOrientationFreeCamera));
  89810. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89811. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89812. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89813. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89814. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89815. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89816. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89817. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89818. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89819. _this.inputs.addVRDeviceOrientation();
  89820. return _this;
  89821. }
  89822. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89823. return "VRDeviceOrientationArcRotateCamera";
  89824. };
  89825. return VRDeviceOrientationArcRotateCamera;
  89826. }(BABYLON.ArcRotateCamera));
  89827. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89828. })(BABYLON || (BABYLON = {}));
  89829. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89830. var BABYLON;
  89831. (function (BABYLON) {
  89832. /**
  89833. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89834. */
  89835. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89836. __extends(AnaglyphFreeCamera, _super);
  89837. /**
  89838. * Creates a new AnaglyphFreeCamera
  89839. * @param name defines camera name
  89840. * @param position defines initial position
  89841. * @param interaxialDistance defines distance between each color axis
  89842. * @param scene defines the hosting scene
  89843. */
  89844. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89845. var _this = _super.call(this, name, position, scene) || this;
  89846. _this.interaxialDistance = interaxialDistance;
  89847. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89848. return _this;
  89849. }
  89850. /**
  89851. * Gets camera class name
  89852. * @returns AnaglyphFreeCamera
  89853. */
  89854. AnaglyphFreeCamera.prototype.getClassName = function () {
  89855. return "AnaglyphFreeCamera";
  89856. };
  89857. return AnaglyphFreeCamera;
  89858. }(BABYLON.FreeCamera));
  89859. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89860. /**
  89861. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89862. */
  89863. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89864. __extends(AnaglyphArcRotateCamera, _super);
  89865. /**
  89866. * Creates a new AnaglyphArcRotateCamera
  89867. * @param name defines camera name
  89868. * @param alpha defines alpha angle (in radians)
  89869. * @param beta defines beta angle (in radians)
  89870. * @param radius defines radius
  89871. * @param target defines camera target
  89872. * @param interaxialDistance defines distance between each color axis
  89873. * @param scene defines the hosting scene
  89874. */
  89875. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89876. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89877. _this.interaxialDistance = interaxialDistance;
  89878. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89879. return _this;
  89880. }
  89881. /**
  89882. * Gets camera class name
  89883. * @returns AnaglyphArcRotateCamera
  89884. */
  89885. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89886. return "AnaglyphArcRotateCamera";
  89887. };
  89888. return AnaglyphArcRotateCamera;
  89889. }(BABYLON.ArcRotateCamera));
  89890. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89891. /**
  89892. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89893. */
  89894. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89895. __extends(AnaglyphGamepadCamera, _super);
  89896. /**
  89897. * Creates a new AnaglyphGamepadCamera
  89898. * @param name defines camera name
  89899. * @param position defines initial position
  89900. * @param interaxialDistance defines distance between each color axis
  89901. * @param scene defines the hosting scene
  89902. */
  89903. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89904. var _this = _super.call(this, name, position, scene) || this;
  89905. _this.interaxialDistance = interaxialDistance;
  89906. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89907. return _this;
  89908. }
  89909. /**
  89910. * Gets camera class name
  89911. * @returns AnaglyphGamepadCamera
  89912. */
  89913. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89914. return "AnaglyphGamepadCamera";
  89915. };
  89916. return AnaglyphGamepadCamera;
  89917. }(BABYLON.GamepadCamera));
  89918. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89919. /**
  89920. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89921. */
  89922. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89923. __extends(AnaglyphUniversalCamera, _super);
  89924. /**
  89925. * Creates a new AnaglyphUniversalCamera
  89926. * @param name defines camera name
  89927. * @param position defines initial position
  89928. * @param interaxialDistance defines distance between each color axis
  89929. * @param scene defines the hosting scene
  89930. */
  89931. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89932. var _this = _super.call(this, name, position, scene) || this;
  89933. _this.interaxialDistance = interaxialDistance;
  89934. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89935. return _this;
  89936. }
  89937. /**
  89938. * Gets camera class name
  89939. * @returns AnaglyphUniversalCamera
  89940. */
  89941. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89942. return "AnaglyphUniversalCamera";
  89943. };
  89944. return AnaglyphUniversalCamera;
  89945. }(BABYLON.UniversalCamera));
  89946. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89947. /**
  89948. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89949. */
  89950. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89951. __extends(StereoscopicFreeCamera, _super);
  89952. /**
  89953. * Creates a new StereoscopicFreeCamera
  89954. * @param name defines camera name
  89955. * @param position defines initial position
  89956. * @param interaxialDistance defines distance between each color axis
  89957. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89958. * @param scene defines the hosting scene
  89959. */
  89960. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89961. var _this = _super.call(this, name, position, scene) || this;
  89962. _this.interaxialDistance = interaxialDistance;
  89963. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89964. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89965. return _this;
  89966. }
  89967. /**
  89968. * Gets camera class name
  89969. * @returns StereoscopicFreeCamera
  89970. */
  89971. StereoscopicFreeCamera.prototype.getClassName = function () {
  89972. return "StereoscopicFreeCamera";
  89973. };
  89974. return StereoscopicFreeCamera;
  89975. }(BABYLON.FreeCamera));
  89976. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89977. /**
  89978. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89979. */
  89980. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89981. __extends(StereoscopicArcRotateCamera, _super);
  89982. /**
  89983. * Creates a new StereoscopicArcRotateCamera
  89984. * @param name defines camera name
  89985. * @param alpha defines alpha angle (in radians)
  89986. * @param beta defines beta angle (in radians)
  89987. * @param radius defines radius
  89988. * @param target defines camera target
  89989. * @param interaxialDistance defines distance between each color axis
  89990. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89991. * @param scene defines the hosting scene
  89992. */
  89993. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89994. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89995. _this.interaxialDistance = interaxialDistance;
  89996. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89997. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89998. return _this;
  89999. }
  90000. /**
  90001. * Gets camera class name
  90002. * @returns StereoscopicArcRotateCamera
  90003. */
  90004. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  90005. return "StereoscopicArcRotateCamera";
  90006. };
  90007. return StereoscopicArcRotateCamera;
  90008. }(BABYLON.ArcRotateCamera));
  90009. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  90010. /**
  90011. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  90012. */
  90013. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  90014. __extends(StereoscopicGamepadCamera, _super);
  90015. /**
  90016. * Creates a new StereoscopicGamepadCamera
  90017. * @param name defines camera name
  90018. * @param position defines initial position
  90019. * @param interaxialDistance defines distance between each color axis
  90020. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90021. * @param scene defines the hosting scene
  90022. */
  90023. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90024. var _this = _super.call(this, name, position, scene) || this;
  90025. _this.interaxialDistance = interaxialDistance;
  90026. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90027. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90028. return _this;
  90029. }
  90030. /**
  90031. * Gets camera class name
  90032. * @returns StereoscopicGamepadCamera
  90033. */
  90034. StereoscopicGamepadCamera.prototype.getClassName = function () {
  90035. return "StereoscopicGamepadCamera";
  90036. };
  90037. return StereoscopicGamepadCamera;
  90038. }(BABYLON.GamepadCamera));
  90039. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  90040. /**
  90041. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  90042. */
  90043. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  90044. __extends(StereoscopicUniversalCamera, _super);
  90045. /**
  90046. * Creates a new StereoscopicUniversalCamera
  90047. * @param name defines camera name
  90048. * @param position defines initial position
  90049. * @param interaxialDistance defines distance between each color axis
  90050. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90051. * @param scene defines the hosting scene
  90052. */
  90053. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90054. var _this = _super.call(this, name, position, scene) || this;
  90055. _this.interaxialDistance = interaxialDistance;
  90056. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90057. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90058. return _this;
  90059. }
  90060. /**
  90061. * Gets camera class name
  90062. * @returns StereoscopicUniversalCamera
  90063. */
  90064. StereoscopicUniversalCamera.prototype.getClassName = function () {
  90065. return "StereoscopicUniversalCamera";
  90066. };
  90067. return StereoscopicUniversalCamera;
  90068. }(BABYLON.UniversalCamera));
  90069. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  90070. })(BABYLON || (BABYLON = {}));
  90071. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  90072. var BABYLON;
  90073. (function (BABYLON) {
  90074. var VRExperienceHelperGazer = /** @class */ (function () {
  90075. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  90076. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  90077. this.scene = scene;
  90078. this._pointerDownOnMeshAsked = false;
  90079. this._isActionableMesh = false;
  90080. this._teleportationRequestInitiated = false;
  90081. this._teleportationBackRequestInitiated = false;
  90082. this._rotationRightAsked = false;
  90083. this._rotationLeftAsked = false;
  90084. this._dpadPressed = true;
  90085. this._activePointer = false;
  90086. this._id = VRExperienceHelperGazer._idCounter++;
  90087. // Gaze tracker
  90088. if (!gazeTrackerToClone) {
  90089. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  90090. this._gazeTracker.bakeCurrentTransformIntoVertices();
  90091. this._gazeTracker.isPickable = false;
  90092. this._gazeTracker.isVisible = false;
  90093. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  90094. targetMat.specularColor = BABYLON.Color3.Black();
  90095. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90096. targetMat.backFaceCulling = false;
  90097. this._gazeTracker.material = targetMat;
  90098. }
  90099. else {
  90100. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  90101. }
  90102. }
  90103. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  90104. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  90105. };
  90106. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  90107. this._pointerDownOnMeshAsked = true;
  90108. if (this._currentHit) {
  90109. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  90110. }
  90111. };
  90112. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  90113. if (this._currentHit) {
  90114. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  90115. }
  90116. this._pointerDownOnMeshAsked = false;
  90117. };
  90118. VRExperienceHelperGazer.prototype._activatePointer = function () {
  90119. this._activePointer = true;
  90120. };
  90121. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  90122. this._activePointer = false;
  90123. };
  90124. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  90125. if (distance === void 0) { distance = 100; }
  90126. };
  90127. VRExperienceHelperGazer.prototype.dispose = function () {
  90128. this._interactionsEnabled = false;
  90129. this._teleportationEnabled = false;
  90130. if (this._gazeTracker) {
  90131. this._gazeTracker.dispose();
  90132. }
  90133. };
  90134. VRExperienceHelperGazer._idCounter = 0;
  90135. return VRExperienceHelperGazer;
  90136. }());
  90137. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  90138. __extends(VRExperienceHelperControllerGazer, _super);
  90139. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  90140. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  90141. _this.webVRController = webVRController;
  90142. // Laser pointer
  90143. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  90144. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  90145. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  90146. laserPointerMaterial.alpha = 0.6;
  90147. _this._laserPointer.material = laserPointerMaterial;
  90148. _this._laserPointer.rotation.x = Math.PI / 2;
  90149. _this._laserPointer.position.z = -0.5;
  90150. _this._laserPointer.isVisible = false;
  90151. if (!webVRController.mesh) {
  90152. // Create an empty mesh that is used prior to loading the high quality model
  90153. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  90154. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  90155. preloadPointerPose.rotation.x = -0.7;
  90156. preloadMesh.addChild(preloadPointerPose);
  90157. webVRController.attachToMesh(preloadMesh);
  90158. }
  90159. _this._setLaserPointerParent(webVRController.mesh);
  90160. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  90161. _this._setLaserPointerParent(mesh);
  90162. });
  90163. return _this;
  90164. }
  90165. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  90166. return this.webVRController.getForwardRay(length);
  90167. };
  90168. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  90169. _super.prototype._activatePointer.call(this);
  90170. this._laserPointer.isVisible = true;
  90171. };
  90172. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  90173. _super.prototype._deactivatePointer.call(this);
  90174. this._laserPointer.isVisible = false;
  90175. };
  90176. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  90177. this._laserPointer.material.emissiveColor = color;
  90178. };
  90179. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  90180. var makeNotPick = function (root) {
  90181. root.name += " laserPointer";
  90182. root.getChildMeshes().forEach(function (c) {
  90183. makeNotPick(c);
  90184. });
  90185. };
  90186. makeNotPick(mesh);
  90187. var childMeshes = mesh.getChildMeshes();
  90188. this.webVRController._pointingPoseNode = null;
  90189. for (var i = 0; i < childMeshes.length; i++) {
  90190. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  90191. mesh = childMeshes[i];
  90192. this.webVRController._pointingPoseNode = mesh;
  90193. break;
  90194. }
  90195. }
  90196. this._laserPointer.parent = mesh;
  90197. };
  90198. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  90199. if (distance === void 0) { distance = 100; }
  90200. this._laserPointer.scaling.y = distance;
  90201. this._laserPointer.position.z = -distance / 2;
  90202. };
  90203. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  90204. _super.prototype.dispose.call(this);
  90205. this._laserPointer.dispose();
  90206. if (this._meshAttachedObserver) {
  90207. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  90208. }
  90209. };
  90210. return VRExperienceHelperControllerGazer;
  90211. }(VRExperienceHelperGazer));
  90212. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  90213. __extends(VRExperienceHelperCameraGazer, _super);
  90214. function VRExperienceHelperCameraGazer(getCamera, scene) {
  90215. var _this = _super.call(this, scene) || this;
  90216. _this.getCamera = getCamera;
  90217. return _this;
  90218. }
  90219. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  90220. var camera = this.getCamera();
  90221. if (camera) {
  90222. return camera.getForwardRay(length);
  90223. }
  90224. else {
  90225. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  90226. }
  90227. };
  90228. return VRExperienceHelperCameraGazer;
  90229. }(VRExperienceHelperGazer));
  90230. /**
  90231. * Helps to quickly add VR support to an existing scene.
  90232. * See http://doc.babylonjs.com/how_to/webvr_helper
  90233. */
  90234. var VRExperienceHelper = /** @class */ (function () {
  90235. /**
  90236. * Instantiates a VRExperienceHelper.
  90237. * Helps to quickly add VR support to an existing scene.
  90238. * @param scene The scene the VRExperienceHelper belongs to.
  90239. * @param webVROptions Options to modify the vr experience helper's behavior.
  90240. */
  90241. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  90242. if (webVROptions === void 0) { webVROptions = {}; }
  90243. var _this = this;
  90244. this.webVROptions = webVROptions;
  90245. // Can the system support WebVR, even if a headset isn't plugged in?
  90246. this._webVRsupported = false;
  90247. // If WebVR is supported, is a headset plugged in and are we ready to present?
  90248. this._webVRready = false;
  90249. // Are we waiting for the requestPresent callback to complete?
  90250. this._webVRrequesting = false;
  90251. // Are we presenting to the headset right now?
  90252. this._webVRpresenting = false;
  90253. // Are we presenting in the fullscreen fallback?
  90254. this._fullscreenVRpresenting = false;
  90255. /**
  90256. * Observable raised when entering VR.
  90257. */
  90258. this.onEnteringVRObservable = new BABYLON.Observable();
  90259. /**
  90260. * Observable raised when exiting VR.
  90261. */
  90262. this.onExitingVRObservable = new BABYLON.Observable();
  90263. /**
  90264. * Observable raised when controller mesh is loaded.
  90265. */
  90266. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90267. this._useCustomVRButton = false;
  90268. this._teleportationRequested = false;
  90269. this._teleportActive = false;
  90270. this._floorMeshesCollection = [];
  90271. this._rotationAllowed = true;
  90272. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  90273. this._isDefaultTeleportationTarget = true;
  90274. this._teleportationFillColor = "#444444";
  90275. this._teleportationBorderColor = "#FFFFFF";
  90276. this._rotationAngle = 0;
  90277. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  90278. this._padSensibilityUp = 0.65;
  90279. this._padSensibilityDown = 0.35;
  90280. this.leftController = null;
  90281. this.rightController = null;
  90282. /**
  90283. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  90284. */
  90285. this.onNewMeshSelected = new BABYLON.Observable();
  90286. /**
  90287. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  90288. */
  90289. this.onNewMeshPicked = new BABYLON.Observable();
  90290. /**
  90291. * Observable raised before camera teleportation
  90292. */
  90293. this.onBeforeCameraTeleport = new BABYLON.Observable();
  90294. /**
  90295. * Observable raised after camera teleportation
  90296. */
  90297. this.onAfterCameraTeleport = new BABYLON.Observable();
  90298. /**
  90299. * Observable raised when current selected mesh gets unselected
  90300. */
  90301. this.onSelectedMeshUnselected = new BABYLON.Observable();
  90302. /**
  90303. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  90304. */
  90305. this.teleportationEnabled = true;
  90306. this._teleportationInitialized = false;
  90307. this._interactionsEnabled = false;
  90308. this._interactionsRequested = false;
  90309. this._displayGaze = true;
  90310. this._displayLaserPointer = true;
  90311. this._onResize = function () {
  90312. _this.moveButtonToBottomRight();
  90313. if (_this._fullscreenVRpresenting && _this._webVRready) {
  90314. _this.exitVR();
  90315. }
  90316. };
  90317. this._onFullscreenChange = function () {
  90318. if (document.fullscreen !== undefined) {
  90319. _this._fullscreenVRpresenting = document.fullscreen;
  90320. }
  90321. else if (document.mozFullScreen !== undefined) {
  90322. _this._fullscreenVRpresenting = document.mozFullScreen;
  90323. }
  90324. else if (document.webkitIsFullScreen !== undefined) {
  90325. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  90326. }
  90327. else if (document.msIsFullScreen !== undefined) {
  90328. _this._fullscreenVRpresenting = document.msIsFullScreen;
  90329. }
  90330. if (!_this._fullscreenVRpresenting && _this._canvas) {
  90331. _this.exitVR();
  90332. if (!_this._useCustomVRButton) {
  90333. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  90334. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  90335. }
  90336. }
  90337. };
  90338. this.beforeRender = function () {
  90339. if (_this.leftController && _this.leftController._activePointer) {
  90340. _this._castRayAndSelectObject(_this.leftController);
  90341. }
  90342. if (_this.rightController && _this.rightController._activePointer) {
  90343. _this._castRayAndSelectObject(_this.rightController);
  90344. }
  90345. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  90346. _this._castRayAndSelectObject(_this._cameraGazer);
  90347. }
  90348. else {
  90349. _this._cameraGazer._gazeTracker.isVisible = false;
  90350. }
  90351. };
  90352. this._onNewGamepadConnected = function (gamepad) {
  90353. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  90354. if (gamepad.leftStick) {
  90355. gamepad.onleftstickchanged(function (stickValues) {
  90356. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  90357. // Listening to classic/xbox gamepad only if no VR controller is active
  90358. if ((!_this.leftController && !_this.rightController) ||
  90359. ((_this.leftController && !_this.leftController._activePointer) &&
  90360. (_this.rightController && !_this.rightController._activePointer))) {
  90361. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  90362. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  90363. }
  90364. }
  90365. });
  90366. }
  90367. if (gamepad.rightStick) {
  90368. gamepad.onrightstickchanged(function (stickValues) {
  90369. if (_this._teleportationInitialized) {
  90370. _this._checkRotate(stickValues, _this._cameraGazer);
  90371. }
  90372. });
  90373. }
  90374. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  90375. gamepad.onbuttondown(function (buttonPressed) {
  90376. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90377. _this._cameraGazer._selectionPointerDown();
  90378. }
  90379. });
  90380. gamepad.onbuttonup(function (buttonPressed) {
  90381. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  90382. _this._cameraGazer._selectionPointerUp();
  90383. }
  90384. });
  90385. }
  90386. }
  90387. else {
  90388. var webVRController = gamepad;
  90389. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  90390. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  90391. _this.rightController = controller;
  90392. }
  90393. else {
  90394. _this.leftController = controller;
  90395. }
  90396. _this._tryEnableInteractionOnController(controller);
  90397. }
  90398. };
  90399. // 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
  90400. this._tryEnableInteractionOnController = function (controller) {
  90401. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  90402. _this._enableInteractionOnController(controller);
  90403. }
  90404. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  90405. _this._enableTeleportationOnController(controller);
  90406. }
  90407. };
  90408. this._onNewGamepadDisconnected = function (gamepad) {
  90409. if (gamepad instanceof BABYLON.WebVRController) {
  90410. if (gamepad.hand === "left" && _this.leftController != null) {
  90411. _this.leftController.dispose();
  90412. _this.leftController = null;
  90413. }
  90414. if (gamepad.hand === "right" && _this.rightController != null) {
  90415. _this.rightController.dispose();
  90416. _this.rightController = null;
  90417. }
  90418. }
  90419. };
  90420. this._workingVector = BABYLON.Vector3.Zero();
  90421. this._workingQuaternion = BABYLON.Quaternion.Identity();
  90422. this._workingMatrix = BABYLON.Matrix.Identity();
  90423. this._scene = scene;
  90424. this._canvas = scene.getEngine().getRenderingCanvas();
  90425. // Parse options
  90426. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  90427. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  90428. }
  90429. if (webVROptions.createDeviceOrientationCamera === undefined) {
  90430. webVROptions.createDeviceOrientationCamera = true;
  90431. }
  90432. if (webVROptions.laserToggle === undefined) {
  90433. webVROptions.laserToggle = true;
  90434. }
  90435. if (webVROptions.defaultHeight === undefined) {
  90436. webVROptions.defaultHeight = 1.7;
  90437. }
  90438. if (webVROptions.useCustomVRButton) {
  90439. this._useCustomVRButton = true;
  90440. if (webVROptions.customVRButton) {
  90441. this._btnVR = webVROptions.customVRButton;
  90442. }
  90443. }
  90444. if (webVROptions.rayLength) {
  90445. this._rayLength = webVROptions.rayLength;
  90446. }
  90447. this._defaultHeight = webVROptions.defaultHeight;
  90448. if (webVROptions.positionScale) {
  90449. this._rayLength *= webVROptions.positionScale;
  90450. this._defaultHeight *= webVROptions.positionScale;
  90451. }
  90452. // Set position
  90453. if (this._scene.activeCamera) {
  90454. this._position = this._scene.activeCamera.position.clone();
  90455. }
  90456. else {
  90457. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  90458. }
  90459. // Set non-vr camera
  90460. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  90461. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  90462. // Copy data from existing camera
  90463. if (this._scene.activeCamera) {
  90464. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90465. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  90466. // Set rotation from previous camera
  90467. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90468. var targetCamera = this._scene.activeCamera;
  90469. if (targetCamera.rotationQuaternion) {
  90470. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90471. }
  90472. else {
  90473. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90474. }
  90475. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90476. }
  90477. }
  90478. this._scene.activeCamera = this._deviceOrientationCamera;
  90479. if (this._canvas) {
  90480. this._scene.activeCamera.attachControl(this._canvas);
  90481. }
  90482. }
  90483. else {
  90484. this._existingCamera = this._scene.activeCamera;
  90485. }
  90486. // Create VR cameras
  90487. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90488. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90489. }
  90490. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90491. this._webVRCamera.useStandingMatrix();
  90492. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90493. // Create default button
  90494. if (!this._useCustomVRButton) {
  90495. this._btnVR = document.createElement("BUTTON");
  90496. this._btnVR.className = "babylonVRicon";
  90497. this._btnVR.id = "babylonVRiconbtn";
  90498. this._btnVR.title = "Click to switch to VR";
  90499. 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) }";
  90500. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90501. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90502. // css += ".babylonVRicon.vrdisplaysupported { }";
  90503. // css += ".babylonVRicon.vrdisplayready { }";
  90504. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90505. var style = document.createElement('style');
  90506. style.appendChild(document.createTextNode(css));
  90507. document.getElementsByTagName('head')[0].appendChild(style);
  90508. this.moveButtonToBottomRight();
  90509. }
  90510. // VR button click event
  90511. if (this._btnVR) {
  90512. this._btnVR.addEventListener("click", function () {
  90513. if (!_this.isInVRMode) {
  90514. _this.enterVR();
  90515. }
  90516. else {
  90517. _this.exitVR();
  90518. }
  90519. });
  90520. }
  90521. // Window events
  90522. window.addEventListener("resize", this._onResize);
  90523. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90524. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90525. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90526. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90527. // Display vr button when headset is connected
  90528. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90529. this.displayVRButton();
  90530. }
  90531. else {
  90532. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90533. if (e.vrDisplay) {
  90534. _this.displayVRButton();
  90535. }
  90536. });
  90537. }
  90538. // Exiting VR mode using 'ESC' key on desktop
  90539. this._onKeyDown = function (event) {
  90540. if (event.keyCode === 27 && _this.isInVRMode) {
  90541. _this.exitVR();
  90542. }
  90543. };
  90544. document.addEventListener("keydown", this._onKeyDown);
  90545. // Exiting VR mode double tapping the touch screen
  90546. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90547. if (_this.isInVRMode) {
  90548. _this.exitVR();
  90549. if (_this._fullscreenVRpresenting) {
  90550. _this._scene.getEngine().switchFullscreen(true);
  90551. }
  90552. }
  90553. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90554. // Listen for WebVR display changes
  90555. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90556. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90557. this._onVRRequestPresentStart = function () {
  90558. _this._webVRrequesting = true;
  90559. _this.updateButtonVisibility();
  90560. };
  90561. this._onVRRequestPresentComplete = function (success) {
  90562. _this._webVRrequesting = false;
  90563. _this.updateButtonVisibility();
  90564. };
  90565. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90566. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90567. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90568. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90569. scene.onDisposeObservable.add(function () {
  90570. _this.dispose();
  90571. });
  90572. // Gamepad connection events
  90573. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90574. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90575. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90576. this.updateButtonVisibility();
  90577. //create easing functions
  90578. this._circleEase = new BABYLON.CircleEase();
  90579. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90580. if (this.webVROptions.floorMeshes) {
  90581. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90582. }
  90583. }
  90584. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90585. /** Return this.onEnteringVRObservable
  90586. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90587. */
  90588. get: function () {
  90589. return this.onEnteringVRObservable;
  90590. },
  90591. enumerable: true,
  90592. configurable: true
  90593. });
  90594. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90595. /** Return this.onExitingVRObservable
  90596. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90597. */
  90598. get: function () {
  90599. return this.onExitingVRObservable;
  90600. },
  90601. enumerable: true,
  90602. configurable: true
  90603. });
  90604. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90605. /** Return this.onControllerMeshLoadedObservable
  90606. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90607. */
  90608. get: function () {
  90609. return this.onControllerMeshLoadedObservable;
  90610. },
  90611. enumerable: true,
  90612. configurable: true
  90613. });
  90614. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90615. /**
  90616. * The mesh used to display where the user is going to teleport.
  90617. */
  90618. get: function () {
  90619. return this._teleportationTarget;
  90620. },
  90621. /**
  90622. * Sets the mesh to be used to display where the user is going to teleport.
  90623. */
  90624. set: function (value) {
  90625. if (value) {
  90626. value.name = "teleportationTarget";
  90627. this._isDefaultTeleportationTarget = false;
  90628. this._teleportationTarget = value;
  90629. }
  90630. },
  90631. enumerable: true,
  90632. configurable: true
  90633. });
  90634. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90635. /**
  90636. * The mesh used to display where the user is selecting,
  90637. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90638. * See http://doc.babylonjs.com/resources/baking_transformations
  90639. */
  90640. get: function () {
  90641. return this._cameraGazer._gazeTracker;
  90642. },
  90643. set: function (value) {
  90644. if (value) {
  90645. this._cameraGazer._gazeTracker = value;
  90646. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90647. this._cameraGazer._gazeTracker.isPickable = false;
  90648. this._cameraGazer._gazeTracker.isVisible = false;
  90649. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90650. if (this.leftController) {
  90651. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90652. }
  90653. if (this.rightController) {
  90654. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90655. }
  90656. }
  90657. },
  90658. enumerable: true,
  90659. configurable: true
  90660. });
  90661. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90662. /**
  90663. * If the ray of the gaze should be displayed.
  90664. */
  90665. get: function () {
  90666. return this._displayGaze;
  90667. },
  90668. /**
  90669. * Sets if the ray of the gaze should be displayed.
  90670. */
  90671. set: function (value) {
  90672. this._displayGaze = value;
  90673. if (!value) {
  90674. this._cameraGazer._gazeTracker.isVisible = false;
  90675. if (this.leftController) {
  90676. this.leftController._gazeTracker.isVisible = false;
  90677. }
  90678. if (this.rightController) {
  90679. this.rightController._gazeTracker.isVisible = false;
  90680. }
  90681. }
  90682. },
  90683. enumerable: true,
  90684. configurable: true
  90685. });
  90686. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90687. /**
  90688. * If the ray of the LaserPointer should be displayed.
  90689. */
  90690. get: function () {
  90691. return this._displayLaserPointer;
  90692. },
  90693. /**
  90694. * Sets if the ray of the LaserPointer should be displayed.
  90695. */
  90696. set: function (value) {
  90697. this._displayLaserPointer = value;
  90698. if (!value) {
  90699. if (this.rightController) {
  90700. this.rightController._deactivatePointer();
  90701. this.rightController._gazeTracker.isVisible = false;
  90702. }
  90703. if (this.leftController) {
  90704. this.leftController._deactivatePointer();
  90705. this.leftController._gazeTracker.isVisible = false;
  90706. }
  90707. }
  90708. else {
  90709. if (this.rightController) {
  90710. this.rightController._activatePointer();
  90711. }
  90712. if (this.leftController) {
  90713. this.leftController._activatePointer();
  90714. }
  90715. }
  90716. },
  90717. enumerable: true,
  90718. configurable: true
  90719. });
  90720. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90721. /**
  90722. * The deviceOrientationCamera used as the camera when not in VR.
  90723. */
  90724. get: function () {
  90725. return this._deviceOrientationCamera;
  90726. },
  90727. enumerable: true,
  90728. configurable: true
  90729. });
  90730. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90731. /**
  90732. * Based on the current WebVR support, returns the current VR camera used.
  90733. */
  90734. get: function () {
  90735. if (this._webVRready) {
  90736. return this._webVRCamera;
  90737. }
  90738. else {
  90739. return this._scene.activeCamera;
  90740. }
  90741. },
  90742. enumerable: true,
  90743. configurable: true
  90744. });
  90745. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90746. /**
  90747. * The webVRCamera which is used when in VR.
  90748. */
  90749. get: function () {
  90750. return this._webVRCamera;
  90751. },
  90752. enumerable: true,
  90753. configurable: true
  90754. });
  90755. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90756. /**
  90757. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90758. */
  90759. get: function () {
  90760. return this._vrDeviceOrientationCamera;
  90761. },
  90762. enumerable: true,
  90763. configurable: true
  90764. });
  90765. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90766. get: function () {
  90767. var result = this._cameraGazer._teleportationRequestInitiated
  90768. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90769. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90770. return result;
  90771. },
  90772. enumerable: true,
  90773. configurable: true
  90774. });
  90775. // Raised when one of the controller has loaded successfully its associated default mesh
  90776. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90777. if (this.leftController && this.leftController.webVRController == webVRController) {
  90778. if (webVRController.mesh) {
  90779. this.leftController._setLaserPointerParent(webVRController.mesh);
  90780. }
  90781. }
  90782. if (this.rightController && this.rightController.webVRController == webVRController) {
  90783. if (webVRController.mesh) {
  90784. this.rightController._setLaserPointerParent(webVRController.mesh);
  90785. }
  90786. }
  90787. try {
  90788. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90789. }
  90790. catch (err) {
  90791. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90792. }
  90793. };
  90794. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90795. /**
  90796. * Gets a value indicating if we are currently in VR mode.
  90797. */
  90798. get: function () {
  90799. return this._webVRpresenting || this._fullscreenVRpresenting;
  90800. },
  90801. enumerable: true,
  90802. configurable: true
  90803. });
  90804. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90805. var vrDisplay = this._scene.getEngine().getVRDevice();
  90806. if (vrDisplay) {
  90807. var wasPresenting = this._webVRpresenting;
  90808. // A VR display is connected
  90809. this._webVRpresenting = vrDisplay.isPresenting;
  90810. if (wasPresenting && !this._webVRpresenting)
  90811. this.exitVR();
  90812. }
  90813. else {
  90814. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90815. }
  90816. this.updateButtonVisibility();
  90817. };
  90818. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90819. this._webVRsupported = eventArgs.vrSupported;
  90820. this._webVRready = !!eventArgs.vrDisplay;
  90821. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90822. this.updateButtonVisibility();
  90823. };
  90824. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90825. if (this._canvas && !this._useCustomVRButton) {
  90826. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90827. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90828. }
  90829. };
  90830. VRExperienceHelper.prototype.displayVRButton = function () {
  90831. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90832. document.body.appendChild(this._btnVR);
  90833. this._btnVRDisplayed = true;
  90834. }
  90835. };
  90836. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90837. if (!this._btnVR || this._useCustomVRButton) {
  90838. return;
  90839. }
  90840. this._btnVR.className = "babylonVRicon";
  90841. if (this.isInVRMode) {
  90842. this._btnVR.className += " vrdisplaypresenting";
  90843. }
  90844. else {
  90845. if (this._webVRready)
  90846. this._btnVR.className += " vrdisplayready";
  90847. if (this._webVRsupported)
  90848. this._btnVR.className += " vrdisplaysupported";
  90849. if (this._webVRrequesting)
  90850. this._btnVR.className += " vrdisplayrequesting";
  90851. }
  90852. };
  90853. /**
  90854. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90855. * Otherwise, will use the fullscreen API.
  90856. */
  90857. VRExperienceHelper.prototype.enterVR = function () {
  90858. if (this.onEnteringVRObservable) {
  90859. try {
  90860. this.onEnteringVRObservable.notifyObservers(this);
  90861. }
  90862. catch (err) {
  90863. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90864. }
  90865. }
  90866. if (this._scene.activeCamera) {
  90867. this._position = this._scene.activeCamera.position.clone();
  90868. // make sure that we return to the last active camera
  90869. this._existingCamera = this._scene.activeCamera;
  90870. }
  90871. if (this._webVRrequesting)
  90872. return;
  90873. // If WebVR is supported and a headset is connected
  90874. if (this._webVRready) {
  90875. if (!this._webVRpresenting) {
  90876. this._webVRCamera.position = this._position;
  90877. this._scene.activeCamera = this._webVRCamera;
  90878. }
  90879. }
  90880. else if (this._vrDeviceOrientationCamera) {
  90881. this._vrDeviceOrientationCamera.position = this._position;
  90882. if (this._scene.activeCamera) {
  90883. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90884. }
  90885. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90886. this._scene.getEngine().switchFullscreen(true);
  90887. this.updateButtonVisibility();
  90888. }
  90889. if (this._scene.activeCamera && this._canvas) {
  90890. this._scene.activeCamera.attachControl(this._canvas);
  90891. }
  90892. if (this._interactionsEnabled) {
  90893. this._scene.registerBeforeRender(this.beforeRender);
  90894. }
  90895. };
  90896. /**
  90897. * Attempt to exit VR, or fullscreen.
  90898. */
  90899. VRExperienceHelper.prototype.exitVR = function () {
  90900. if (this.onExitingVRObservable) {
  90901. try {
  90902. this.onExitingVRObservable.notifyObservers(this);
  90903. }
  90904. catch (err) {
  90905. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90906. }
  90907. }
  90908. if (this._webVRpresenting) {
  90909. this._scene.getEngine().disableVR();
  90910. }
  90911. if (this._scene.activeCamera) {
  90912. this._position = this._scene.activeCamera.position.clone();
  90913. }
  90914. if (this._deviceOrientationCamera) {
  90915. this._deviceOrientationCamera.position = this._position;
  90916. this._scene.activeCamera = this._deviceOrientationCamera;
  90917. if (this._canvas) {
  90918. this._scene.activeCamera.attachControl(this._canvas);
  90919. }
  90920. }
  90921. else if (this._existingCamera) {
  90922. this._existingCamera.position = this._position;
  90923. this._scene.activeCamera = this._existingCamera;
  90924. }
  90925. this.updateButtonVisibility();
  90926. if (this._interactionsEnabled) {
  90927. this._scene.unregisterBeforeRender(this.beforeRender);
  90928. }
  90929. // resize to update width and height when exiting vr exits fullscreen
  90930. this._scene.getEngine().resize();
  90931. };
  90932. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90933. /**
  90934. * The position of the vr experience helper.
  90935. */
  90936. get: function () {
  90937. return this._position;
  90938. },
  90939. /**
  90940. * Sets the position of the vr experience helper.
  90941. */
  90942. set: function (value) {
  90943. this._position = value;
  90944. if (this._scene.activeCamera) {
  90945. this._scene.activeCamera.position = value;
  90946. }
  90947. },
  90948. enumerable: true,
  90949. configurable: true
  90950. });
  90951. /**
  90952. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90953. */
  90954. VRExperienceHelper.prototype.enableInteractions = function () {
  90955. var _this = this;
  90956. if (!this._interactionsEnabled) {
  90957. this._interactionsRequested = true;
  90958. if (this.leftController) {
  90959. this._enableInteractionOnController(this.leftController);
  90960. }
  90961. if (this.rightController) {
  90962. this._enableInteractionOnController(this.rightController);
  90963. }
  90964. this.raySelectionPredicate = function (mesh) {
  90965. return mesh.isVisible;
  90966. };
  90967. this.meshSelectionPredicate = function (mesh) {
  90968. return true;
  90969. };
  90970. this._raySelectionPredicate = function (mesh) {
  90971. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90972. && mesh.name.indexOf("teleportationTarget") === -1
  90973. && mesh.name.indexOf("torusTeleportation") === -1
  90974. && mesh.name.indexOf("laserPointer") === -1)) {
  90975. return _this.raySelectionPredicate(mesh);
  90976. }
  90977. return false;
  90978. };
  90979. this._interactionsEnabled = true;
  90980. }
  90981. };
  90982. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90983. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90984. if (this._floorMeshesCollection[i].id === mesh.id) {
  90985. return true;
  90986. }
  90987. }
  90988. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90989. return true;
  90990. }
  90991. return false;
  90992. };
  90993. /**
  90994. * Adds a floor mesh to be used for teleportation.
  90995. * @param floorMesh the mesh to be used for teleportation.
  90996. */
  90997. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90998. if (!this._floorMeshesCollection) {
  90999. return;
  91000. }
  91001. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  91002. return;
  91003. }
  91004. this._floorMeshesCollection.push(floorMesh);
  91005. };
  91006. /**
  91007. * Removes a floor mesh from being used for teleportation.
  91008. * @param floorMesh the mesh to be removed.
  91009. */
  91010. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  91011. if (!this._floorMeshesCollection) {
  91012. return;
  91013. }
  91014. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  91015. if (meshIndex !== -1) {
  91016. this._floorMeshesCollection.splice(meshIndex, 1);
  91017. }
  91018. };
  91019. /**
  91020. * Enables interactions and teleportation using the VR controllers and gaze.
  91021. * @param vrTeleportationOptions options to modify teleportation behavior.
  91022. */
  91023. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  91024. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  91025. if (!this._teleportationInitialized) {
  91026. this._teleportationRequested = true;
  91027. this.enableInteractions();
  91028. if (vrTeleportationOptions.floorMeshName) {
  91029. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  91030. }
  91031. if (vrTeleportationOptions.floorMeshes) {
  91032. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  91033. }
  91034. if (this.leftController != null) {
  91035. this._enableTeleportationOnController(this.leftController);
  91036. }
  91037. if (this.rightController != null) {
  91038. this._enableTeleportationOnController(this.rightController);
  91039. }
  91040. // Creates an image processing post process for the vignette not relying
  91041. // on the main scene configuration for image processing to reduce setup and spaces
  91042. // (gamma/linear) conflicts.
  91043. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  91044. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  91045. imageProcessingConfiguration.vignetteEnabled = true;
  91046. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  91047. this._webVRCamera.detachPostProcess(this._postProcessMove);
  91048. this._teleportationInitialized = true;
  91049. if (this._isDefaultTeleportationTarget) {
  91050. this._createTeleportationCircles();
  91051. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  91052. }
  91053. }
  91054. };
  91055. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  91056. var _this = this;
  91057. var controllerMesh = controller.webVRController.mesh;
  91058. if (controllerMesh) {
  91059. controller._interactionsEnabled = true;
  91060. controller._activatePointer();
  91061. if (this.webVROptions.laserToggle) {
  91062. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  91063. // Enabling / disabling laserPointer
  91064. if (_this._displayLaserPointer && stateObject.value === 1) {
  91065. if (controller._activePointer) {
  91066. controller._deactivatePointer();
  91067. }
  91068. else {
  91069. controller._activatePointer();
  91070. }
  91071. if (_this.displayGaze) {
  91072. controller._gazeTracker.isVisible = controller._activePointer;
  91073. }
  91074. }
  91075. });
  91076. }
  91077. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  91078. if (!controller._pointerDownOnMeshAsked) {
  91079. if (stateObject.value > _this._padSensibilityUp) {
  91080. controller._selectionPointerDown();
  91081. }
  91082. }
  91083. else if (stateObject.value < _this._padSensibilityDown) {
  91084. controller._selectionPointerUp();
  91085. }
  91086. });
  91087. }
  91088. };
  91089. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  91090. // Dont teleport if another gaze already requested teleportation
  91091. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  91092. return;
  91093. }
  91094. if (!gazer._teleportationRequestInitiated) {
  91095. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  91096. gazer._activatePointer();
  91097. gazer._teleportationRequestInitiated = true;
  91098. }
  91099. }
  91100. else {
  91101. // Listening to the proper controller values changes to confirm teleportation
  91102. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  91103. if (this._teleportActive) {
  91104. this._teleportCamera(this._haloCenter);
  91105. }
  91106. gazer._teleportationRequestInitiated = false;
  91107. }
  91108. }
  91109. };
  91110. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  91111. // Only rotate when user is not currently selecting a teleportation location
  91112. if (gazer._teleportationRequestInitiated) {
  91113. return;
  91114. }
  91115. if (!gazer._rotationLeftAsked) {
  91116. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  91117. gazer._rotationLeftAsked = true;
  91118. if (this._rotationAllowed) {
  91119. this._rotateCamera(false);
  91120. }
  91121. }
  91122. }
  91123. else {
  91124. if (stateObject.x > -this._padSensibilityDown) {
  91125. gazer._rotationLeftAsked = false;
  91126. }
  91127. }
  91128. if (!gazer._rotationRightAsked) {
  91129. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  91130. gazer._rotationRightAsked = true;
  91131. if (this._rotationAllowed) {
  91132. this._rotateCamera(true);
  91133. }
  91134. }
  91135. }
  91136. else {
  91137. if (stateObject.x < this._padSensibilityDown) {
  91138. gazer._rotationRightAsked = false;
  91139. }
  91140. }
  91141. };
  91142. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  91143. // Only teleport backwards when user is not currently selecting a teleportation location
  91144. if (gazer._teleportationRequestInitiated) {
  91145. return;
  91146. }
  91147. // Teleport backwards
  91148. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  91149. if (!gazer._teleportationBackRequestInitiated) {
  91150. if (!this.currentVRCamera) {
  91151. return;
  91152. }
  91153. // Get rotation and position of the current camera
  91154. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  91155. var position = this.currentVRCamera.position;
  91156. // If the camera has device position, use that instead
  91157. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  91158. rotation = this.currentVRCamera.deviceRotationQuaternion;
  91159. position = this.currentVRCamera.devicePosition;
  91160. }
  91161. // Get matrix with only the y rotation of the device rotation
  91162. rotation.toEulerAnglesToRef(this._workingVector);
  91163. this._workingVector.z = 0;
  91164. this._workingVector.x = 0;
  91165. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  91166. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  91167. // Rotate backwards ray by device rotation to cast at the ground behind the user
  91168. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  91169. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  91170. var ray = new BABYLON.Ray(position, this._workingVector);
  91171. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91172. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  91173. this._teleportCamera(hit.pickedPoint);
  91174. }
  91175. gazer._teleportationBackRequestInitiated = true;
  91176. }
  91177. }
  91178. else {
  91179. gazer._teleportationBackRequestInitiated = false;
  91180. }
  91181. };
  91182. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  91183. var _this = this;
  91184. var controllerMesh = controller.webVRController.mesh;
  91185. if (controllerMesh) {
  91186. if (!controller._interactionsEnabled) {
  91187. this._enableInteractionOnController(controller);
  91188. }
  91189. controller._interactionsEnabled = true;
  91190. controller._teleportationEnabled = true;
  91191. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91192. controller._dpadPressed = false;
  91193. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  91194. controller._dpadPressed = stateObject.pressed;
  91195. if (!controller._dpadPressed) {
  91196. controller._rotationLeftAsked = false;
  91197. controller._rotationRightAsked = false;
  91198. controller._teleportationBackRequestInitiated = false;
  91199. }
  91200. });
  91201. }
  91202. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  91203. if (_this.teleportationEnabled) {
  91204. _this._checkTeleportBackwards(stateObject, controller);
  91205. _this._checkTeleportWithRay(stateObject, controller);
  91206. }
  91207. _this._checkRotate(stateObject, controller);
  91208. });
  91209. }
  91210. };
  91211. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  91212. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  91213. this._teleportationTarget.isPickable = false;
  91214. var length = 512;
  91215. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  91216. dynamicTexture.hasAlpha = true;
  91217. var context = dynamicTexture.getContext();
  91218. var centerX = length / 2;
  91219. var centerY = length / 2;
  91220. var radius = 200;
  91221. context.beginPath();
  91222. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  91223. context.fillStyle = this._teleportationFillColor;
  91224. context.fill();
  91225. context.lineWidth = 10;
  91226. context.strokeStyle = this._teleportationBorderColor;
  91227. context.stroke();
  91228. context.closePath();
  91229. dynamicTexture.update();
  91230. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  91231. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  91232. this._teleportationTarget.material = teleportationCircleMaterial;
  91233. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  91234. torus.isPickable = false;
  91235. torus.parent = this._teleportationTarget;
  91236. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91237. var keys = [];
  91238. keys.push({
  91239. frame: 0,
  91240. value: 0
  91241. });
  91242. keys.push({
  91243. frame: 30,
  91244. value: 0.4
  91245. });
  91246. keys.push({
  91247. frame: 60,
  91248. value: 0
  91249. });
  91250. animationInnerCircle.setKeys(keys);
  91251. var easingFunction = new BABYLON.SineEase();
  91252. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91253. animationInnerCircle.setEasingFunction(easingFunction);
  91254. torus.animations = [];
  91255. torus.animations.push(animationInnerCircle);
  91256. this._scene.beginAnimation(torus, 0, 60, true);
  91257. this._hideTeleportationTarget();
  91258. };
  91259. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  91260. this._teleportActive = true;
  91261. if (this._teleportationInitialized) {
  91262. this._teleportationTarget.isVisible = true;
  91263. if (this._isDefaultTeleportationTarget) {
  91264. this._teleportationTarget.getChildren()[0].isVisible = true;
  91265. }
  91266. }
  91267. };
  91268. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  91269. this._teleportActive = false;
  91270. if (this._teleportationInitialized) {
  91271. this._teleportationTarget.isVisible = false;
  91272. if (this._isDefaultTeleportationTarget) {
  91273. this._teleportationTarget.getChildren()[0].isVisible = false;
  91274. }
  91275. }
  91276. };
  91277. VRExperienceHelper.prototype._rotateCamera = function (right) {
  91278. var _this = this;
  91279. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91280. return;
  91281. }
  91282. if (right) {
  91283. this._rotationAngle++;
  91284. }
  91285. else {
  91286. this._rotationAngle--;
  91287. }
  91288. this.currentVRCamera.animations = [];
  91289. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  91290. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91291. var animationRotationKeys = [];
  91292. animationRotationKeys.push({
  91293. frame: 0,
  91294. value: this.currentVRCamera.rotationQuaternion
  91295. });
  91296. animationRotationKeys.push({
  91297. frame: 6,
  91298. value: target
  91299. });
  91300. animationRotation.setKeys(animationRotationKeys);
  91301. animationRotation.setEasingFunction(this._circleEase);
  91302. this.currentVRCamera.animations.push(animationRotation);
  91303. this._postProcessMove.animations = [];
  91304. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91305. var vignetteWeightKeys = [];
  91306. vignetteWeightKeys.push({
  91307. frame: 0,
  91308. value: 0
  91309. });
  91310. vignetteWeightKeys.push({
  91311. frame: 3,
  91312. value: 4
  91313. });
  91314. vignetteWeightKeys.push({
  91315. frame: 6,
  91316. value: 0
  91317. });
  91318. animationPP.setKeys(vignetteWeightKeys);
  91319. animationPP.setEasingFunction(this._circleEase);
  91320. this._postProcessMove.animations.push(animationPP);
  91321. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91322. var vignetteStretchKeys = [];
  91323. vignetteStretchKeys.push({
  91324. frame: 0,
  91325. value: 0
  91326. });
  91327. vignetteStretchKeys.push({
  91328. frame: 3,
  91329. value: 10
  91330. });
  91331. vignetteStretchKeys.push({
  91332. frame: 6,
  91333. value: 0
  91334. });
  91335. animationPP2.setKeys(vignetteStretchKeys);
  91336. animationPP2.setEasingFunction(this._circleEase);
  91337. this._postProcessMove.animations.push(animationPP2);
  91338. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91339. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91340. this._postProcessMove.samples = 4;
  91341. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91342. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  91343. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91344. });
  91345. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  91346. };
  91347. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  91348. if (hit.pickedPoint) {
  91349. if (gazer._teleportationRequestInitiated) {
  91350. this._displayTeleportationTarget();
  91351. this._haloCenter.copyFrom(hit.pickedPoint);
  91352. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  91353. }
  91354. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  91355. if (pickNormal) {
  91356. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91357. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91358. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  91359. }
  91360. this._teleportationTarget.position.y += 0.1;
  91361. }
  91362. };
  91363. VRExperienceHelper.prototype._teleportCamera = function (location) {
  91364. var _this = this;
  91365. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91366. return;
  91367. }
  91368. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  91369. // offset of the headset from the anchor.
  91370. if (this.webVRCamera.leftCamera) {
  91371. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  91372. this._workingVector.subtractInPlace(this.webVRCamera.position);
  91373. location.subtractToRef(this._workingVector, this._workingVector);
  91374. }
  91375. else {
  91376. this._workingVector.copyFrom(location);
  91377. }
  91378. // Add height to account for user's height offset
  91379. if (this.isInVRMode) {
  91380. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  91381. }
  91382. else {
  91383. this._workingVector.y += this._defaultHeight;
  91384. }
  91385. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  91386. // Create animation from the camera's position to the new location
  91387. this.currentVRCamera.animations = [];
  91388. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91389. var animationCameraTeleportationKeys = [{
  91390. frame: 0,
  91391. value: this.currentVRCamera.position
  91392. },
  91393. {
  91394. frame: 11,
  91395. value: this._workingVector
  91396. }
  91397. ];
  91398. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  91399. animationCameraTeleportation.setEasingFunction(this._circleEase);
  91400. this.currentVRCamera.animations.push(animationCameraTeleportation);
  91401. this._postProcessMove.animations = [];
  91402. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91403. var vignetteWeightKeys = [];
  91404. vignetteWeightKeys.push({
  91405. frame: 0,
  91406. value: 0
  91407. });
  91408. vignetteWeightKeys.push({
  91409. frame: 5,
  91410. value: 8
  91411. });
  91412. vignetteWeightKeys.push({
  91413. frame: 11,
  91414. value: 0
  91415. });
  91416. animationPP.setKeys(vignetteWeightKeys);
  91417. this._postProcessMove.animations.push(animationPP);
  91418. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  91419. var vignetteStretchKeys = [];
  91420. vignetteStretchKeys.push({
  91421. frame: 0,
  91422. value: 0
  91423. });
  91424. vignetteStretchKeys.push({
  91425. frame: 5,
  91426. value: 10
  91427. });
  91428. vignetteStretchKeys.push({
  91429. frame: 11,
  91430. value: 0
  91431. });
  91432. animationPP2.setKeys(vignetteStretchKeys);
  91433. this._postProcessMove.animations.push(animationPP2);
  91434. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  91435. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  91436. this._webVRCamera.attachPostProcess(this._postProcessMove);
  91437. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  91438. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  91439. });
  91440. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  91441. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  91442. });
  91443. this._hideTeleportationTarget();
  91444. };
  91445. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  91446. if (normal) {
  91447. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  91448. if (angle < Math.PI / 2) {
  91449. normal.scaleInPlace(-1);
  91450. }
  91451. }
  91452. return normal;
  91453. };
  91454. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  91455. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  91456. return;
  91457. }
  91458. var ray = gazer._getForwardRay(this._rayLength);
  91459. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91460. if (hit) {
  91461. // Populate the contrllers mesh that can be used for drag/drop
  91462. if (gazer._laserPointer) {
  91463. hit.originMesh = gazer._laserPointer.parent;
  91464. }
  91465. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  91466. }
  91467. gazer._currentHit = hit;
  91468. // Moving the gazeTracker on the mesh face targetted
  91469. if (hit && hit.pickedPoint) {
  91470. if (this._displayGaze) {
  91471. var multiplier = 1;
  91472. gazer._gazeTracker.isVisible = true;
  91473. if (gazer._isActionableMesh) {
  91474. multiplier = 3;
  91475. }
  91476. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91477. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91478. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91479. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91480. // To avoid z-fighting
  91481. var deltaFighting = 0.002;
  91482. if (pickNormal) {
  91483. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91484. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91485. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91486. }
  91487. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91488. if (gazer._gazeTracker.position.x < 0) {
  91489. gazer._gazeTracker.position.x += deltaFighting;
  91490. }
  91491. else {
  91492. gazer._gazeTracker.position.x -= deltaFighting;
  91493. }
  91494. if (gazer._gazeTracker.position.y < 0) {
  91495. gazer._gazeTracker.position.y += deltaFighting;
  91496. }
  91497. else {
  91498. gazer._gazeTracker.position.y -= deltaFighting;
  91499. }
  91500. if (gazer._gazeTracker.position.z < 0) {
  91501. gazer._gazeTracker.position.z += deltaFighting;
  91502. }
  91503. else {
  91504. gazer._gazeTracker.position.z -= deltaFighting;
  91505. }
  91506. }
  91507. // Changing the size of the laser pointer based on the distance from the targetted point
  91508. gazer._updatePointerDistance(hit.distance);
  91509. }
  91510. else {
  91511. gazer._updatePointerDistance();
  91512. gazer._gazeTracker.isVisible = false;
  91513. }
  91514. if (hit && hit.pickedMesh) {
  91515. // The object selected is the floor, we're in a teleportation scenario
  91516. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91517. // Moving the teleportation area to this targetted point
  91518. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91519. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91520. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91521. }
  91522. gazer._currentMeshSelected = null;
  91523. if (gazer._teleportationRequestInitiated) {
  91524. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91525. }
  91526. return;
  91527. }
  91528. // If not, we're in a selection scenario
  91529. //this._teleportationAllowed = false;
  91530. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91531. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91532. this.onNewMeshPicked.notifyObservers(hit);
  91533. gazer._currentMeshSelected = hit.pickedMesh;
  91534. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91535. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91536. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91537. gazer._isActionableMesh = true;
  91538. }
  91539. else {
  91540. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91541. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91542. gazer._isActionableMesh = false;
  91543. }
  91544. try {
  91545. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91546. }
  91547. catch (err) {
  91548. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91549. }
  91550. }
  91551. else {
  91552. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91553. gazer._currentMeshSelected = null;
  91554. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91555. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91556. }
  91557. }
  91558. }
  91559. else {
  91560. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91561. gazer._currentMeshSelected = null;
  91562. //this._teleportationAllowed = false;
  91563. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91564. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91565. }
  91566. };
  91567. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91568. if (mesh) {
  91569. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91570. }
  91571. };
  91572. /**
  91573. * Sets the color of the laser ray from the vr controllers.
  91574. * @param color new color for the ray.
  91575. */
  91576. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91577. if (this.leftController) {
  91578. this.leftController._setLaserPointerColor(color);
  91579. }
  91580. if (this.rightController) {
  91581. this.rightController._setLaserPointerColor(color);
  91582. }
  91583. };
  91584. /**
  91585. * Sets the color of the ray from the vr headsets gaze.
  91586. * @param color new color for the ray.
  91587. */
  91588. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91589. if (!this._cameraGazer._gazeTracker.material) {
  91590. return;
  91591. }
  91592. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91593. if (this.leftController) {
  91594. this.leftController._gazeTracker.material.emissiveColor = color;
  91595. }
  91596. if (this.rightController) {
  91597. this.rightController._gazeTracker.material.emissiveColor = color;
  91598. }
  91599. };
  91600. /**
  91601. * Exits VR and disposes of the vr experience helper
  91602. */
  91603. VRExperienceHelper.prototype.dispose = function () {
  91604. if (this.isInVRMode) {
  91605. this.exitVR();
  91606. }
  91607. if (this._postProcessMove) {
  91608. this._postProcessMove.dispose();
  91609. }
  91610. if (this._webVRCamera) {
  91611. this._webVRCamera.dispose();
  91612. }
  91613. if (this._vrDeviceOrientationCamera) {
  91614. this._vrDeviceOrientationCamera.dispose();
  91615. }
  91616. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91617. document.body.removeChild(this._btnVR);
  91618. }
  91619. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91620. this._deviceOrientationCamera.dispose();
  91621. }
  91622. if (this._cameraGazer) {
  91623. this._cameraGazer.dispose();
  91624. }
  91625. if (this.leftController) {
  91626. this.leftController.dispose();
  91627. }
  91628. if (this.rightController) {
  91629. this.rightController.dispose();
  91630. }
  91631. if (this._teleportationTarget) {
  91632. this._teleportationTarget.dispose();
  91633. }
  91634. this._floorMeshesCollection = [];
  91635. document.removeEventListener("keydown", this._onKeyDown);
  91636. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91637. window.removeEventListener("resize", this._onResize);
  91638. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91639. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91640. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91641. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91642. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91643. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91644. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91645. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91646. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91647. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91648. this._scene.unregisterBeforeRender(this.beforeRender);
  91649. };
  91650. /**
  91651. * Gets the name of the VRExperienceHelper class
  91652. * @returns "VRExperienceHelper"
  91653. */
  91654. VRExperienceHelper.prototype.getClassName = function () {
  91655. return "VRExperienceHelper";
  91656. };
  91657. return VRExperienceHelper;
  91658. }());
  91659. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91660. })(BABYLON || (BABYLON = {}));
  91661. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91662. // Mainly based on these 2 articles :
  91663. // 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
  91664. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91665. var BABYLON;
  91666. (function (BABYLON) {
  91667. /**
  91668. * Defines the potential axis of a Joystick
  91669. */
  91670. var JoystickAxis;
  91671. (function (JoystickAxis) {
  91672. /** X axis */
  91673. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91674. /** Y axis */
  91675. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91676. /** Z axis */
  91677. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91678. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91679. /**
  91680. * Class used to define virtual joystick (used in touch mode)
  91681. */
  91682. var VirtualJoystick = /** @class */ (function () {
  91683. /**
  91684. * Creates a new virtual joystick
  91685. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91686. */
  91687. function VirtualJoystick(leftJoystick) {
  91688. var _this = this;
  91689. if (leftJoystick) {
  91690. this._leftJoystick = true;
  91691. }
  91692. else {
  91693. this._leftJoystick = false;
  91694. }
  91695. VirtualJoystick._globalJoystickIndex++;
  91696. // By default left & right arrow keys are moving the X
  91697. // and up & down keys are moving the Y
  91698. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91699. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91700. this.reverseLeftRight = false;
  91701. this.reverseUpDown = false;
  91702. // collections of pointers
  91703. this._touches = new BABYLON.StringDictionary();
  91704. this.deltaPosition = BABYLON.Vector3.Zero();
  91705. this._joystickSensibility = 25;
  91706. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91707. this._onResize = function (evt) {
  91708. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91709. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91710. if (VirtualJoystick.vjCanvas) {
  91711. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91712. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91713. }
  91714. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91715. };
  91716. // injecting a canvas element on top of the canvas 3D game
  91717. if (!VirtualJoystick.vjCanvas) {
  91718. window.addEventListener("resize", this._onResize, false);
  91719. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91720. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91721. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91722. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91723. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91724. VirtualJoystick.vjCanvas.style.width = "100%";
  91725. VirtualJoystick.vjCanvas.style.height = "100%";
  91726. VirtualJoystick.vjCanvas.style.position = "absolute";
  91727. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91728. VirtualJoystick.vjCanvas.style.top = "0px";
  91729. VirtualJoystick.vjCanvas.style.left = "0px";
  91730. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91731. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91732. // Support for jQuery PEP polyfill
  91733. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91734. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91735. if (!context) {
  91736. throw new Error("Unable to create canvas for virtual joystick");
  91737. }
  91738. VirtualJoystick.vjCanvasContext = context;
  91739. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91740. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91741. document.body.appendChild(VirtualJoystick.vjCanvas);
  91742. }
  91743. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91744. this.pressed = false;
  91745. // default joystick color
  91746. this._joystickColor = "cyan";
  91747. this._joystickPointerID = -1;
  91748. // current joystick position
  91749. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91750. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91751. // origin joystick position
  91752. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91753. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91754. this._onPointerDownHandlerRef = function (evt) {
  91755. _this._onPointerDown(evt);
  91756. };
  91757. this._onPointerMoveHandlerRef = function (evt) {
  91758. _this._onPointerMove(evt);
  91759. };
  91760. this._onPointerUpHandlerRef = function (evt) {
  91761. _this._onPointerUp(evt);
  91762. };
  91763. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91764. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91765. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91766. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91767. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91768. evt.preventDefault(); // Disables system menu
  91769. }, false);
  91770. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91771. }
  91772. /**
  91773. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91774. * @param newJoystickSensibility defines the new sensibility
  91775. */
  91776. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91777. this._joystickSensibility = newJoystickSensibility;
  91778. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91779. };
  91780. VirtualJoystick.prototype._onPointerDown = function (e) {
  91781. var positionOnScreenCondition;
  91782. e.preventDefault();
  91783. if (this._leftJoystick === true) {
  91784. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91785. }
  91786. else {
  91787. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91788. }
  91789. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91790. // First contact will be dedicated to the virtual joystick
  91791. this._joystickPointerID = e.pointerId;
  91792. this._joystickPointerStartPos.x = e.clientX;
  91793. this._joystickPointerStartPos.y = e.clientY;
  91794. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91795. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91796. this._deltaJoystickVector.x = 0;
  91797. this._deltaJoystickVector.y = 0;
  91798. this.pressed = true;
  91799. this._touches.add(e.pointerId.toString(), e);
  91800. }
  91801. else {
  91802. // You can only trigger the action buttons with a joystick declared
  91803. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91804. this._action();
  91805. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91806. }
  91807. }
  91808. };
  91809. VirtualJoystick.prototype._onPointerMove = function (e) {
  91810. // If the current pointer is the one associated to the joystick (first touch contact)
  91811. if (this._joystickPointerID == e.pointerId) {
  91812. this._joystickPointerPos.x = e.clientX;
  91813. this._joystickPointerPos.y = e.clientY;
  91814. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91815. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91816. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91817. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91818. switch (this._axisTargetedByLeftAndRight) {
  91819. case JoystickAxis.X:
  91820. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91821. break;
  91822. case JoystickAxis.Y:
  91823. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91824. break;
  91825. case JoystickAxis.Z:
  91826. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91827. break;
  91828. }
  91829. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91830. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91831. switch (this._axisTargetedByUpAndDown) {
  91832. case JoystickAxis.X:
  91833. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91834. break;
  91835. case JoystickAxis.Y:
  91836. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91837. break;
  91838. case JoystickAxis.Z:
  91839. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91840. break;
  91841. }
  91842. }
  91843. else {
  91844. var data = this._touches.get(e.pointerId.toString());
  91845. if (data) {
  91846. data.x = e.clientX;
  91847. data.y = e.clientY;
  91848. }
  91849. }
  91850. };
  91851. VirtualJoystick.prototype._onPointerUp = function (e) {
  91852. if (this._joystickPointerID == e.pointerId) {
  91853. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91854. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91855. this._joystickPointerID = -1;
  91856. this.pressed = false;
  91857. }
  91858. else {
  91859. var touch = this._touches.get(e.pointerId.toString());
  91860. if (touch) {
  91861. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91862. }
  91863. }
  91864. this._deltaJoystickVector.x = 0;
  91865. this._deltaJoystickVector.y = 0;
  91866. this._touches.remove(e.pointerId.toString());
  91867. };
  91868. /**
  91869. * Change the color of the virtual joystick
  91870. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91871. */
  91872. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91873. this._joystickColor = newColor;
  91874. };
  91875. /**
  91876. * Defines a callback to call when the joystick is touched
  91877. * @param action defines the callback
  91878. */
  91879. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91880. this._action = action;
  91881. };
  91882. /**
  91883. * Defines which axis you'd like to control for left & right
  91884. * @param axis defines the axis to use
  91885. */
  91886. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91887. switch (axis) {
  91888. case JoystickAxis.X:
  91889. case JoystickAxis.Y:
  91890. case JoystickAxis.Z:
  91891. this._axisTargetedByLeftAndRight = axis;
  91892. break;
  91893. default:
  91894. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91895. break;
  91896. }
  91897. };
  91898. /**
  91899. * Defines which axis you'd like to control for up & down
  91900. * @param axis defines the axis to use
  91901. */
  91902. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91903. switch (axis) {
  91904. case JoystickAxis.X:
  91905. case JoystickAxis.Y:
  91906. case JoystickAxis.Z:
  91907. this._axisTargetedByUpAndDown = axis;
  91908. break;
  91909. default:
  91910. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91911. break;
  91912. }
  91913. };
  91914. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91915. var _this = this;
  91916. if (this.pressed) {
  91917. this._touches.forEach(function (key, touch) {
  91918. if (touch.pointerId === _this._joystickPointerID) {
  91919. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91920. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91921. VirtualJoystick.vjCanvasContext.beginPath();
  91922. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91923. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91924. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91925. VirtualJoystick.vjCanvasContext.stroke();
  91926. VirtualJoystick.vjCanvasContext.closePath();
  91927. VirtualJoystick.vjCanvasContext.beginPath();
  91928. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91929. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91930. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91931. VirtualJoystick.vjCanvasContext.stroke();
  91932. VirtualJoystick.vjCanvasContext.closePath();
  91933. VirtualJoystick.vjCanvasContext.beginPath();
  91934. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91935. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91936. VirtualJoystick.vjCanvasContext.stroke();
  91937. VirtualJoystick.vjCanvasContext.closePath();
  91938. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91939. }
  91940. else {
  91941. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91942. VirtualJoystick.vjCanvasContext.beginPath();
  91943. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91944. VirtualJoystick.vjCanvasContext.beginPath();
  91945. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91946. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91947. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91948. VirtualJoystick.vjCanvasContext.stroke();
  91949. VirtualJoystick.vjCanvasContext.closePath();
  91950. touch.prevX = touch.x;
  91951. touch.prevY = touch.y;
  91952. }
  91953. ;
  91954. });
  91955. }
  91956. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91957. };
  91958. /**
  91959. * Release internal HTML canvas
  91960. */
  91961. VirtualJoystick.prototype.releaseCanvas = function () {
  91962. if (VirtualJoystick.vjCanvas) {
  91963. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91964. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91965. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91966. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91967. window.removeEventListener("resize", this._onResize);
  91968. document.body.removeChild(VirtualJoystick.vjCanvas);
  91969. VirtualJoystick.vjCanvas = null;
  91970. }
  91971. };
  91972. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91973. VirtualJoystick._globalJoystickIndex = 0;
  91974. return VirtualJoystick;
  91975. }());
  91976. BABYLON.VirtualJoystick = VirtualJoystick;
  91977. })(BABYLON || (BABYLON = {}));
  91978. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91979. var BABYLON;
  91980. (function (BABYLON) {
  91981. // We're mainly based on the logic defined into the FreeCamera code
  91982. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91983. __extends(VirtualJoysticksCamera, _super);
  91984. function VirtualJoysticksCamera(name, position, scene) {
  91985. var _this = _super.call(this, name, position, scene) || this;
  91986. _this.inputs.addVirtualJoystick();
  91987. return _this;
  91988. }
  91989. VirtualJoysticksCamera.prototype.getClassName = function () {
  91990. return "VirtualJoysticksCamera";
  91991. };
  91992. return VirtualJoysticksCamera;
  91993. }(BABYLON.FreeCamera));
  91994. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91995. })(BABYLON || (BABYLON = {}));
  91996. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91997. var BABYLON;
  91998. (function (BABYLON) {
  91999. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  92000. function FreeCameraVirtualJoystickInput() {
  92001. }
  92002. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  92003. return this._leftjoystick;
  92004. };
  92005. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  92006. return this._rightjoystick;
  92007. };
  92008. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  92009. if (this._leftjoystick) {
  92010. var camera = this.camera;
  92011. var speed = camera._computeLocalCameraSpeed() * 50;
  92012. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  92013. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  92014. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  92015. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  92016. if (!this._leftjoystick.pressed) {
  92017. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  92018. }
  92019. if (!this._rightjoystick.pressed) {
  92020. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  92021. }
  92022. }
  92023. };
  92024. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  92025. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  92026. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  92027. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  92028. this._leftjoystick.setJoystickSensibility(0.15);
  92029. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  92030. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  92031. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  92032. this._rightjoystick.reverseUpDown = true;
  92033. this._rightjoystick.setJoystickSensibility(0.05);
  92034. this._rightjoystick.setJoystickColor("yellow");
  92035. };
  92036. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  92037. this._leftjoystick.releaseCanvas();
  92038. this._rightjoystick.releaseCanvas();
  92039. };
  92040. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  92041. return "FreeCameraVirtualJoystickInput";
  92042. };
  92043. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  92044. return "virtualJoystick";
  92045. };
  92046. return FreeCameraVirtualJoystickInput;
  92047. }());
  92048. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  92049. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  92050. })(BABYLON || (BABYLON = {}));
  92051. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  92052. var BABYLON;
  92053. (function (BABYLON) {
  92054. var SimplificationSettings = /** @class */ (function () {
  92055. function SimplificationSettings(quality, distance, optimizeMesh) {
  92056. this.quality = quality;
  92057. this.distance = distance;
  92058. this.optimizeMesh = optimizeMesh;
  92059. }
  92060. return SimplificationSettings;
  92061. }());
  92062. BABYLON.SimplificationSettings = SimplificationSettings;
  92063. var SimplificationQueue = /** @class */ (function () {
  92064. function SimplificationQueue() {
  92065. this.running = false;
  92066. this._simplificationArray = [];
  92067. }
  92068. SimplificationQueue.prototype.addTask = function (task) {
  92069. this._simplificationArray.push(task);
  92070. };
  92071. SimplificationQueue.prototype.executeNext = function () {
  92072. var task = this._simplificationArray.pop();
  92073. if (task) {
  92074. this.running = true;
  92075. this.runSimplification(task);
  92076. }
  92077. else {
  92078. this.running = false;
  92079. }
  92080. };
  92081. SimplificationQueue.prototype.runSimplification = function (task) {
  92082. var _this = this;
  92083. if (task.parallelProcessing) {
  92084. //parallel simplifier
  92085. task.settings.forEach(function (setting) {
  92086. var simplifier = _this.getSimplifier(task);
  92087. simplifier.simplify(setting, function (newMesh) {
  92088. task.mesh.addLODLevel(setting.distance, newMesh);
  92089. newMesh.isVisible = true;
  92090. //check if it is the last
  92091. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  92092. //all done, run the success callback.
  92093. task.successCallback();
  92094. }
  92095. _this.executeNext();
  92096. });
  92097. });
  92098. }
  92099. else {
  92100. //single simplifier.
  92101. var simplifier = this.getSimplifier(task);
  92102. var runDecimation = function (setting, callback) {
  92103. simplifier.simplify(setting, function (newMesh) {
  92104. task.mesh.addLODLevel(setting.distance, newMesh);
  92105. newMesh.isVisible = true;
  92106. //run the next quality level
  92107. callback();
  92108. });
  92109. };
  92110. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  92111. runDecimation(task.settings[loop.index], function () {
  92112. loop.executeNext();
  92113. });
  92114. }, function () {
  92115. //execution ended, run the success callback.
  92116. if (task.successCallback) {
  92117. task.successCallback();
  92118. }
  92119. _this.executeNext();
  92120. });
  92121. }
  92122. };
  92123. SimplificationQueue.prototype.getSimplifier = function (task) {
  92124. switch (task.simplificationType) {
  92125. case SimplificationType.QUADRATIC:
  92126. default:
  92127. return new QuadraticErrorSimplification(task.mesh);
  92128. }
  92129. };
  92130. return SimplificationQueue;
  92131. }());
  92132. BABYLON.SimplificationQueue = SimplificationQueue;
  92133. /**
  92134. * The implemented types of simplification
  92135. * At the moment only Quadratic Error Decimation is implemented
  92136. */
  92137. var SimplificationType;
  92138. (function (SimplificationType) {
  92139. /** Quadratic error decimation */
  92140. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  92141. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  92142. var DecimationTriangle = /** @class */ (function () {
  92143. function DecimationTriangle(vertices) {
  92144. this.vertices = vertices;
  92145. this.error = new Array(4);
  92146. this.deleted = false;
  92147. this.isDirty = false;
  92148. this.deletePending = false;
  92149. this.borderFactor = 0;
  92150. }
  92151. return DecimationTriangle;
  92152. }());
  92153. BABYLON.DecimationTriangle = DecimationTriangle;
  92154. var DecimationVertex = /** @class */ (function () {
  92155. function DecimationVertex(position, id) {
  92156. this.position = position;
  92157. this.id = id;
  92158. this.isBorder = true;
  92159. this.q = new QuadraticMatrix();
  92160. this.triangleCount = 0;
  92161. this.triangleStart = 0;
  92162. this.originalOffsets = [];
  92163. }
  92164. DecimationVertex.prototype.updatePosition = function (newPosition) {
  92165. this.position.copyFrom(newPosition);
  92166. };
  92167. return DecimationVertex;
  92168. }());
  92169. BABYLON.DecimationVertex = DecimationVertex;
  92170. var QuadraticMatrix = /** @class */ (function () {
  92171. function QuadraticMatrix(data) {
  92172. this.data = new Array(10);
  92173. for (var i = 0; i < 10; ++i) {
  92174. if (data && data[i]) {
  92175. this.data[i] = data[i];
  92176. }
  92177. else {
  92178. this.data[i] = 0;
  92179. }
  92180. }
  92181. }
  92182. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  92183. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  92184. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  92185. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  92186. return det;
  92187. };
  92188. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  92189. for (var i = 0; i < 10; ++i) {
  92190. this.data[i] += matrix.data[i];
  92191. }
  92192. };
  92193. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  92194. for (var i = 0; i < 10; ++i) {
  92195. this.data[i] += data[i];
  92196. }
  92197. };
  92198. QuadraticMatrix.prototype.add = function (matrix) {
  92199. var m = new QuadraticMatrix();
  92200. for (var i = 0; i < 10; ++i) {
  92201. m.data[i] = this.data[i] + matrix.data[i];
  92202. }
  92203. return m;
  92204. };
  92205. QuadraticMatrix.FromData = function (a, b, c, d) {
  92206. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  92207. };
  92208. //returning an array to avoid garbage collection
  92209. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  92210. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  92211. };
  92212. return QuadraticMatrix;
  92213. }());
  92214. BABYLON.QuadraticMatrix = QuadraticMatrix;
  92215. var Reference = /** @class */ (function () {
  92216. function Reference(vertexId, triangleId) {
  92217. this.vertexId = vertexId;
  92218. this.triangleId = triangleId;
  92219. }
  92220. return Reference;
  92221. }());
  92222. BABYLON.Reference = Reference;
  92223. /**
  92224. * An implementation of the Quadratic Error simplification algorithm.
  92225. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  92226. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  92227. * @author RaananW
  92228. */
  92229. var QuadraticErrorSimplification = /** @class */ (function () {
  92230. function QuadraticErrorSimplification(_mesh) {
  92231. this._mesh = _mesh;
  92232. this.syncIterations = 5000;
  92233. this.aggressiveness = 7;
  92234. this.decimationIterations = 100;
  92235. this.boundingBoxEpsilon = BABYLON.Epsilon;
  92236. }
  92237. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  92238. var _this = this;
  92239. this.initDecimatedMesh();
  92240. //iterating through the submeshes array, one after the other.
  92241. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  92242. _this.initWithMesh(loop.index, function () {
  92243. _this.runDecimation(settings, loop.index, function () {
  92244. loop.executeNext();
  92245. });
  92246. }, settings.optimizeMesh);
  92247. }, function () {
  92248. setTimeout(function () {
  92249. successCallback(_this._reconstructedMesh);
  92250. }, 0);
  92251. });
  92252. };
  92253. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  92254. var _this = this;
  92255. var targetCount = ~~(this.triangles.length * settings.quality);
  92256. var deletedTriangles = 0;
  92257. var triangleCount = this.triangles.length;
  92258. var iterationFunction = function (iteration, callback) {
  92259. setTimeout(function () {
  92260. if (iteration % 5 === 0) {
  92261. _this.updateMesh(iteration === 0);
  92262. }
  92263. for (var i = 0; i < _this.triangles.length; ++i) {
  92264. _this.triangles[i].isDirty = false;
  92265. }
  92266. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  92267. var trianglesIterator = function (i) {
  92268. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  92269. var t = _this.triangles[tIdx];
  92270. if (!t)
  92271. return;
  92272. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  92273. return;
  92274. }
  92275. for (var j = 0; j < 3; ++j) {
  92276. if (t.error[j] < threshold) {
  92277. var deleted0 = [];
  92278. var deleted1 = [];
  92279. var v0 = t.vertices[j];
  92280. var v1 = t.vertices[(j + 1) % 3];
  92281. if (v0.isBorder || v1.isBorder)
  92282. continue;
  92283. var p = BABYLON.Vector3.Zero();
  92284. var n = BABYLON.Vector3.Zero();
  92285. var uv = BABYLON.Vector2.Zero();
  92286. var color = new BABYLON.Color4(0, 0, 0, 1);
  92287. _this.calculateError(v0, v1, p, n, uv, color);
  92288. var delTr = new Array();
  92289. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  92290. continue;
  92291. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  92292. continue;
  92293. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  92294. continue;
  92295. var uniqueArray = new Array();
  92296. delTr.forEach(function (deletedT) {
  92297. if (uniqueArray.indexOf(deletedT) === -1) {
  92298. deletedT.deletePending = true;
  92299. uniqueArray.push(deletedT);
  92300. }
  92301. });
  92302. if (uniqueArray.length % 2 !== 0) {
  92303. continue;
  92304. }
  92305. v0.q = v1.q.add(v0.q);
  92306. v0.updatePosition(p);
  92307. var tStart = _this.references.length;
  92308. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  92309. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  92310. var tCount = _this.references.length - tStart;
  92311. if (tCount <= v0.triangleCount) {
  92312. if (tCount) {
  92313. for (var c = 0; c < tCount; c++) {
  92314. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  92315. }
  92316. }
  92317. }
  92318. else {
  92319. v0.triangleStart = tStart;
  92320. }
  92321. v0.triangleCount = tCount;
  92322. break;
  92323. }
  92324. }
  92325. };
  92326. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  92327. }, 0);
  92328. };
  92329. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  92330. if (triangleCount - deletedTriangles <= targetCount)
  92331. loop.breakLoop();
  92332. else {
  92333. iterationFunction(loop.index, function () {
  92334. loop.executeNext();
  92335. });
  92336. }
  92337. }, function () {
  92338. setTimeout(function () {
  92339. //reconstruct this part of the mesh
  92340. _this.reconstructMesh(submeshIndex);
  92341. successCallback();
  92342. }, 0);
  92343. });
  92344. };
  92345. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  92346. var _this = this;
  92347. this.vertices = [];
  92348. this.triangles = [];
  92349. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  92350. var indices = this._mesh.getIndices();
  92351. var submesh = this._mesh.subMeshes[submeshIndex];
  92352. var findInVertices = function (positionToSearch) {
  92353. if (optimizeMesh) {
  92354. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  92355. if (_this.vertices[ii].position.equals(positionToSearch)) {
  92356. return _this.vertices[ii];
  92357. }
  92358. }
  92359. }
  92360. return null;
  92361. };
  92362. var vertexReferences = [];
  92363. var vertexInit = function (i) {
  92364. if (!positionData) {
  92365. return;
  92366. }
  92367. var offset = i + submesh.verticesStart;
  92368. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  92369. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  92370. vertex.originalOffsets.push(offset);
  92371. if (vertex.id === _this.vertices.length) {
  92372. _this.vertices.push(vertex);
  92373. }
  92374. vertexReferences.push(vertex.id);
  92375. };
  92376. //var totalVertices = mesh.getTotalVertices();
  92377. var totalVertices = submesh.verticesCount;
  92378. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  92379. var indicesInit = function (i) {
  92380. if (!indices) {
  92381. return;
  92382. }
  92383. var offset = (submesh.indexStart / 3) + i;
  92384. var pos = (offset * 3);
  92385. var i0 = indices[pos + 0];
  92386. var i1 = indices[pos + 1];
  92387. var i2 = indices[pos + 2];
  92388. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  92389. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  92390. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  92391. var triangle = new DecimationTriangle([v0, v1, v2]);
  92392. triangle.originalOffset = pos;
  92393. _this.triangles.push(triangle);
  92394. };
  92395. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  92396. _this.init(callback);
  92397. });
  92398. });
  92399. };
  92400. QuadraticErrorSimplification.prototype.init = function (callback) {
  92401. var _this = this;
  92402. var triangleInit1 = function (i) {
  92403. var t = _this.triangles[i];
  92404. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  92405. for (var j = 0; j < 3; j++) {
  92406. 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))));
  92407. }
  92408. };
  92409. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  92410. var triangleInit2 = function (i) {
  92411. var t = _this.triangles[i];
  92412. for (var j = 0; j < 3; ++j) {
  92413. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  92414. }
  92415. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92416. };
  92417. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  92418. callback();
  92419. });
  92420. });
  92421. };
  92422. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  92423. var newTriangles = [];
  92424. var i;
  92425. for (i = 0; i < this.vertices.length; ++i) {
  92426. this.vertices[i].triangleCount = 0;
  92427. }
  92428. var t;
  92429. var j;
  92430. for (i = 0; i < this.triangles.length; ++i) {
  92431. if (!this.triangles[i].deleted) {
  92432. t = this.triangles[i];
  92433. for (j = 0; j < 3; ++j) {
  92434. t.vertices[j].triangleCount = 1;
  92435. }
  92436. newTriangles.push(t);
  92437. }
  92438. }
  92439. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  92440. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  92441. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  92442. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  92443. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  92444. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92445. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  92446. var vertexCount = 0;
  92447. for (i = 0; i < this.vertices.length; ++i) {
  92448. var vertex = this.vertices[i];
  92449. vertex.id = vertexCount;
  92450. if (vertex.triangleCount) {
  92451. vertex.originalOffsets.forEach(function (originalOffset) {
  92452. if (!normalData) {
  92453. return;
  92454. }
  92455. newPositionData.push(vertex.position.x);
  92456. newPositionData.push(vertex.position.y);
  92457. newPositionData.push(vertex.position.z);
  92458. newNormalData.push(normalData[originalOffset * 3]);
  92459. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  92460. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  92461. if (uvs && uvs.length) {
  92462. newUVsData.push(uvs[(originalOffset * 2)]);
  92463. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  92464. }
  92465. else if (colorsData && colorsData.length) {
  92466. newColorsData.push(colorsData[(originalOffset * 4)]);
  92467. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92468. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92469. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92470. }
  92471. ++vertexCount;
  92472. });
  92473. }
  92474. }
  92475. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92476. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92477. var submeshesArray = this._reconstructedMesh.subMeshes;
  92478. this._reconstructedMesh.subMeshes = [];
  92479. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92480. var originalIndices = this._mesh.getIndices();
  92481. for (i = 0; i < newTriangles.length; ++i) {
  92482. t = newTriangles[i]; //now get the new referencing point for each vertex
  92483. [0, 1, 2].forEach(function (idx) {
  92484. var id = originalIndices[t.originalOffset + idx];
  92485. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92486. if (offset < 0)
  92487. offset = 0;
  92488. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92489. });
  92490. }
  92491. //overwriting the old vertex buffers and indices.
  92492. this._reconstructedMesh.setIndices(newIndicesArray);
  92493. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92494. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92495. if (newUVsData.length > 0)
  92496. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92497. if (newColorsData.length > 0)
  92498. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92499. //create submesh
  92500. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92501. if (submeshIndex > 0) {
  92502. this._reconstructedMesh.subMeshes = [];
  92503. submeshesArray.forEach(function (submesh) {
  92504. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92505. });
  92506. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92507. }
  92508. };
  92509. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92510. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92511. this._reconstructedMesh.material = this._mesh.material;
  92512. this._reconstructedMesh.parent = this._mesh.parent;
  92513. this._reconstructedMesh.isVisible = false;
  92514. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92515. };
  92516. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92517. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92518. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92519. if (t.deleted)
  92520. continue;
  92521. var s = this.references[vertex1.triangleStart + i].vertexId;
  92522. var v1 = t.vertices[(s + 1) % 3];
  92523. var v2 = t.vertices[(s + 2) % 3];
  92524. if ((v1 === vertex2 || v2 === vertex2)) {
  92525. deletedArray[i] = true;
  92526. delTr.push(t);
  92527. continue;
  92528. }
  92529. var d1 = v1.position.subtract(point);
  92530. d1 = d1.normalize();
  92531. var d2 = v2.position.subtract(point);
  92532. d2 = d2.normalize();
  92533. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92534. return true;
  92535. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92536. deletedArray[i] = false;
  92537. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92538. return true;
  92539. }
  92540. return false;
  92541. };
  92542. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92543. var newDeleted = deletedTriangles;
  92544. for (var i = 0; i < vertex.triangleCount; ++i) {
  92545. var ref = this.references[vertex.triangleStart + i];
  92546. var t = this.triangles[ref.triangleId];
  92547. if (t.deleted)
  92548. continue;
  92549. if (deletedArray[i] && t.deletePending) {
  92550. t.deleted = true;
  92551. newDeleted++;
  92552. continue;
  92553. }
  92554. t.vertices[ref.vertexId] = origVertex;
  92555. t.isDirty = true;
  92556. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92557. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92558. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92559. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92560. this.references.push(ref);
  92561. }
  92562. return newDeleted;
  92563. };
  92564. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92565. for (var i = 0; i < this.vertices.length; ++i) {
  92566. var vCount = [];
  92567. var vId = [];
  92568. var v = this.vertices[i];
  92569. var j;
  92570. for (j = 0; j < v.triangleCount; ++j) {
  92571. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92572. for (var ii = 0; ii < 3; ii++) {
  92573. var ofs = 0;
  92574. var vv = triangle.vertices[ii];
  92575. while (ofs < vCount.length) {
  92576. if (vId[ofs] === vv.id)
  92577. break;
  92578. ++ofs;
  92579. }
  92580. if (ofs === vCount.length) {
  92581. vCount.push(1);
  92582. vId.push(vv.id);
  92583. }
  92584. else {
  92585. vCount[ofs]++;
  92586. }
  92587. }
  92588. }
  92589. for (j = 0; j < vCount.length; ++j) {
  92590. if (vCount[j] === 1) {
  92591. this.vertices[vId[j]].isBorder = true;
  92592. }
  92593. else {
  92594. this.vertices[vId[j]].isBorder = false;
  92595. }
  92596. }
  92597. }
  92598. };
  92599. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92600. if (identifyBorders === void 0) { identifyBorders = false; }
  92601. var i;
  92602. if (!identifyBorders) {
  92603. var newTrianglesVector = [];
  92604. for (i = 0; i < this.triangles.length; ++i) {
  92605. if (!this.triangles[i].deleted) {
  92606. newTrianglesVector.push(this.triangles[i]);
  92607. }
  92608. }
  92609. this.triangles = newTrianglesVector;
  92610. }
  92611. for (i = 0; i < this.vertices.length; ++i) {
  92612. this.vertices[i].triangleCount = 0;
  92613. this.vertices[i].triangleStart = 0;
  92614. }
  92615. var t;
  92616. var j;
  92617. var v;
  92618. for (i = 0; i < this.triangles.length; ++i) {
  92619. t = this.triangles[i];
  92620. for (j = 0; j < 3; ++j) {
  92621. v = t.vertices[j];
  92622. v.triangleCount++;
  92623. }
  92624. }
  92625. var tStart = 0;
  92626. for (i = 0; i < this.vertices.length; ++i) {
  92627. this.vertices[i].triangleStart = tStart;
  92628. tStart += this.vertices[i].triangleCount;
  92629. this.vertices[i].triangleCount = 0;
  92630. }
  92631. var newReferences = new Array(this.triangles.length * 3);
  92632. for (i = 0; i < this.triangles.length; ++i) {
  92633. t = this.triangles[i];
  92634. for (j = 0; j < 3; ++j) {
  92635. v = t.vertices[j];
  92636. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92637. v.triangleCount++;
  92638. }
  92639. }
  92640. this.references = newReferences;
  92641. if (identifyBorders) {
  92642. this.identifyBorder();
  92643. }
  92644. };
  92645. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92646. var x = point.x;
  92647. var y = point.y;
  92648. var z = point.z;
  92649. 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
  92650. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92651. };
  92652. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92653. var q = vertex1.q.add(vertex2.q);
  92654. var border = vertex1.isBorder && vertex2.isBorder;
  92655. var error = 0;
  92656. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92657. if (qDet !== 0 && !border) {
  92658. if (!pointResult) {
  92659. pointResult = BABYLON.Vector3.Zero();
  92660. }
  92661. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92662. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92663. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92664. error = this.vertexError(q, pointResult);
  92665. }
  92666. else {
  92667. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92668. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92669. var error1 = this.vertexError(q, vertex1.position);
  92670. var error2 = this.vertexError(q, vertex2.position);
  92671. var error3 = this.vertexError(q, p3);
  92672. error = Math.min(error1, error2, error3);
  92673. if (error === error1) {
  92674. if (pointResult) {
  92675. pointResult.copyFrom(vertex1.position);
  92676. }
  92677. }
  92678. else if (error === error2) {
  92679. if (pointResult) {
  92680. pointResult.copyFrom(vertex2.position);
  92681. }
  92682. }
  92683. else {
  92684. if (pointResult) {
  92685. pointResult.copyFrom(p3);
  92686. }
  92687. }
  92688. }
  92689. return error;
  92690. };
  92691. return QuadraticErrorSimplification;
  92692. }());
  92693. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92694. })(BABYLON || (BABYLON = {}));
  92695. //# sourceMappingURL=babylon.meshSimplification.js.map
  92696. var BABYLON;
  92697. (function (BABYLON) {
  92698. var MeshLODLevel = /** @class */ (function () {
  92699. function MeshLODLevel(distance, mesh) {
  92700. this.distance = distance;
  92701. this.mesh = mesh;
  92702. }
  92703. return MeshLODLevel;
  92704. }());
  92705. BABYLON.MeshLODLevel = MeshLODLevel;
  92706. })(BABYLON || (BABYLON = {}));
  92707. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92708. var BABYLON;
  92709. (function (BABYLON) {
  92710. /**
  92711. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92712. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92713. */
  92714. var SceneOptimization = /** @class */ (function () {
  92715. /**
  92716. * Creates the SceneOptimization object
  92717. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92718. * @param desc defines the description associated with the optimization
  92719. */
  92720. function SceneOptimization(
  92721. /**
  92722. * Defines the priority of this optimization (0 by default which means first in the list)
  92723. */
  92724. priority) {
  92725. if (priority === void 0) { priority = 0; }
  92726. this.priority = priority;
  92727. }
  92728. /**
  92729. * Gets a string describing the action executed by the current optimization
  92730. * @returns description string
  92731. */
  92732. SceneOptimization.prototype.getDescription = function () {
  92733. return "";
  92734. };
  92735. /**
  92736. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92737. * @param scene defines the current scene where to apply this optimization
  92738. * @param optimizer defines the current optimizer
  92739. * @returns true if everything that can be done was applied
  92740. */
  92741. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92742. return true;
  92743. };
  92744. ;
  92745. return SceneOptimization;
  92746. }());
  92747. BABYLON.SceneOptimization = SceneOptimization;
  92748. /**
  92749. * Defines an optimization used to reduce the size of render target textures
  92750. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92751. */
  92752. var TextureOptimization = /** @class */ (function (_super) {
  92753. __extends(TextureOptimization, _super);
  92754. /**
  92755. * Creates the TextureOptimization object
  92756. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92757. * @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
  92758. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92759. */
  92760. function TextureOptimization(
  92761. /**
  92762. * Defines the priority of this optimization (0 by default which means first in the list)
  92763. */
  92764. priority,
  92765. /**
  92766. * 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
  92767. */
  92768. maximumSize,
  92769. /**
  92770. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92771. */
  92772. step) {
  92773. if (priority === void 0) { priority = 0; }
  92774. if (maximumSize === void 0) { maximumSize = 1024; }
  92775. if (step === void 0) { step = 0.5; }
  92776. var _this = _super.call(this, priority) || this;
  92777. _this.priority = priority;
  92778. _this.maximumSize = maximumSize;
  92779. _this.step = step;
  92780. return _this;
  92781. }
  92782. /**
  92783. * Gets a string describing the action executed by the current optimization
  92784. * @returns description string
  92785. */
  92786. TextureOptimization.prototype.getDescription = function () {
  92787. return "Reducing render target texture size to " + this.maximumSize;
  92788. };
  92789. /**
  92790. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92791. * @param scene defines the current scene where to apply this optimization
  92792. * @param optimizer defines the current optimizer
  92793. * @returns true if everything that can be done was applied
  92794. */
  92795. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92796. var allDone = true;
  92797. for (var index = 0; index < scene.textures.length; index++) {
  92798. var texture = scene.textures[index];
  92799. if (!texture.canRescale || texture.getContext) {
  92800. continue;
  92801. }
  92802. var currentSize = texture.getSize();
  92803. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92804. if (maxDimension > this.maximumSize) {
  92805. texture.scale(this.step);
  92806. allDone = false;
  92807. }
  92808. }
  92809. return allDone;
  92810. };
  92811. return TextureOptimization;
  92812. }(SceneOptimization));
  92813. BABYLON.TextureOptimization = TextureOptimization;
  92814. /**
  92815. * Defines an optimization used to increase or decrease the rendering resolution
  92816. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92817. */
  92818. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92819. __extends(HardwareScalingOptimization, _super);
  92820. /**
  92821. * Creates the HardwareScalingOptimization object
  92822. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92823. * @param maximumScale defines the maximum scale to use (2 by default)
  92824. * @param step defines the step to use between two passes (0.5 by default)
  92825. */
  92826. function HardwareScalingOptimization(
  92827. /**
  92828. * Defines the priority of this optimization (0 by default which means first in the list)
  92829. */
  92830. priority,
  92831. /**
  92832. * Defines the maximum scale to use (2 by default)
  92833. */
  92834. maximumScale,
  92835. /**
  92836. * Defines the step to use between two passes (0.5 by default)
  92837. */
  92838. step) {
  92839. if (priority === void 0) { priority = 0; }
  92840. if (maximumScale === void 0) { maximumScale = 2; }
  92841. if (step === void 0) { step = 0.25; }
  92842. var _this = _super.call(this, priority) || this;
  92843. _this.priority = priority;
  92844. _this.maximumScale = maximumScale;
  92845. _this.step = step;
  92846. _this._currentScale = -1;
  92847. _this._directionOffset = 1;
  92848. return _this;
  92849. }
  92850. /**
  92851. * Gets a string describing the action executed by the current optimization
  92852. * @return description string
  92853. */
  92854. HardwareScalingOptimization.prototype.getDescription = function () {
  92855. return "Setting hardware scaling level to " + this._currentScale;
  92856. };
  92857. /**
  92858. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92859. * @param scene defines the current scene where to apply this optimization
  92860. * @param optimizer defines the current optimizer
  92861. * @returns true if everything that can be done was applied
  92862. */
  92863. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92864. if (this._currentScale === -1) {
  92865. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92866. if (this._currentScale > this.maximumScale) {
  92867. this._directionOffset = -1;
  92868. }
  92869. }
  92870. this._currentScale += this._directionOffset * this.step;
  92871. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92872. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92873. };
  92874. ;
  92875. return HardwareScalingOptimization;
  92876. }(SceneOptimization));
  92877. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92878. /**
  92879. * Defines an optimization used to remove shadows
  92880. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92881. */
  92882. var ShadowsOptimization = /** @class */ (function (_super) {
  92883. __extends(ShadowsOptimization, _super);
  92884. function ShadowsOptimization() {
  92885. return _super !== null && _super.apply(this, arguments) || this;
  92886. }
  92887. /**
  92888. * Gets a string describing the action executed by the current optimization
  92889. * @return description string
  92890. */
  92891. ShadowsOptimization.prototype.getDescription = function () {
  92892. return "Turning shadows on/off";
  92893. };
  92894. /**
  92895. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92896. * @param scene defines the current scene where to apply this optimization
  92897. * @param optimizer defines the current optimizer
  92898. * @returns true if everything that can be done was applied
  92899. */
  92900. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92901. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92902. return true;
  92903. };
  92904. ;
  92905. return ShadowsOptimization;
  92906. }(SceneOptimization));
  92907. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92908. /**
  92909. * Defines an optimization used to turn post-processes off
  92910. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92911. */
  92912. var PostProcessesOptimization = /** @class */ (function (_super) {
  92913. __extends(PostProcessesOptimization, _super);
  92914. function PostProcessesOptimization() {
  92915. return _super !== null && _super.apply(this, arguments) || this;
  92916. }
  92917. /**
  92918. * Gets a string describing the action executed by the current optimization
  92919. * @return description string
  92920. */
  92921. PostProcessesOptimization.prototype.getDescription = function () {
  92922. return "Turning post-processes on/off";
  92923. };
  92924. /**
  92925. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92926. * @param scene defines the current scene where to apply this optimization
  92927. * @param optimizer defines the current optimizer
  92928. * @returns true if everything that can be done was applied
  92929. */
  92930. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92931. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92932. return true;
  92933. };
  92934. ;
  92935. return PostProcessesOptimization;
  92936. }(SceneOptimization));
  92937. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92938. /**
  92939. * Defines an optimization used to turn lens flares off
  92940. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92941. */
  92942. var LensFlaresOptimization = /** @class */ (function (_super) {
  92943. __extends(LensFlaresOptimization, _super);
  92944. function LensFlaresOptimization() {
  92945. return _super !== null && _super.apply(this, arguments) || this;
  92946. }
  92947. /**
  92948. * Gets a string describing the action executed by the current optimization
  92949. * @return description string
  92950. */
  92951. LensFlaresOptimization.prototype.getDescription = function () {
  92952. return "Turning lens flares on/off";
  92953. };
  92954. /**
  92955. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92956. * @param scene defines the current scene where to apply this optimization
  92957. * @param optimizer defines the current optimizer
  92958. * @returns true if everything that can be done was applied
  92959. */
  92960. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92961. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92962. return true;
  92963. };
  92964. ;
  92965. return LensFlaresOptimization;
  92966. }(SceneOptimization));
  92967. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92968. /**
  92969. * Defines an optimization based on user defined callback.
  92970. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92971. */
  92972. var CustomOptimization = /** @class */ (function (_super) {
  92973. __extends(CustomOptimization, _super);
  92974. function CustomOptimization() {
  92975. return _super !== null && _super.apply(this, arguments) || this;
  92976. }
  92977. /**
  92978. * Gets a string describing the action executed by the current optimization
  92979. * @returns description string
  92980. */
  92981. CustomOptimization.prototype.getDescription = function () {
  92982. if (this.onGetDescription) {
  92983. return this.onGetDescription();
  92984. }
  92985. return "Running user defined callback";
  92986. };
  92987. /**
  92988. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92989. * @param scene defines the current scene where to apply this optimization
  92990. * @param optimizer defines the current optimizer
  92991. * @returns true if everything that can be done was applied
  92992. */
  92993. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92994. if (this.onApply) {
  92995. return this.onApply(scene, optimizer);
  92996. }
  92997. return true;
  92998. };
  92999. ;
  93000. return CustomOptimization;
  93001. }(SceneOptimization));
  93002. BABYLON.CustomOptimization = CustomOptimization;
  93003. /**
  93004. * Defines an optimization used to turn particles off
  93005. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93006. */
  93007. var ParticlesOptimization = /** @class */ (function (_super) {
  93008. __extends(ParticlesOptimization, _super);
  93009. function ParticlesOptimization() {
  93010. return _super !== null && _super.apply(this, arguments) || this;
  93011. }
  93012. /**
  93013. * Gets a string describing the action executed by the current optimization
  93014. * @return description string
  93015. */
  93016. ParticlesOptimization.prototype.getDescription = function () {
  93017. return "Turning particles on/off";
  93018. };
  93019. /**
  93020. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93021. * @param scene defines the current scene where to apply this optimization
  93022. * @param optimizer defines the current optimizer
  93023. * @returns true if everything that can be done was applied
  93024. */
  93025. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  93026. scene.particlesEnabled = optimizer.isInImprovementMode;
  93027. return true;
  93028. };
  93029. ;
  93030. return ParticlesOptimization;
  93031. }(SceneOptimization));
  93032. BABYLON.ParticlesOptimization = ParticlesOptimization;
  93033. /**
  93034. * Defines an optimization used to turn render targets off
  93035. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93036. */
  93037. var RenderTargetsOptimization = /** @class */ (function (_super) {
  93038. __extends(RenderTargetsOptimization, _super);
  93039. function RenderTargetsOptimization() {
  93040. return _super !== null && _super.apply(this, arguments) || this;
  93041. }
  93042. /**
  93043. * Gets a string describing the action executed by the current optimization
  93044. * @return description string
  93045. */
  93046. RenderTargetsOptimization.prototype.getDescription = function () {
  93047. return "Turning render targets off";
  93048. };
  93049. /**
  93050. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93051. * @param scene defines the current scene where to apply this optimization
  93052. * @param optimizer defines the current optimizer
  93053. * @returns true if everything that can be done was applied
  93054. */
  93055. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  93056. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  93057. return true;
  93058. };
  93059. ;
  93060. return RenderTargetsOptimization;
  93061. }(SceneOptimization));
  93062. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  93063. /**
  93064. * Defines an optimization used to merge meshes with compatible materials
  93065. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93066. */
  93067. var MergeMeshesOptimization = /** @class */ (function (_super) {
  93068. __extends(MergeMeshesOptimization, _super);
  93069. function MergeMeshesOptimization() {
  93070. var _this = _super !== null && _super.apply(this, arguments) || this;
  93071. _this._canBeMerged = function (abstractMesh) {
  93072. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  93073. return false;
  93074. }
  93075. var mesh = abstractMesh;
  93076. if (!mesh.isVisible || !mesh.isEnabled()) {
  93077. return false;
  93078. }
  93079. if (mesh.instances.length > 0) {
  93080. return false;
  93081. }
  93082. if (mesh.skeleton || mesh.hasLODLevels) {
  93083. return false;
  93084. }
  93085. if (mesh.parent) {
  93086. return false;
  93087. }
  93088. return true;
  93089. };
  93090. return _this;
  93091. }
  93092. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  93093. /**
  93094. * Gets or sets a boolean which defines if optimization octree has to be updated
  93095. */
  93096. get: function () {
  93097. return MergeMeshesOptimization._UpdateSelectionTree;
  93098. },
  93099. /**
  93100. * Gets or sets a boolean which defines if optimization octree has to be updated
  93101. */
  93102. set: function (value) {
  93103. MergeMeshesOptimization._UpdateSelectionTree = value;
  93104. },
  93105. enumerable: true,
  93106. configurable: true
  93107. });
  93108. /**
  93109. * Gets a string describing the action executed by the current optimization
  93110. * @return description string
  93111. */
  93112. MergeMeshesOptimization.prototype.getDescription = function () {
  93113. return "Merging similar meshes together";
  93114. };
  93115. /**
  93116. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93117. * @param scene defines the current scene where to apply this optimization
  93118. * @param optimizer defines the current optimizer
  93119. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  93120. * @returns true if everything that can be done was applied
  93121. */
  93122. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  93123. var globalPool = scene.meshes.slice(0);
  93124. var globalLength = globalPool.length;
  93125. for (var index = 0; index < globalLength; index++) {
  93126. var currentPool = new Array();
  93127. var current = globalPool[index];
  93128. // Checks
  93129. if (!this._canBeMerged(current)) {
  93130. continue;
  93131. }
  93132. currentPool.push(current);
  93133. // Find compatible meshes
  93134. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  93135. var otherMesh = globalPool[subIndex];
  93136. if (!this._canBeMerged(otherMesh)) {
  93137. continue;
  93138. }
  93139. if (otherMesh.material !== current.material) {
  93140. continue;
  93141. }
  93142. if (otherMesh.checkCollisions !== current.checkCollisions) {
  93143. continue;
  93144. }
  93145. currentPool.push(otherMesh);
  93146. globalLength--;
  93147. globalPool.splice(subIndex, 1);
  93148. subIndex--;
  93149. }
  93150. if (currentPool.length < 2) {
  93151. continue;
  93152. }
  93153. // Merge meshes
  93154. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  93155. }
  93156. if (updateSelectionTree != undefined) {
  93157. if (updateSelectionTree) {
  93158. scene.createOrUpdateSelectionOctree();
  93159. }
  93160. }
  93161. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  93162. scene.createOrUpdateSelectionOctree();
  93163. }
  93164. return true;
  93165. };
  93166. ;
  93167. MergeMeshesOptimization._UpdateSelectionTree = false;
  93168. return MergeMeshesOptimization;
  93169. }(SceneOptimization));
  93170. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  93171. /**
  93172. * Defines a list of options used by SceneOptimizer
  93173. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93174. */
  93175. var SceneOptimizerOptions = /** @class */ (function () {
  93176. /**
  93177. * Creates a new list of options used by SceneOptimizer
  93178. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  93179. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  93180. */
  93181. function SceneOptimizerOptions(
  93182. /**
  93183. * Defines the target frame rate to reach (60 by default)
  93184. */
  93185. targetFrameRate,
  93186. /**
  93187. * Defines the interval between two checkes (2000ms by default)
  93188. */
  93189. trackerDuration) {
  93190. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  93191. if (trackerDuration === void 0) { trackerDuration = 2000; }
  93192. this.targetFrameRate = targetFrameRate;
  93193. this.trackerDuration = trackerDuration;
  93194. /**
  93195. * Gets the list of optimizations to apply
  93196. */
  93197. this.optimizations = new Array();
  93198. }
  93199. /**
  93200. * Add a new optimization
  93201. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  93202. * @returns the current SceneOptimizerOptions
  93203. */
  93204. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  93205. this.optimizations.push(optimization);
  93206. return this;
  93207. };
  93208. /**
  93209. * Add a new custom optimization
  93210. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  93211. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  93212. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93213. * @returns the current SceneOptimizerOptions
  93214. */
  93215. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  93216. if (priority === void 0) { priority = 0; }
  93217. var optimization = new CustomOptimization(priority);
  93218. optimization.onApply = onApply;
  93219. optimization.onGetDescription = onGetDescription;
  93220. this.optimizations.push(optimization);
  93221. return this;
  93222. };
  93223. /**
  93224. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  93225. * @param targetFrameRate defines the target frame rate (60 by default)
  93226. * @returns a SceneOptimizerOptions object
  93227. */
  93228. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  93229. var result = new SceneOptimizerOptions(targetFrameRate);
  93230. var priority = 0;
  93231. result.addOptimization(new MergeMeshesOptimization(priority));
  93232. result.addOptimization(new ShadowsOptimization(priority));
  93233. result.addOptimization(new LensFlaresOptimization(priority));
  93234. // Next priority
  93235. priority++;
  93236. result.addOptimization(new PostProcessesOptimization(priority));
  93237. result.addOptimization(new ParticlesOptimization(priority));
  93238. // Next priority
  93239. priority++;
  93240. result.addOptimization(new TextureOptimization(priority, 1024));
  93241. return result;
  93242. };
  93243. /**
  93244. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  93245. * @param targetFrameRate defines the target frame rate (60 by default)
  93246. * @returns a SceneOptimizerOptions object
  93247. */
  93248. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  93249. var result = new SceneOptimizerOptions(targetFrameRate);
  93250. var priority = 0;
  93251. result.addOptimization(new MergeMeshesOptimization(priority));
  93252. result.addOptimization(new ShadowsOptimization(priority));
  93253. result.addOptimization(new LensFlaresOptimization(priority));
  93254. // Next priority
  93255. priority++;
  93256. result.addOptimization(new PostProcessesOptimization(priority));
  93257. result.addOptimization(new ParticlesOptimization(priority));
  93258. // Next priority
  93259. priority++;
  93260. result.addOptimization(new TextureOptimization(priority, 512));
  93261. // Next priority
  93262. priority++;
  93263. result.addOptimization(new RenderTargetsOptimization(priority));
  93264. // Next priority
  93265. priority++;
  93266. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  93267. return result;
  93268. };
  93269. /**
  93270. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  93271. * @param targetFrameRate defines the target frame rate (60 by default)
  93272. * @returns a SceneOptimizerOptions object
  93273. */
  93274. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  93275. var result = new SceneOptimizerOptions(targetFrameRate);
  93276. var priority = 0;
  93277. result.addOptimization(new MergeMeshesOptimization(priority));
  93278. result.addOptimization(new ShadowsOptimization(priority));
  93279. result.addOptimization(new LensFlaresOptimization(priority));
  93280. // Next priority
  93281. priority++;
  93282. result.addOptimization(new PostProcessesOptimization(priority));
  93283. result.addOptimization(new ParticlesOptimization(priority));
  93284. // Next priority
  93285. priority++;
  93286. result.addOptimization(new TextureOptimization(priority, 256));
  93287. // Next priority
  93288. priority++;
  93289. result.addOptimization(new RenderTargetsOptimization(priority));
  93290. // Next priority
  93291. priority++;
  93292. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  93293. return result;
  93294. };
  93295. return SceneOptimizerOptions;
  93296. }());
  93297. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  93298. /**
  93299. * Class used to run optimizations in order to reach a target frame rate
  93300. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93301. */
  93302. var SceneOptimizer = /** @class */ (function () {
  93303. /**
  93304. * Creates a new SceneOptimizer
  93305. * @param scene defines the scene to work on
  93306. * @param options defines the options to use with the SceneOptimizer
  93307. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  93308. * @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)
  93309. */
  93310. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  93311. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  93312. if (improvementMode === void 0) { improvementMode = false; }
  93313. var _this = this;
  93314. this._isRunning = false;
  93315. this._currentPriorityLevel = 0;
  93316. this._targetFrameRate = 60;
  93317. this._trackerDuration = 2000;
  93318. this._currentFrameRate = 0;
  93319. this._improvementMode = false;
  93320. /**
  93321. * Defines an observable called when the optimizer reaches the target frame rate
  93322. */
  93323. this.onSuccessObservable = new BABYLON.Observable();
  93324. /**
  93325. * Defines an observable called when the optimizer enables an optimization
  93326. */
  93327. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  93328. /**
  93329. * Defines an observable called when the optimizer is not able to reach the target frame rate
  93330. */
  93331. this.onFailureObservable = new BABYLON.Observable();
  93332. if (!options) {
  93333. this._options = new SceneOptimizerOptions();
  93334. }
  93335. else {
  93336. this._options = options;
  93337. }
  93338. if (this._options.targetFrameRate) {
  93339. this._targetFrameRate = this._options.targetFrameRate;
  93340. }
  93341. if (this._options.trackerDuration) {
  93342. this._trackerDuration = this._options.trackerDuration;
  93343. }
  93344. if (autoGeneratePriorities) {
  93345. var priority = 0;
  93346. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  93347. var optim = _a[_i];
  93348. optim.priority = priority++;
  93349. }
  93350. }
  93351. this._improvementMode = improvementMode;
  93352. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93353. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  93354. _this._sceneDisposeObserver = null;
  93355. _this.dispose();
  93356. });
  93357. }
  93358. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  93359. /**
  93360. * Gets a boolean indicating if the optimizer is in improvement mode
  93361. */
  93362. get: function () {
  93363. return this._improvementMode;
  93364. },
  93365. enumerable: true,
  93366. configurable: true
  93367. });
  93368. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  93369. /**
  93370. * Gets the current priority level (0 at start)
  93371. */
  93372. get: function () {
  93373. return this._currentPriorityLevel;
  93374. },
  93375. enumerable: true,
  93376. configurable: true
  93377. });
  93378. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  93379. /**
  93380. * Gets the current frame rate checked by the SceneOptimizer
  93381. */
  93382. get: function () {
  93383. return this._currentFrameRate;
  93384. },
  93385. enumerable: true,
  93386. configurable: true
  93387. });
  93388. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  93389. /**
  93390. * Gets or sets the current target frame rate (60 by default)
  93391. */
  93392. get: function () {
  93393. return this._targetFrameRate;
  93394. },
  93395. /**
  93396. * Gets or sets the current target frame rate (60 by default)
  93397. */
  93398. set: function (value) {
  93399. this._targetFrameRate = value;
  93400. },
  93401. enumerable: true,
  93402. configurable: true
  93403. });
  93404. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  93405. /**
  93406. * Gets or sets the current interval between two checks (every 2000ms by default)
  93407. */
  93408. get: function () {
  93409. return this._trackerDuration;
  93410. },
  93411. /**
  93412. * Gets or sets the current interval between two checks (every 2000ms by default)
  93413. */
  93414. set: function (value) {
  93415. this._trackerDuration = value;
  93416. },
  93417. enumerable: true,
  93418. configurable: true
  93419. });
  93420. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  93421. /**
  93422. * Gets the list of active optimizations
  93423. */
  93424. get: function () {
  93425. return this._options.optimizations;
  93426. },
  93427. enumerable: true,
  93428. configurable: true
  93429. });
  93430. /**
  93431. * Stops the current optimizer
  93432. */
  93433. SceneOptimizer.prototype.stop = function () {
  93434. this._isRunning = false;
  93435. };
  93436. /**
  93437. * Reset the optimizer to initial step (current priority level = 0)
  93438. */
  93439. SceneOptimizer.prototype.reset = function () {
  93440. this._currentPriorityLevel = 0;
  93441. };
  93442. /**
  93443. * Start the optimizer. By default it will try to reach a specific framerate
  93444. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  93445. */
  93446. SceneOptimizer.prototype.start = function () {
  93447. var _this = this;
  93448. if (this._isRunning) {
  93449. return;
  93450. }
  93451. this._isRunning = true;
  93452. // Let's wait for the scene to be ready before running our check
  93453. this._scene.executeWhenReady(function () {
  93454. setTimeout(function () {
  93455. _this._checkCurrentState();
  93456. }, _this._trackerDuration);
  93457. });
  93458. };
  93459. SceneOptimizer.prototype._checkCurrentState = function () {
  93460. var _this = this;
  93461. if (!this._isRunning) {
  93462. return;
  93463. }
  93464. var scene = this._scene;
  93465. var options = this._options;
  93466. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93467. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93468. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93469. this._isRunning = false;
  93470. this.onSuccessObservable.notifyObservers(this);
  93471. return;
  93472. }
  93473. // Apply current level of optimizations
  93474. var allDone = true;
  93475. var noOptimizationApplied = true;
  93476. for (var index = 0; index < options.optimizations.length; index++) {
  93477. var optimization = options.optimizations[index];
  93478. if (optimization.priority === this._currentPriorityLevel) {
  93479. noOptimizationApplied = false;
  93480. allDone = allDone && optimization.apply(scene, this);
  93481. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93482. }
  93483. }
  93484. // If no optimization was applied, this is a failure :(
  93485. if (noOptimizationApplied) {
  93486. this._isRunning = false;
  93487. this.onFailureObservable.notifyObservers(this);
  93488. return;
  93489. }
  93490. // If all optimizations were done, move to next level
  93491. if (allDone) {
  93492. this._currentPriorityLevel++;
  93493. }
  93494. // Let's the system running for a specific amount of time before checking FPS
  93495. scene.executeWhenReady(function () {
  93496. setTimeout(function () {
  93497. _this._checkCurrentState();
  93498. }, _this._trackerDuration);
  93499. });
  93500. };
  93501. /**
  93502. * Release all resources
  93503. */
  93504. SceneOptimizer.prototype.dispose = function () {
  93505. this.stop();
  93506. this.onSuccessObservable.clear();
  93507. this.onFailureObservable.clear();
  93508. this.onNewOptimizationAppliedObservable.clear();
  93509. if (this._sceneDisposeObserver) {
  93510. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93511. }
  93512. };
  93513. /**
  93514. * Helper function to create a SceneOptimizer with one single line of code
  93515. * @param scene defines the scene to work on
  93516. * @param options defines the options to use with the SceneOptimizer
  93517. * @param onSuccess defines a callback to call on success
  93518. * @param onFailure defines a callback to call on failure
  93519. * @returns the new SceneOptimizer object
  93520. */
  93521. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93522. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93523. if (onSuccess) {
  93524. optimizer.onSuccessObservable.add(function () {
  93525. onSuccess();
  93526. });
  93527. }
  93528. if (onFailure) {
  93529. optimizer.onFailureObservable.add(function () {
  93530. onFailure();
  93531. });
  93532. }
  93533. optimizer.start();
  93534. return optimizer;
  93535. };
  93536. return SceneOptimizer;
  93537. }());
  93538. BABYLON.SceneOptimizer = SceneOptimizer;
  93539. })(BABYLON || (BABYLON = {}));
  93540. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93541. var BABYLON;
  93542. (function (BABYLON) {
  93543. var OutlineRenderer = /** @class */ (function () {
  93544. function OutlineRenderer(scene) {
  93545. this.zOffset = 1;
  93546. this._scene = scene;
  93547. }
  93548. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93549. var _this = this;
  93550. if (useOverlay === void 0) { useOverlay = false; }
  93551. var scene = this._scene;
  93552. var engine = this._scene.getEngine();
  93553. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93554. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93555. return;
  93556. }
  93557. var mesh = subMesh.getRenderingMesh();
  93558. var material = subMesh.getMaterial();
  93559. if (!material || !scene.activeCamera) {
  93560. return;
  93561. }
  93562. engine.enableEffect(this._effect);
  93563. // Logarithmic depth
  93564. if (material.useLogarithmicDepth) {
  93565. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93566. }
  93567. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93568. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93569. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93570. // Bones
  93571. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93572. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93573. }
  93574. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93575. // Alpha test
  93576. if (material && material.needAlphaTesting()) {
  93577. var alphaTexture = material.getAlphaTestTexture();
  93578. if (alphaTexture) {
  93579. this._effect.setTexture("diffuseSampler", alphaTexture);
  93580. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93581. }
  93582. }
  93583. engine.setZOffset(-this.zOffset);
  93584. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93585. engine.setZOffset(0);
  93586. };
  93587. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93588. var defines = [];
  93589. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93590. var mesh = subMesh.getMesh();
  93591. var material = subMesh.getMaterial();
  93592. if (material) {
  93593. // Alpha test
  93594. if (material.needAlphaTesting()) {
  93595. defines.push("#define ALPHATEST");
  93596. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93597. attribs.push(BABYLON.VertexBuffer.UVKind);
  93598. defines.push("#define UV1");
  93599. }
  93600. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93601. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93602. defines.push("#define UV2");
  93603. }
  93604. }
  93605. //Logarithmic depth
  93606. if (material.useLogarithmicDepth) {
  93607. defines.push("#define LOGARITHMICDEPTH");
  93608. }
  93609. }
  93610. // Bones
  93611. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93614. if (mesh.numBoneInfluencers > 4) {
  93615. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93616. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93617. }
  93618. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93619. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93620. }
  93621. else {
  93622. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93623. }
  93624. // Instances
  93625. if (useInstances) {
  93626. defines.push("#define INSTANCES");
  93627. attribs.push("world0");
  93628. attribs.push("world1");
  93629. attribs.push("world2");
  93630. attribs.push("world3");
  93631. }
  93632. // Get correct effect
  93633. var join = defines.join("\n");
  93634. if (this._cachedDefines !== join) {
  93635. this._cachedDefines = join;
  93636. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93637. }
  93638. return this._effect.isReady();
  93639. };
  93640. return OutlineRenderer;
  93641. }());
  93642. BABYLON.OutlineRenderer = OutlineRenderer;
  93643. })(BABYLON || (BABYLON = {}));
  93644. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93645. var BABYLON;
  93646. (function (BABYLON) {
  93647. var FaceAdjacencies = /** @class */ (function () {
  93648. function FaceAdjacencies() {
  93649. this.edges = new Array();
  93650. this.edgesConnectedCount = 0;
  93651. }
  93652. return FaceAdjacencies;
  93653. }());
  93654. var EdgesRenderer = /** @class */ (function () {
  93655. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93656. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93657. if (epsilon === void 0) { epsilon = 0.95; }
  93658. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93659. this.edgesWidthScalerForOrthographic = 1000.0;
  93660. this.edgesWidthScalerForPerspective = 50.0;
  93661. this._linesPositions = new Array();
  93662. this._linesNormals = new Array();
  93663. this._linesIndices = new Array();
  93664. this._buffers = {};
  93665. this._checkVerticesInsteadOfIndices = false;
  93666. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93667. this.isEnabled = true;
  93668. this._source = source;
  93669. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93670. this._epsilon = epsilon;
  93671. this._prepareRessources();
  93672. this._generateEdgesLines();
  93673. }
  93674. EdgesRenderer.prototype._prepareRessources = function () {
  93675. if (this._lineShader) {
  93676. return;
  93677. }
  93678. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93679. attributes: ["position", "normal"],
  93680. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93681. });
  93682. this._lineShader.disableDepthWrite = true;
  93683. this._lineShader.backFaceCulling = false;
  93684. };
  93685. EdgesRenderer.prototype._rebuild = function () {
  93686. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93687. if (buffer) {
  93688. buffer._rebuild();
  93689. }
  93690. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93691. if (buffer) {
  93692. buffer._rebuild();
  93693. }
  93694. var scene = this._source.getScene();
  93695. var engine = scene.getEngine();
  93696. this._ib = engine.createIndexBuffer(this._linesIndices);
  93697. };
  93698. EdgesRenderer.prototype.dispose = function () {
  93699. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93700. if (buffer) {
  93701. buffer.dispose();
  93702. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93703. }
  93704. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93705. if (buffer) {
  93706. buffer.dispose();
  93707. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93708. }
  93709. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93710. this._lineShader.dispose();
  93711. };
  93712. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93713. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93714. return 0;
  93715. }
  93716. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93717. return 1;
  93718. }
  93719. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93720. return 2;
  93721. }
  93722. return -1;
  93723. };
  93724. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93725. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93726. return 0;
  93727. }
  93728. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93729. return 1;
  93730. }
  93731. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93732. return 2;
  93733. }
  93734. return -1;
  93735. };
  93736. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93737. var needToCreateLine;
  93738. if (edge === undefined) {
  93739. needToCreateLine = true;
  93740. }
  93741. else {
  93742. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93743. needToCreateLine = dotProduct < this._epsilon;
  93744. }
  93745. if (needToCreateLine) {
  93746. var offset = this._linesPositions.length / 3;
  93747. var normal = p0.subtract(p1);
  93748. normal.normalize();
  93749. // Positions
  93750. this._linesPositions.push(p0.x);
  93751. this._linesPositions.push(p0.y);
  93752. this._linesPositions.push(p0.z);
  93753. this._linesPositions.push(p0.x);
  93754. this._linesPositions.push(p0.y);
  93755. this._linesPositions.push(p0.z);
  93756. this._linesPositions.push(p1.x);
  93757. this._linesPositions.push(p1.y);
  93758. this._linesPositions.push(p1.z);
  93759. this._linesPositions.push(p1.x);
  93760. this._linesPositions.push(p1.y);
  93761. this._linesPositions.push(p1.z);
  93762. // Normals
  93763. this._linesNormals.push(p1.x);
  93764. this._linesNormals.push(p1.y);
  93765. this._linesNormals.push(p1.z);
  93766. this._linesNormals.push(-1);
  93767. this._linesNormals.push(p1.x);
  93768. this._linesNormals.push(p1.y);
  93769. this._linesNormals.push(p1.z);
  93770. this._linesNormals.push(1);
  93771. this._linesNormals.push(p0.x);
  93772. this._linesNormals.push(p0.y);
  93773. this._linesNormals.push(p0.z);
  93774. this._linesNormals.push(-1);
  93775. this._linesNormals.push(p0.x);
  93776. this._linesNormals.push(p0.y);
  93777. this._linesNormals.push(p0.z);
  93778. this._linesNormals.push(1);
  93779. // Indices
  93780. this._linesIndices.push(offset);
  93781. this._linesIndices.push(offset + 1);
  93782. this._linesIndices.push(offset + 2);
  93783. this._linesIndices.push(offset);
  93784. this._linesIndices.push(offset + 2);
  93785. this._linesIndices.push(offset + 3);
  93786. }
  93787. };
  93788. EdgesRenderer.prototype._generateEdgesLines = function () {
  93789. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93790. var indices = this._source.getIndices();
  93791. if (!indices || !positions) {
  93792. return;
  93793. }
  93794. // First let's find adjacencies
  93795. var adjacencies = new Array();
  93796. var faceNormals = new Array();
  93797. var index;
  93798. var faceAdjacencies;
  93799. // Prepare faces
  93800. for (index = 0; index < indices.length; index += 3) {
  93801. faceAdjacencies = new FaceAdjacencies();
  93802. var p0Index = indices[index];
  93803. var p1Index = indices[index + 1];
  93804. var p2Index = indices[index + 2];
  93805. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93806. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93807. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93808. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93809. faceNormal.normalize();
  93810. faceNormals.push(faceNormal);
  93811. adjacencies.push(faceAdjacencies);
  93812. }
  93813. // Scan
  93814. for (index = 0; index < adjacencies.length; index++) {
  93815. faceAdjacencies = adjacencies[index];
  93816. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93817. var otherFaceAdjacencies = adjacencies[otherIndex];
  93818. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93819. break;
  93820. }
  93821. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93822. continue;
  93823. }
  93824. var otherP0 = indices[otherIndex * 3];
  93825. var otherP1 = indices[otherIndex * 3 + 1];
  93826. var otherP2 = indices[otherIndex * 3 + 2];
  93827. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93828. var otherEdgeIndex = 0;
  93829. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93830. continue;
  93831. }
  93832. switch (edgeIndex) {
  93833. case 0:
  93834. if (this._checkVerticesInsteadOfIndices) {
  93835. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93836. }
  93837. else {
  93838. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93839. }
  93840. break;
  93841. case 1:
  93842. if (this._checkVerticesInsteadOfIndices) {
  93843. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93844. }
  93845. else {
  93846. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93847. }
  93848. break;
  93849. case 2:
  93850. if (this._checkVerticesInsteadOfIndices) {
  93851. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93852. }
  93853. else {
  93854. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93855. }
  93856. break;
  93857. }
  93858. if (otherEdgeIndex === -1) {
  93859. continue;
  93860. }
  93861. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93862. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93863. faceAdjacencies.edgesConnectedCount++;
  93864. otherFaceAdjacencies.edgesConnectedCount++;
  93865. if (faceAdjacencies.edgesConnectedCount === 3) {
  93866. break;
  93867. }
  93868. }
  93869. }
  93870. }
  93871. // Create lines
  93872. for (index = 0; index < adjacencies.length; index++) {
  93873. // 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
  93874. var current = adjacencies[index];
  93875. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93876. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93877. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93878. }
  93879. // Merge into a single mesh
  93880. var engine = this._source.getScene().getEngine();
  93881. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93882. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93883. this._ib = engine.createIndexBuffer(this._linesIndices);
  93884. this._indicesCount = this._linesIndices.length;
  93885. };
  93886. EdgesRenderer.prototype.render = function () {
  93887. var scene = this._source.getScene();
  93888. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93889. return;
  93890. }
  93891. var engine = scene.getEngine();
  93892. this._lineShader._preBind();
  93893. // VBOs
  93894. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93895. scene.resetCachedMaterial();
  93896. this._lineShader.setColor4("color", this._source.edgesColor);
  93897. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93898. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93899. }
  93900. else {
  93901. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93902. }
  93903. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93904. this._lineShader.bind(this._source.getWorldMatrix());
  93905. // Draw order
  93906. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93907. this._lineShader.unbind();
  93908. engine.setDepthWrite(true);
  93909. };
  93910. return EdgesRenderer;
  93911. }());
  93912. BABYLON.EdgesRenderer = EdgesRenderer;
  93913. })(BABYLON || (BABYLON = {}));
  93914. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93915. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93916. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93917. s = arguments[i];
  93918. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93919. t[p] = s[p];
  93920. }
  93921. return t;
  93922. };
  93923. var BABYLON;
  93924. (function (BABYLON) {
  93925. /**
  93926. * The effect layer Helps adding post process effect blended with the main pass.
  93927. *
  93928. * This can be for instance use to generate glow or higlight effects on the scene.
  93929. *
  93930. * The effect layer class can not be used directly and is intented to inherited from to be
  93931. * customized per effects.
  93932. */
  93933. var EffectLayer = /** @class */ (function () {
  93934. /**
  93935. * Instantiates a new effect Layer and references it in the scene.
  93936. * @param name The name of the layer
  93937. * @param scene The scene to use the layer in
  93938. */
  93939. function EffectLayer(
  93940. /** The Friendly of the effect in the scene */
  93941. name, scene) {
  93942. this._vertexBuffers = {};
  93943. this._maxSize = 0;
  93944. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93945. this._shouldRender = true;
  93946. this._postProcesses = [];
  93947. this._textures = [];
  93948. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93949. /**
  93950. * The clear color of the texture used to generate the glow map.
  93951. */
  93952. this.neutralColor = new BABYLON.Color4();
  93953. /**
  93954. * Specifies wether the highlight layer is enabled or not.
  93955. */
  93956. this.isEnabled = true;
  93957. /**
  93958. * An event triggered when the effect layer has been disposed.
  93959. */
  93960. this.onDisposeObservable = new BABYLON.Observable();
  93961. /**
  93962. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93963. */
  93964. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93965. /**
  93966. * An event triggered when the generated texture is being merged in the scene.
  93967. */
  93968. this.onBeforeComposeObservable = new BABYLON.Observable();
  93969. /**
  93970. * An event triggered when the generated texture has been merged in the scene.
  93971. */
  93972. this.onAfterComposeObservable = new BABYLON.Observable();
  93973. /**
  93974. * An event triggered when the efffect layer changes its size.
  93975. */
  93976. this.onSizeChangedObservable = new BABYLON.Observable();
  93977. this.name = name;
  93978. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93979. this._engine = scene.getEngine();
  93980. this._maxSize = this._engine.getCaps().maxTextureSize;
  93981. this._scene.effectLayers.push(this);
  93982. // Generate Buffers
  93983. this._generateIndexBuffer();
  93984. this._genrateVertexBuffer();
  93985. }
  93986. Object.defineProperty(EffectLayer.prototype, "camera", {
  93987. /**
  93988. * Gets the camera attached to the layer.
  93989. */
  93990. get: function () {
  93991. return this._effectLayerOptions.camera;
  93992. },
  93993. enumerable: true,
  93994. configurable: true
  93995. });
  93996. /**
  93997. * Initializes the effect layer with the required options.
  93998. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93999. */
  94000. EffectLayer.prototype._init = function (options) {
  94001. // Adapt options
  94002. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94003. this._setMainTextureSize();
  94004. this._createMainTexture();
  94005. this._createTextureAndPostProcesses();
  94006. this._mergeEffect = this._createMergeEffect();
  94007. };
  94008. /**
  94009. * Generates the index buffer of the full screen quad blending to the main canvas.
  94010. */
  94011. EffectLayer.prototype._generateIndexBuffer = function () {
  94012. // Indices
  94013. var indices = [];
  94014. indices.push(0);
  94015. indices.push(1);
  94016. indices.push(2);
  94017. indices.push(0);
  94018. indices.push(2);
  94019. indices.push(3);
  94020. this._indexBuffer = this._engine.createIndexBuffer(indices);
  94021. };
  94022. /**
  94023. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  94024. */
  94025. EffectLayer.prototype._genrateVertexBuffer = function () {
  94026. // VBO
  94027. var vertices = [];
  94028. vertices.push(1, 1);
  94029. vertices.push(-1, 1);
  94030. vertices.push(-1, -1);
  94031. vertices.push(1, -1);
  94032. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94033. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94034. };
  94035. /**
  94036. * Sets the main texture desired size which is the closest power of two
  94037. * of the engine canvas size.
  94038. */
  94039. EffectLayer.prototype._setMainTextureSize = function () {
  94040. if (this._effectLayerOptions.mainTextureFixedSize) {
  94041. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  94042. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  94043. }
  94044. else {
  94045. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  94046. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  94047. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  94048. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  94049. }
  94050. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  94051. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  94052. };
  94053. /**
  94054. * Creates the main texture for the effect layer.
  94055. */
  94056. EffectLayer.prototype._createMainTexture = function () {
  94057. var _this = this;
  94058. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  94059. width: this._mainTextureDesiredSize.width,
  94060. height: this._mainTextureDesiredSize.height
  94061. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94062. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  94063. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94064. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94065. this._mainTexture.anisotropicFilteringLevel = 1;
  94066. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94067. this._mainTexture.renderParticles = false;
  94068. this._mainTexture.renderList = null;
  94069. this._mainTexture.ignoreCameraViewport = true;
  94070. // Custom render function
  94071. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  94072. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  94073. var index;
  94074. var engine = _this._scene.getEngine();
  94075. if (depthOnlySubMeshes.length) {
  94076. engine.setColorWrite(false);
  94077. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  94078. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  94079. }
  94080. engine.setColorWrite(true);
  94081. }
  94082. for (index = 0; index < opaqueSubMeshes.length; index++) {
  94083. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  94084. }
  94085. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  94086. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  94087. }
  94088. for (index = 0; index < transparentSubMeshes.length; index++) {
  94089. _this._renderSubMesh(transparentSubMeshes.data[index]);
  94090. }
  94091. };
  94092. this._mainTexture.onClearObservable.add(function (engine) {
  94093. engine.clear(_this.neutralColor, true, true, true);
  94094. });
  94095. };
  94096. /**
  94097. * Checks for the readiness of the element composing the layer.
  94098. * @param subMesh the mesh to check for
  94099. * @param useInstances specify wether or not to use instances to render the mesh
  94100. * @param emissiveTexture the associated emissive texture used to generate the glow
  94101. * @return true if ready otherwise, false
  94102. */
  94103. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  94104. var material = subMesh.getMaterial();
  94105. if (!material) {
  94106. return false;
  94107. }
  94108. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  94109. return false;
  94110. }
  94111. var defines = [];
  94112. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94113. var mesh = subMesh.getMesh();
  94114. var uv1 = false;
  94115. var uv2 = false;
  94116. // Alpha test
  94117. if (material && material.needAlphaTesting()) {
  94118. var alphaTexture = material.getAlphaTestTexture();
  94119. if (alphaTexture) {
  94120. defines.push("#define ALPHATEST");
  94121. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94122. alphaTexture.coordinatesIndex === 1) {
  94123. defines.push("#define DIFFUSEUV2");
  94124. uv2 = true;
  94125. }
  94126. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94127. defines.push("#define DIFFUSEUV1");
  94128. uv1 = true;
  94129. }
  94130. }
  94131. }
  94132. // Emissive
  94133. if (emissiveTexture) {
  94134. defines.push("#define EMISSIVE");
  94135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  94136. emissiveTexture.coordinatesIndex === 1) {
  94137. defines.push("#define EMISSIVEUV2");
  94138. uv2 = true;
  94139. }
  94140. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94141. defines.push("#define EMISSIVEUV1");
  94142. uv1 = true;
  94143. }
  94144. }
  94145. if (uv1) {
  94146. attribs.push(BABYLON.VertexBuffer.UVKind);
  94147. defines.push("#define UV1");
  94148. }
  94149. if (uv2) {
  94150. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94151. defines.push("#define UV2");
  94152. }
  94153. // Bones
  94154. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94155. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94156. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94157. if (mesh.numBoneInfluencers > 4) {
  94158. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94159. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94160. }
  94161. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94162. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  94163. }
  94164. else {
  94165. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94166. }
  94167. // Morph targets
  94168. var manager = mesh.morphTargetManager;
  94169. var morphInfluencers = 0;
  94170. if (manager) {
  94171. if (manager.numInfluencers > 0) {
  94172. defines.push("#define MORPHTARGETS");
  94173. morphInfluencers = manager.numInfluencers;
  94174. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  94175. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  94176. }
  94177. }
  94178. // Instances
  94179. if (useInstances) {
  94180. defines.push("#define INSTANCES");
  94181. attribs.push("world0");
  94182. attribs.push("world1");
  94183. attribs.push("world2");
  94184. attribs.push("world3");
  94185. }
  94186. // Get correct effect
  94187. var join = defines.join("\n");
  94188. if (this._cachedDefines !== join) {
  94189. this._cachedDefines = join;
  94190. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  94191. }
  94192. return this._effectLayerMapGenerationEffect.isReady();
  94193. };
  94194. /**
  94195. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  94196. */
  94197. EffectLayer.prototype.render = function () {
  94198. var currentEffect = this._mergeEffect;
  94199. // Check
  94200. if (!currentEffect.isReady())
  94201. return;
  94202. for (var i = 0; i < this._postProcesses.length; i++) {
  94203. if (!this._postProcesses[i].isReady()) {
  94204. return;
  94205. }
  94206. }
  94207. var engine = this._scene.getEngine();
  94208. this.onBeforeComposeObservable.notifyObservers(this);
  94209. // Render
  94210. engine.enableEffect(currentEffect);
  94211. engine.setState(false);
  94212. // VBOs
  94213. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94214. // Cache
  94215. var previousAlphaMode = engine.getAlphaMode();
  94216. // Go Blend.
  94217. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  94218. // Blends the map on the main canvas.
  94219. this._internalRender(currentEffect);
  94220. // Restore Alpha
  94221. engine.setAlphaMode(previousAlphaMode);
  94222. this.onAfterComposeObservable.notifyObservers(this);
  94223. // Handle size changes.
  94224. var size = this._mainTexture.getSize();
  94225. this._setMainTextureSize();
  94226. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  94227. // Recreate RTT and post processes on size change.
  94228. this.onSizeChangedObservable.notifyObservers(this);
  94229. this._disposeTextureAndPostProcesses();
  94230. this._createMainTexture();
  94231. this._createTextureAndPostProcesses();
  94232. }
  94233. };
  94234. /**
  94235. * Determine if a given mesh will be used in the current effect.
  94236. * @param mesh mesh to test
  94237. * @returns true if the mesh will be used
  94238. */
  94239. EffectLayer.prototype.hasMesh = function (mesh) {
  94240. return true;
  94241. };
  94242. /**
  94243. * Returns true if the layer contains information to display, otherwise false.
  94244. * @returns true if the glow layer should be rendered
  94245. */
  94246. EffectLayer.prototype.shouldRender = function () {
  94247. return this.isEnabled && this._shouldRender;
  94248. };
  94249. /**
  94250. * Returns true if the mesh should render, otherwise false.
  94251. * @param mesh The mesh to render
  94252. * @returns true if it should render otherwise false
  94253. */
  94254. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  94255. return true;
  94256. };
  94257. /**
  94258. * Returns true if the mesh should render, otherwise false.
  94259. * @param mesh The mesh to render
  94260. * @returns true if it should render otherwise false
  94261. */
  94262. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  94263. return true;
  94264. };
  94265. /**
  94266. * Renders the submesh passed in parameter to the generation map.
  94267. */
  94268. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  94269. var _this = this;
  94270. if (!this.shouldRender()) {
  94271. return;
  94272. }
  94273. var material = subMesh.getMaterial();
  94274. var mesh = subMesh.getRenderingMesh();
  94275. var scene = this._scene;
  94276. var engine = scene.getEngine();
  94277. if (!material) {
  94278. return;
  94279. }
  94280. // Do not block in blend mode.
  94281. if (material.needAlphaBlendingForMesh(mesh)) {
  94282. return;
  94283. }
  94284. // Culling
  94285. engine.setState(material.backFaceCulling);
  94286. // Managing instances
  94287. var batch = mesh._getInstancesRenderList(subMesh._id);
  94288. if (batch.mustReturn) {
  94289. return;
  94290. }
  94291. // Early Exit per mesh
  94292. if (!this._shouldRenderMesh(mesh)) {
  94293. return;
  94294. }
  94295. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94296. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  94297. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  94298. engine.enableEffect(this._effectLayerMapGenerationEffect);
  94299. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  94300. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  94301. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  94302. // Alpha test
  94303. if (material && material.needAlphaTesting()) {
  94304. var alphaTexture = material.getAlphaTestTexture();
  94305. if (alphaTexture) {
  94306. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  94307. var textureMatrix = alphaTexture.getTextureMatrix();
  94308. if (textureMatrix) {
  94309. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  94310. }
  94311. }
  94312. }
  94313. // Glow emissive only
  94314. if (this._emissiveTextureAndColor.texture) {
  94315. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  94316. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  94317. }
  94318. // Bones
  94319. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94320. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94321. }
  94322. // Morph targets
  94323. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  94324. // Draw
  94325. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  94326. }
  94327. else {
  94328. // Need to reset refresh rate of the shadowMap
  94329. this._mainTexture.resetRefreshCounter();
  94330. }
  94331. };
  94332. /**
  94333. * Rebuild the required buffers.
  94334. * @hidden Internal use only.
  94335. */
  94336. EffectLayer.prototype._rebuild = function () {
  94337. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94338. if (vb) {
  94339. vb._rebuild();
  94340. }
  94341. this._generateIndexBuffer();
  94342. };
  94343. /**
  94344. * Dispose only the render target textures and post process.
  94345. */
  94346. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  94347. this._mainTexture.dispose();
  94348. for (var i = 0; i < this._postProcesses.length; i++) {
  94349. if (this._postProcesses[i]) {
  94350. this._postProcesses[i].dispose();
  94351. }
  94352. }
  94353. this._postProcesses = [];
  94354. for (var i = 0; i < this._textures.length; i++) {
  94355. if (this._textures[i]) {
  94356. this._textures[i].dispose();
  94357. }
  94358. }
  94359. this._textures = [];
  94360. };
  94361. /**
  94362. * Dispose the highlight layer and free resources.
  94363. */
  94364. EffectLayer.prototype.dispose = function () {
  94365. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94366. if (vertexBuffer) {
  94367. vertexBuffer.dispose();
  94368. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94369. }
  94370. if (this._indexBuffer) {
  94371. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94372. this._indexBuffer = null;
  94373. }
  94374. // Clean textures and post processes
  94375. this._disposeTextureAndPostProcesses();
  94376. // Remove from scene
  94377. var index = this._scene.effectLayers.indexOf(this, 0);
  94378. if (index > -1) {
  94379. this._scene.effectLayers.splice(index, 1);
  94380. }
  94381. // Callback
  94382. this.onDisposeObservable.notifyObservers(this);
  94383. this.onDisposeObservable.clear();
  94384. this.onBeforeRenderMainTextureObservable.clear();
  94385. this.onBeforeComposeObservable.clear();
  94386. this.onAfterComposeObservable.clear();
  94387. this.onSizeChangedObservable.clear();
  94388. };
  94389. /**
  94390. * Gets the class name of the effect layer
  94391. * @returns the string with the class name of the effect layer
  94392. */
  94393. EffectLayer.prototype.getClassName = function () {
  94394. return "EffectLayer";
  94395. };
  94396. /**
  94397. * Creates an effect layer from parsed effect layer data
  94398. * @param parsedEffectLayer defines effect layer data
  94399. * @param scene defines the current scene
  94400. * @param rootUrl defines the root URL containing the effect layer information
  94401. * @returns a parsed effect Layer
  94402. */
  94403. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  94404. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  94405. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  94406. };
  94407. __decorate([
  94408. BABYLON.serialize()
  94409. ], EffectLayer.prototype, "name", void 0);
  94410. __decorate([
  94411. BABYLON.serializeAsColor4()
  94412. ], EffectLayer.prototype, "neutralColor", void 0);
  94413. __decorate([
  94414. BABYLON.serialize()
  94415. ], EffectLayer.prototype, "isEnabled", void 0);
  94416. __decorate([
  94417. BABYLON.serializeAsCameraReference()
  94418. ], EffectLayer.prototype, "camera", null);
  94419. return EffectLayer;
  94420. }());
  94421. BABYLON.EffectLayer = EffectLayer;
  94422. })(BABYLON || (BABYLON = {}));
  94423. //# sourceMappingURL=babylon.effectLayer.js.map
  94424. var BABYLON;
  94425. (function (BABYLON) {
  94426. /**
  94427. * Special Glow Blur post process only blurring the alpha channel
  94428. * It enforces keeping the most luminous color in the color channel.
  94429. */
  94430. var GlowBlurPostProcess = /** @class */ (function (_super) {
  94431. __extends(GlowBlurPostProcess, _super);
  94432. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  94433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  94434. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  94435. _this.direction = direction;
  94436. _this.kernel = kernel;
  94437. _this.onApplyObservable.add(function (effect) {
  94438. effect.setFloat2("screenSize", _this.width, _this.height);
  94439. effect.setVector2("direction", _this.direction);
  94440. effect.setFloat("blurWidth", _this.kernel);
  94441. });
  94442. return _this;
  94443. }
  94444. return GlowBlurPostProcess;
  94445. }(BABYLON.PostProcess));
  94446. /**
  94447. * The highlight layer Helps adding a glow effect around a mesh.
  94448. *
  94449. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94450. * glowy meshes to your scene.
  94451. *
  94452. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  94453. */
  94454. var HighlightLayer = /** @class */ (function (_super) {
  94455. __extends(HighlightLayer, _super);
  94456. /**
  94457. * Instantiates a new highlight Layer and references it to the scene..
  94458. * @param name The name of the layer
  94459. * @param scene The scene to use the layer in
  94460. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  94461. */
  94462. function HighlightLayer(name, scene, options) {
  94463. var _this = _super.call(this, name, scene) || this;
  94464. _this.name = name;
  94465. /**
  94466. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94467. */
  94468. _this.innerGlow = true;
  94469. /**
  94470. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94471. */
  94472. _this.outerGlow = true;
  94473. /**
  94474. * An event triggered when the highlight layer is being blurred.
  94475. */
  94476. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94477. /**
  94478. * An event triggered when the highlight layer has been blurred.
  94479. */
  94480. _this.onAfterBlurObservable = new BABYLON.Observable();
  94481. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94482. _this._meshes = {};
  94483. _this._excludedMeshes = {};
  94484. _this.neutralColor = HighlightLayer.NeutralColor;
  94485. // Warn on stencil
  94486. if (!_this._engine.isStencilEnable) {
  94487. 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 }");
  94488. }
  94489. // Adapt options
  94490. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94491. // Initialize the layer
  94492. _this._init({
  94493. alphaBlendingMode: _this._options.alphaBlendingMode,
  94494. camera: _this._options.camera,
  94495. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94496. mainTextureRatio: _this._options.mainTextureRatio
  94497. });
  94498. // Do not render as long as no meshes have been added
  94499. _this._shouldRender = false;
  94500. return _this;
  94501. }
  94502. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94503. /**
  94504. * Gets the horizontal size of the blur.
  94505. */
  94506. get: function () {
  94507. return this._horizontalBlurPostprocess.kernel;
  94508. },
  94509. /**
  94510. * Specifies the horizontal size of the blur.
  94511. */
  94512. set: function (value) {
  94513. this._horizontalBlurPostprocess.kernel = value;
  94514. },
  94515. enumerable: true,
  94516. configurable: true
  94517. });
  94518. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94519. /**
  94520. * Gets the vertical size of the blur.
  94521. */
  94522. get: function () {
  94523. return this._verticalBlurPostprocess.kernel;
  94524. },
  94525. /**
  94526. * Specifies the vertical size of the blur.
  94527. */
  94528. set: function (value) {
  94529. this._verticalBlurPostprocess.kernel = value;
  94530. },
  94531. enumerable: true,
  94532. configurable: true
  94533. });
  94534. /**
  94535. * Get the effect name of the layer.
  94536. * @return The effect name
  94537. */
  94538. HighlightLayer.prototype.getEffectName = function () {
  94539. return HighlightLayer.EffectName;
  94540. };
  94541. /**
  94542. * Create the merge effect. This is the shader use to blit the information back
  94543. * to the main canvas at the end of the scene rendering.
  94544. */
  94545. HighlightLayer.prototype._createMergeEffect = function () {
  94546. // Effect
  94547. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94548. };
  94549. /**
  94550. * Creates the render target textures and post processes used in the highlight layer.
  94551. */
  94552. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94553. var _this = this;
  94554. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94555. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94556. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94557. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94558. var textureType = 0;
  94559. if (this._engine.getCaps().textureHalfFloatRender) {
  94560. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94561. }
  94562. else {
  94563. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94564. }
  94565. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94566. width: blurTextureWidth,
  94567. height: blurTextureHeight
  94568. }, this._scene, false, true, textureType);
  94569. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94570. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94571. this._blurTexture.anisotropicFilteringLevel = 16;
  94572. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94573. this._blurTexture.renderParticles = false;
  94574. this._blurTexture.ignoreCameraViewport = true;
  94575. this._textures = [this._blurTexture];
  94576. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94577. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94578. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94579. effect.setTexture("textureSampler", _this._mainTexture);
  94580. });
  94581. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94582. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94583. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94584. });
  94585. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94586. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94587. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94588. });
  94589. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94590. }
  94591. else {
  94592. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94593. width: blurTextureWidth,
  94594. height: blurTextureHeight
  94595. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94596. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94597. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94598. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94599. effect.setTexture("textureSampler", _this._mainTexture);
  94600. });
  94601. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94602. width: blurTextureWidth,
  94603. height: blurTextureHeight
  94604. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94605. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94606. }
  94607. this._mainTexture.onAfterUnbindObservable.add(function () {
  94608. _this.onBeforeBlurObservable.notifyObservers(_this);
  94609. var internalTexture = _this._blurTexture.getInternalTexture();
  94610. if (internalTexture) {
  94611. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94612. }
  94613. _this.onAfterBlurObservable.notifyObservers(_this);
  94614. });
  94615. // Prevent autoClear.
  94616. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94617. };
  94618. /**
  94619. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94620. */
  94621. HighlightLayer.prototype.needStencil = function () {
  94622. return true;
  94623. };
  94624. /**
  94625. * Checks for the readiness of the element composing the layer.
  94626. * @param subMesh the mesh to check for
  94627. * @param useInstances specify wether or not to use instances to render the mesh
  94628. * @param emissiveTexture the associated emissive texture used to generate the glow
  94629. * @return true if ready otherwise, false
  94630. */
  94631. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94632. var material = subMesh.getMaterial();
  94633. var mesh = subMesh.getRenderingMesh();
  94634. if (!material || !mesh || !this._meshes) {
  94635. return false;
  94636. }
  94637. var emissiveTexture = null;
  94638. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94639. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94640. emissiveTexture = material.emissiveTexture;
  94641. }
  94642. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94643. };
  94644. /**
  94645. * Implementation specific of rendering the generating effect on the main canvas.
  94646. * @param effect The effect used to render through
  94647. */
  94648. HighlightLayer.prototype._internalRender = function (effect) {
  94649. // Texture
  94650. effect.setTexture("textureSampler", this._blurTexture);
  94651. // Cache
  94652. var engine = this._engine;
  94653. var previousStencilBuffer = engine.getStencilBuffer();
  94654. var previousStencilFunction = engine.getStencilFunction();
  94655. var previousStencilMask = engine.getStencilMask();
  94656. var previousStencilOperationPass = engine.getStencilOperationPass();
  94657. var previousStencilOperationFail = engine.getStencilOperationFail();
  94658. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94659. var previousStencilReference = engine.getStencilFunctionReference();
  94660. // Stencil operations
  94661. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94662. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94663. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94664. // Draw order
  94665. engine.setStencilMask(0x00);
  94666. engine.setStencilBuffer(true);
  94667. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94668. // 2 passes inner outer
  94669. if (this.outerGlow) {
  94670. effect.setFloat("offset", 0);
  94671. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94672. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94673. }
  94674. if (this.innerGlow) {
  94675. effect.setFloat("offset", 1);
  94676. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94677. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94678. }
  94679. // Restore Cache
  94680. engine.setStencilFunction(previousStencilFunction);
  94681. engine.setStencilMask(previousStencilMask);
  94682. engine.setStencilBuffer(previousStencilBuffer);
  94683. engine.setStencilOperationPass(previousStencilOperationPass);
  94684. engine.setStencilOperationFail(previousStencilOperationFail);
  94685. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94686. engine.setStencilFunctionReference(previousStencilReference);
  94687. };
  94688. /**
  94689. * Returns true if the layer contains information to display, otherwise false.
  94690. */
  94691. HighlightLayer.prototype.shouldRender = function () {
  94692. if (_super.prototype.shouldRender.call(this)) {
  94693. return this._meshes ? true : false;
  94694. }
  94695. return false;
  94696. };
  94697. /**
  94698. * Returns true if the mesh should render, otherwise false.
  94699. * @param mesh The mesh to render
  94700. * @returns true if it should render otherwise false
  94701. */
  94702. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94703. // Excluded Mesh
  94704. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94705. return false;
  94706. }
  94707. ;
  94708. return true;
  94709. };
  94710. /**
  94711. * Sets the required values for both the emissive texture and and the main color.
  94712. */
  94713. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94714. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94715. if (highlightLayerMesh) {
  94716. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94717. }
  94718. else {
  94719. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94720. }
  94721. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94722. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94723. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94724. }
  94725. else {
  94726. this._emissiveTextureAndColor.texture = null;
  94727. }
  94728. };
  94729. /**
  94730. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94731. * @param mesh The mesh to exclude from the highlight layer
  94732. */
  94733. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94734. if (!this._excludedMeshes) {
  94735. return;
  94736. }
  94737. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94738. if (!meshExcluded) {
  94739. this._excludedMeshes[mesh.uniqueId] = {
  94740. mesh: mesh,
  94741. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94742. mesh.getEngine().setStencilBuffer(false);
  94743. }),
  94744. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94745. mesh.getEngine().setStencilBuffer(true);
  94746. }),
  94747. };
  94748. }
  94749. };
  94750. /**
  94751. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94752. * @param mesh The mesh to highlight
  94753. */
  94754. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94755. if (!this._excludedMeshes) {
  94756. return;
  94757. }
  94758. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94759. if (meshExcluded) {
  94760. if (meshExcluded.beforeRender) {
  94761. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94762. }
  94763. if (meshExcluded.afterRender) {
  94764. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94765. }
  94766. }
  94767. this._excludedMeshes[mesh.uniqueId] = null;
  94768. };
  94769. /**
  94770. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94771. * @param mesh mesh to test
  94772. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94773. */
  94774. HighlightLayer.prototype.hasMesh = function (mesh) {
  94775. if (!this._meshes) {
  94776. return false;
  94777. }
  94778. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94779. };
  94780. /**
  94781. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94782. * @param mesh The mesh to highlight
  94783. * @param color The color of the highlight
  94784. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94785. */
  94786. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94787. var _this = this;
  94788. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94789. if (!this._meshes) {
  94790. return;
  94791. }
  94792. var meshHighlight = this._meshes[mesh.uniqueId];
  94793. if (meshHighlight) {
  94794. meshHighlight.color = color;
  94795. }
  94796. else {
  94797. this._meshes[mesh.uniqueId] = {
  94798. mesh: mesh,
  94799. color: color,
  94800. // Lambda required for capture due to Observable this context
  94801. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94802. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94803. _this._defaultStencilReference(mesh);
  94804. }
  94805. else {
  94806. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94807. }
  94808. }),
  94809. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94810. glowEmissiveOnly: glowEmissiveOnly
  94811. };
  94812. }
  94813. this._shouldRender = true;
  94814. };
  94815. /**
  94816. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94817. * @param mesh The mesh to highlight
  94818. */
  94819. HighlightLayer.prototype.removeMesh = function (mesh) {
  94820. if (!this._meshes) {
  94821. return;
  94822. }
  94823. var meshHighlight = this._meshes[mesh.uniqueId];
  94824. if (meshHighlight) {
  94825. if (meshHighlight.observerHighlight) {
  94826. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94827. }
  94828. if (meshHighlight.observerDefault) {
  94829. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94830. }
  94831. delete this._meshes[mesh.uniqueId];
  94832. }
  94833. this._shouldRender = false;
  94834. for (var meshHighlightToCheck in this._meshes) {
  94835. if (this._meshes[meshHighlightToCheck]) {
  94836. this._shouldRender = true;
  94837. break;
  94838. }
  94839. }
  94840. };
  94841. /**
  94842. * Force the stencil to the normal expected value for none glowing parts
  94843. */
  94844. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94845. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94846. };
  94847. /**
  94848. * Free any resources and references associated to a mesh.
  94849. * Internal use
  94850. * @param mesh The mesh to free.
  94851. */
  94852. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94853. this.removeMesh(mesh);
  94854. this.removeExcludedMesh(mesh);
  94855. };
  94856. /**
  94857. * Dispose the highlight layer and free resources.
  94858. */
  94859. HighlightLayer.prototype.dispose = function () {
  94860. if (this._meshes) {
  94861. // Clean mesh references
  94862. for (var id in this._meshes) {
  94863. var meshHighlight = this._meshes[id];
  94864. if (meshHighlight && meshHighlight.mesh) {
  94865. if (meshHighlight.observerHighlight) {
  94866. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94867. }
  94868. if (meshHighlight.observerDefault) {
  94869. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94870. }
  94871. }
  94872. }
  94873. this._meshes = null;
  94874. }
  94875. if (this._excludedMeshes) {
  94876. for (var id in this._excludedMeshes) {
  94877. var meshHighlight = this._excludedMeshes[id];
  94878. if (meshHighlight) {
  94879. if (meshHighlight.beforeRender) {
  94880. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94881. }
  94882. if (meshHighlight.afterRender) {
  94883. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94884. }
  94885. }
  94886. }
  94887. this._excludedMeshes = null;
  94888. }
  94889. _super.prototype.dispose.call(this);
  94890. };
  94891. /**
  94892. * Gets the class name of the effect layer
  94893. * @returns the string with the class name of the effect layer
  94894. */
  94895. HighlightLayer.prototype.getClassName = function () {
  94896. return "HighlightLayer";
  94897. };
  94898. /**
  94899. * Serializes this Highlight layer
  94900. * @returns a serialized Highlight layer object
  94901. */
  94902. HighlightLayer.prototype.serialize = function () {
  94903. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94904. serializationObject.customType = "BABYLON.HighlightLayer";
  94905. // Highlighted meshes
  94906. serializationObject.meshes = [];
  94907. if (this._meshes) {
  94908. for (var m in this._meshes) {
  94909. var mesh = this._meshes[m];
  94910. if (mesh) {
  94911. serializationObject.meshes.push({
  94912. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94913. color: mesh.color.asArray(),
  94914. meshId: mesh.mesh.id
  94915. });
  94916. }
  94917. }
  94918. }
  94919. // Excluded meshes
  94920. serializationObject.excludedMeshes = [];
  94921. if (this._excludedMeshes) {
  94922. for (var e in this._excludedMeshes) {
  94923. var excludedMesh = this._excludedMeshes[e];
  94924. if (excludedMesh) {
  94925. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94926. }
  94927. }
  94928. }
  94929. return serializationObject;
  94930. };
  94931. /**
  94932. * Creates a Highlight layer from parsed Highlight layer data
  94933. * @param parsedHightlightLayer defines the Highlight layer data
  94934. * @param scene defines the current scene
  94935. * @param rootUrl defines the root URL containing the Highlight layer information
  94936. * @returns a parsed Highlight layer
  94937. */
  94938. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94939. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94940. var index;
  94941. // Excluded meshes
  94942. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94943. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94944. if (mesh) {
  94945. hl.addExcludedMesh(mesh);
  94946. }
  94947. }
  94948. // Included meshes
  94949. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94950. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94951. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94952. if (mesh) {
  94953. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94954. }
  94955. }
  94956. return hl;
  94957. };
  94958. /**
  94959. * Effect Name of the highlight layer.
  94960. */
  94961. HighlightLayer.EffectName = "HighlightLayer";
  94962. /**
  94963. * The neutral color used during the preparation of the glow effect.
  94964. * This is black by default as the blend operation is a blend operation.
  94965. */
  94966. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94967. /**
  94968. * Stencil value used for glowing meshes.
  94969. */
  94970. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94971. /**
  94972. * Stencil value used for the other meshes in the scene.
  94973. */
  94974. HighlightLayer.NormalMeshStencilReference = 0x01;
  94975. __decorate([
  94976. BABYLON.serialize()
  94977. ], HighlightLayer.prototype, "innerGlow", void 0);
  94978. __decorate([
  94979. BABYLON.serialize()
  94980. ], HighlightLayer.prototype, "outerGlow", void 0);
  94981. __decorate([
  94982. BABYLON.serialize()
  94983. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94984. __decorate([
  94985. BABYLON.serialize()
  94986. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94987. __decorate([
  94988. BABYLON.serialize("options")
  94989. ], HighlightLayer.prototype, "_options", void 0);
  94990. return HighlightLayer;
  94991. }(BABYLON.EffectLayer));
  94992. BABYLON.HighlightLayer = HighlightLayer;
  94993. })(BABYLON || (BABYLON = {}));
  94994. //# sourceMappingURL=babylon.highlightLayer.js.map
  94995. var BABYLON;
  94996. (function (BABYLON) {
  94997. /**
  94998. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94999. *
  95000. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95001. * glowy meshes to your scene.
  95002. *
  95003. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  95004. */
  95005. var GlowLayer = /** @class */ (function (_super) {
  95006. __extends(GlowLayer, _super);
  95007. /**
  95008. * Instantiates a new glow Layer and references it to the scene.
  95009. * @param name The name of the layer
  95010. * @param scene The scene to use the layer in
  95011. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  95012. */
  95013. function GlowLayer(name, scene, options) {
  95014. var _this = _super.call(this, name, scene) || this;
  95015. _this._intensity = 1.0;
  95016. _this._includedOnlyMeshes = [];
  95017. _this._excludedMeshes = [];
  95018. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  95019. // Adapt options
  95020. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  95021. // Initialize the layer
  95022. _this._init({
  95023. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  95024. camera: _this._options.camera,
  95025. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95026. mainTextureRatio: _this._options.mainTextureRatio
  95027. });
  95028. return _this;
  95029. }
  95030. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  95031. /**
  95032. * Gets the kernel size of the blur.
  95033. */
  95034. get: function () {
  95035. return this._horizontalBlurPostprocess1.kernel;
  95036. },
  95037. /**
  95038. * Sets the kernel size of the blur.
  95039. */
  95040. set: function (value) {
  95041. this._horizontalBlurPostprocess1.kernel = value;
  95042. this._verticalBlurPostprocess1.kernel = value;
  95043. this._horizontalBlurPostprocess2.kernel = value;
  95044. this._verticalBlurPostprocess2.kernel = value;
  95045. },
  95046. enumerable: true,
  95047. configurable: true
  95048. });
  95049. Object.defineProperty(GlowLayer.prototype, "intensity", {
  95050. /**
  95051. * Gets the glow intensity.
  95052. */
  95053. get: function () {
  95054. return this._intensity;
  95055. },
  95056. /**
  95057. * Sets the glow intensity.
  95058. */
  95059. set: function (value) {
  95060. this._intensity = value;
  95061. },
  95062. enumerable: true,
  95063. configurable: true
  95064. });
  95065. /**
  95066. * Get the effect name of the layer.
  95067. * @return The effect name
  95068. */
  95069. GlowLayer.prototype.getEffectName = function () {
  95070. return GlowLayer.EffectName;
  95071. };
  95072. /**
  95073. * Create the merge effect. This is the shader use to blit the information back
  95074. * to the main canvas at the end of the scene rendering.
  95075. */
  95076. GlowLayer.prototype._createMergeEffect = function () {
  95077. // Effect
  95078. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  95079. };
  95080. /**
  95081. * Creates the render target textures and post processes used in the glow layer.
  95082. */
  95083. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  95084. var _this = this;
  95085. var blurTextureWidth = this._mainTextureDesiredSize.width;
  95086. var blurTextureHeight = this._mainTextureDesiredSize.height;
  95087. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95088. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95089. var textureType = 0;
  95090. if (this._engine.getCaps().textureHalfFloatRender) {
  95091. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95092. }
  95093. else {
  95094. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95095. }
  95096. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  95097. width: blurTextureWidth,
  95098. height: blurTextureHeight
  95099. }, this._scene, false, true, textureType);
  95100. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95101. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95102. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95103. this._blurTexture1.renderParticles = false;
  95104. this._blurTexture1.ignoreCameraViewport = true;
  95105. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  95106. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  95107. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  95108. width: blurTextureWidth2,
  95109. height: blurTextureHeight2
  95110. }, this._scene, false, true, textureType);
  95111. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95112. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95113. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95114. this._blurTexture2.renderParticles = false;
  95115. this._blurTexture2.ignoreCameraViewport = true;
  95116. this._textures = [this._blurTexture1, this._blurTexture2];
  95117. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95118. width: blurTextureWidth,
  95119. height: blurTextureHeight
  95120. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95121. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  95122. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  95123. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  95124. effect.setTexture("textureSampler", _this._mainTexture);
  95125. });
  95126. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95127. width: blurTextureWidth,
  95128. height: blurTextureHeight
  95129. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95130. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  95131. width: blurTextureWidth2,
  95132. height: blurTextureHeight2
  95133. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95134. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  95135. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  95136. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  95137. effect.setTexture("textureSampler", _this._blurTexture1);
  95138. });
  95139. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  95140. width: blurTextureWidth2,
  95141. height: blurTextureHeight2
  95142. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95143. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95144. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  95145. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  95146. this._mainTexture.samples = this._options.mainTextureSamples;
  95147. this._mainTexture.onAfterUnbindObservable.add(function () {
  95148. var internalTexture = _this._blurTexture1.getInternalTexture();
  95149. if (internalTexture) {
  95150. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  95151. internalTexture = _this._blurTexture2.getInternalTexture();
  95152. if (internalTexture) {
  95153. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  95154. }
  95155. }
  95156. });
  95157. // Prevent autoClear.
  95158. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95159. };
  95160. /**
  95161. * Checks for the readiness of the element composing the layer.
  95162. * @param subMesh the mesh to check for
  95163. * @param useInstances specify wether or not to use instances to render the mesh
  95164. * @param emissiveTexture the associated emissive texture used to generate the glow
  95165. * @return true if ready otherwise, false
  95166. */
  95167. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  95168. var material = subMesh.getMaterial();
  95169. var mesh = subMesh.getRenderingMesh();
  95170. if (!material || !mesh) {
  95171. return false;
  95172. }
  95173. var emissiveTexture = material.emissiveTexture;
  95174. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95175. };
  95176. /**
  95177. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95178. */
  95179. GlowLayer.prototype.needStencil = function () {
  95180. return false;
  95181. };
  95182. /**
  95183. * Implementation specific of rendering the generating effect on the main canvas.
  95184. * @param effect The effect used to render through
  95185. */
  95186. GlowLayer.prototype._internalRender = function (effect) {
  95187. // Texture
  95188. effect.setTexture("textureSampler", this._blurTexture1);
  95189. effect.setTexture("textureSampler2", this._blurTexture2);
  95190. effect.setFloat("offset", this._intensity);
  95191. // Cache
  95192. var engine = this._engine;
  95193. var previousStencilBuffer = engine.getStencilBuffer();
  95194. // Draw order
  95195. engine.setStencilBuffer(false);
  95196. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95197. // Draw order
  95198. engine.setStencilBuffer(previousStencilBuffer);
  95199. };
  95200. /**
  95201. * Sets the required values for both the emissive texture and and the main color.
  95202. */
  95203. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95204. var textureLevel = 1.0;
  95205. if (this.customEmissiveTextureSelector) {
  95206. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  95207. }
  95208. else {
  95209. if (material) {
  95210. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95211. if (this._emissiveTextureAndColor.texture) {
  95212. textureLevel = this._emissiveTextureAndColor.texture.level;
  95213. }
  95214. }
  95215. else {
  95216. this._emissiveTextureAndColor.texture = null;
  95217. }
  95218. }
  95219. if (this.customEmissiveColorSelector) {
  95220. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  95221. }
  95222. else {
  95223. if (material.emissiveColor) {
  95224. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  95225. }
  95226. else {
  95227. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95228. }
  95229. }
  95230. };
  95231. /**
  95232. * Returns true if the mesh should render, otherwise false.
  95233. * @param mesh The mesh to render
  95234. * @returns true if it should render otherwise false
  95235. */
  95236. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  95237. return this.hasMesh(mesh);
  95238. };
  95239. /**
  95240. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  95241. * @param mesh The mesh to exclude from the glow layer
  95242. */
  95243. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  95244. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  95245. this._excludedMeshes.push(mesh.uniqueId);
  95246. }
  95247. };
  95248. /**
  95249. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  95250. * @param mesh The mesh to remove
  95251. */
  95252. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  95253. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  95254. if (index !== -1) {
  95255. this._excludedMeshes.splice(index, 1);
  95256. }
  95257. };
  95258. /**
  95259. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  95260. * @param mesh The mesh to include in the glow layer
  95261. */
  95262. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  95263. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  95264. this._includedOnlyMeshes.push(mesh.uniqueId);
  95265. }
  95266. };
  95267. /**
  95268. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  95269. * @param mesh The mesh to remove
  95270. */
  95271. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  95272. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  95273. if (index !== -1) {
  95274. this._includedOnlyMeshes.splice(index, 1);
  95275. }
  95276. };
  95277. /**
  95278. * Determine if a given mesh will be used in the glow layer
  95279. * @param mesh The mesh to test
  95280. * @returns true if the mesh will be highlighted by the current glow layer
  95281. */
  95282. GlowLayer.prototype.hasMesh = function (mesh) {
  95283. // Included Mesh
  95284. if (this._includedOnlyMeshes.length) {
  95285. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  95286. }
  95287. ;
  95288. // Excluded Mesh
  95289. if (this._excludedMeshes.length) {
  95290. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  95291. }
  95292. ;
  95293. return true;
  95294. };
  95295. /**
  95296. * Free any resources and references associated to a mesh.
  95297. * Internal use
  95298. * @param mesh The mesh to free.
  95299. */
  95300. GlowLayer.prototype._disposeMesh = function (mesh) {
  95301. this.removeIncludedOnlyMesh(mesh);
  95302. this.removeExcludedMesh(mesh);
  95303. };
  95304. /**
  95305. * Gets the class name of the effect layer
  95306. * @returns the string with the class name of the effect layer
  95307. */
  95308. GlowLayer.prototype.getClassName = function () {
  95309. return "GlowLayer";
  95310. };
  95311. /**
  95312. * Serializes this glow layer
  95313. * @returns a serialized glow layer object
  95314. */
  95315. GlowLayer.prototype.serialize = function () {
  95316. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95317. serializationObject.customType = "BABYLON.GlowLayer";
  95318. var index;
  95319. // Included meshes
  95320. serializationObject.includedMeshes = [];
  95321. if (this._includedOnlyMeshes.length) {
  95322. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  95323. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  95324. if (mesh) {
  95325. serializationObject.includedMeshes.push(mesh.id);
  95326. }
  95327. }
  95328. }
  95329. // Excluded meshes
  95330. serializationObject.excludedMeshes = [];
  95331. if (this._excludedMeshes.length) {
  95332. for (index = 0; index < this._excludedMeshes.length; index++) {
  95333. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  95334. if (mesh) {
  95335. serializationObject.excludedMeshes.push(mesh.id);
  95336. }
  95337. }
  95338. }
  95339. return serializationObject;
  95340. };
  95341. /**
  95342. * Creates a Glow Layer from parsed glow layer data
  95343. * @param parsedGlowLayer defines glow layer data
  95344. * @param scene defines the current scene
  95345. * @param rootUrl defines the root URL containing the glow layer information
  95346. * @returns a parsed Glow Layer
  95347. */
  95348. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  95349. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  95350. var index;
  95351. // Excluded meshes
  95352. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  95353. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  95354. if (mesh) {
  95355. gl.addExcludedMesh(mesh);
  95356. }
  95357. }
  95358. // Included meshes
  95359. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  95360. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  95361. if (mesh) {
  95362. gl.addIncludedOnlyMesh(mesh);
  95363. }
  95364. }
  95365. return gl;
  95366. };
  95367. /**
  95368. * Effect Name of the layer.
  95369. */
  95370. GlowLayer.EffectName = "GlowLayer";
  95371. /**
  95372. * The default blur kernel size used for the glow.
  95373. */
  95374. GlowLayer.DefaultBlurKernelSize = 32;
  95375. /**
  95376. * The default texture size ratio used for the glow.
  95377. */
  95378. GlowLayer.DefaultTextureRatio = 0.5;
  95379. __decorate([
  95380. BABYLON.serialize()
  95381. ], GlowLayer.prototype, "blurKernelSize", null);
  95382. __decorate([
  95383. BABYLON.serialize()
  95384. ], GlowLayer.prototype, "intensity", null);
  95385. __decorate([
  95386. BABYLON.serialize("options")
  95387. ], GlowLayer.prototype, "_options", void 0);
  95388. return GlowLayer;
  95389. }(BABYLON.EffectLayer));
  95390. BABYLON.GlowLayer = GlowLayer;
  95391. })(BABYLON || (BABYLON = {}));
  95392. //# sourceMappingURL=babylon.glowLayer.js.map
  95393. var BABYLON;
  95394. (function (BABYLON) {
  95395. /**
  95396. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  95397. */
  95398. var AssetTaskState;
  95399. (function (AssetTaskState) {
  95400. /**
  95401. * Initialization
  95402. */
  95403. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  95404. /**
  95405. * Running
  95406. */
  95407. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  95408. /**
  95409. * Done
  95410. */
  95411. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  95412. /**
  95413. * Error
  95414. */
  95415. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  95416. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  95417. /**
  95418. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  95419. */
  95420. var AbstractAssetTask = /** @class */ (function () {
  95421. /**
  95422. * Creates a new {BABYLON.AssetsManager}
  95423. * @param name defines the name of the task
  95424. */
  95425. function AbstractAssetTask(
  95426. /**
  95427. * Task name
  95428. */ name) {
  95429. this.name = name;
  95430. this._isCompleted = false;
  95431. this._taskState = AssetTaskState.INIT;
  95432. }
  95433. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  95434. /**
  95435. * Get if the task is completed
  95436. */
  95437. get: function () {
  95438. return this._isCompleted;
  95439. },
  95440. enumerable: true,
  95441. configurable: true
  95442. });
  95443. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  95444. /**
  95445. * Gets the current state of the task
  95446. */
  95447. get: function () {
  95448. return this._taskState;
  95449. },
  95450. enumerable: true,
  95451. configurable: true
  95452. });
  95453. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  95454. /**
  95455. * Gets the current error object (if task is in error)
  95456. */
  95457. get: function () {
  95458. return this._errorObject;
  95459. },
  95460. enumerable: true,
  95461. configurable: true
  95462. });
  95463. /**
  95464. * Internal only
  95465. * @hidden
  95466. */
  95467. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95468. if (this._errorObject) {
  95469. return;
  95470. }
  95471. this._errorObject = {
  95472. message: message,
  95473. exception: exception
  95474. };
  95475. };
  95476. /**
  95477. * Execute the current task
  95478. * @param scene defines the scene where you want your assets to be loaded
  95479. * @param onSuccess is a callback called when the task is successfully executed
  95480. * @param onError is a callback called if an error occurs
  95481. */
  95482. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95483. var _this = this;
  95484. this._taskState = AssetTaskState.RUNNING;
  95485. this.runTask(scene, function () {
  95486. _this.onDoneCallback(onSuccess, onError);
  95487. }, function (msg, exception) {
  95488. _this.onErrorCallback(onError, msg, exception);
  95489. });
  95490. };
  95491. /**
  95492. * Execute the current task
  95493. * @param scene defines the scene where you want your assets to be loaded
  95494. * @param onSuccess is a callback called when the task is successfully executed
  95495. * @param onError is a callback called if an error occurs
  95496. */
  95497. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95498. throw new Error("runTask is not implemented");
  95499. };
  95500. /**
  95501. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95502. * This can be used with failed tasks that have the reason for failure fixed.
  95503. */
  95504. AbstractAssetTask.prototype.reset = function () {
  95505. this._taskState = AssetTaskState.INIT;
  95506. };
  95507. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95508. this._taskState = AssetTaskState.ERROR;
  95509. this._errorObject = {
  95510. message: message,
  95511. exception: exception
  95512. };
  95513. if (this.onError) {
  95514. this.onError(this, message, exception);
  95515. }
  95516. onError();
  95517. };
  95518. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95519. try {
  95520. this._taskState = AssetTaskState.DONE;
  95521. this._isCompleted = true;
  95522. if (this.onSuccess) {
  95523. this.onSuccess(this);
  95524. }
  95525. onSuccess();
  95526. }
  95527. catch (e) {
  95528. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95529. }
  95530. };
  95531. return AbstractAssetTask;
  95532. }());
  95533. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95534. /**
  95535. * Class used to share progress information about assets loading
  95536. */
  95537. var AssetsProgressEvent = /** @class */ (function () {
  95538. /**
  95539. * Creates a {BABYLON.AssetsProgressEvent}
  95540. * @param remainingCount defines the number of remaining tasks to process
  95541. * @param totalCount defines the total number of tasks
  95542. * @param task defines the task that was just processed
  95543. */
  95544. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95545. this.remainingCount = remainingCount;
  95546. this.totalCount = totalCount;
  95547. this.task = task;
  95548. }
  95549. return AssetsProgressEvent;
  95550. }());
  95551. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95552. /**
  95553. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95554. */
  95555. var MeshAssetTask = /** @class */ (function (_super) {
  95556. __extends(MeshAssetTask, _super);
  95557. /**
  95558. * Creates a new {BABYLON.MeshAssetTask}
  95559. * @param name defines the name of the task
  95560. * @param meshesNames defines the list of mesh's names you want to load
  95561. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95562. * @param sceneFilename defines the filename of the scene to load from
  95563. */
  95564. function MeshAssetTask(
  95565. /**
  95566. * Defines the name of the task
  95567. */
  95568. name,
  95569. /**
  95570. * Defines the list of mesh's names you want to load
  95571. */
  95572. meshesNames,
  95573. /**
  95574. * Defines the root url to use as a base to load your meshes and associated resources
  95575. */
  95576. rootUrl,
  95577. /**
  95578. * Defines the filename of the scene to load from
  95579. */
  95580. sceneFilename) {
  95581. var _this = _super.call(this, name) || this;
  95582. _this.name = name;
  95583. _this.meshesNames = meshesNames;
  95584. _this.rootUrl = rootUrl;
  95585. _this.sceneFilename = sceneFilename;
  95586. return _this;
  95587. }
  95588. /**
  95589. * Execute the current task
  95590. * @param scene defines the scene where you want your assets to be loaded
  95591. * @param onSuccess is a callback called when the task is successfully executed
  95592. * @param onError is a callback called if an error occurs
  95593. */
  95594. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95595. var _this = this;
  95596. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95597. _this.loadedMeshes = meshes;
  95598. _this.loadedParticleSystems = particleSystems;
  95599. _this.loadedSkeletons = skeletons;
  95600. onSuccess();
  95601. }, null, function (scene, message, exception) {
  95602. onError(message, exception);
  95603. });
  95604. };
  95605. return MeshAssetTask;
  95606. }(AbstractAssetTask));
  95607. BABYLON.MeshAssetTask = MeshAssetTask;
  95608. /**
  95609. * Define a task used by {BABYLON.AssetsManager} to load text content
  95610. */
  95611. var TextFileAssetTask = /** @class */ (function (_super) {
  95612. __extends(TextFileAssetTask, _super);
  95613. /**
  95614. * Creates a new TextFileAssetTask object
  95615. * @param name defines the name of the task
  95616. * @param url defines the location of the file to load
  95617. */
  95618. function TextFileAssetTask(
  95619. /**
  95620. * Defines the name of the task
  95621. */
  95622. name,
  95623. /**
  95624. * Defines the location of the file to load
  95625. */
  95626. url) {
  95627. var _this = _super.call(this, name) || this;
  95628. _this.name = name;
  95629. _this.url = url;
  95630. return _this;
  95631. }
  95632. /**
  95633. * Execute the current task
  95634. * @param scene defines the scene where you want your assets to be loaded
  95635. * @param onSuccess is a callback called when the task is successfully executed
  95636. * @param onError is a callback called if an error occurs
  95637. */
  95638. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95639. var _this = this;
  95640. scene._loadFile(this.url, function (data) {
  95641. _this.text = data;
  95642. onSuccess();
  95643. }, undefined, false, false, function (request, exception) {
  95644. if (request) {
  95645. onError(request.status + " " + request.statusText, exception);
  95646. }
  95647. });
  95648. };
  95649. return TextFileAssetTask;
  95650. }(AbstractAssetTask));
  95651. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95652. /**
  95653. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95654. */
  95655. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95656. __extends(BinaryFileAssetTask, _super);
  95657. /**
  95658. * Creates a new BinaryFileAssetTask object
  95659. * @param name defines the name of the new task
  95660. * @param url defines the location of the file to load
  95661. */
  95662. function BinaryFileAssetTask(
  95663. /**
  95664. * Defines the name of the task
  95665. */
  95666. name,
  95667. /**
  95668. * Defines the location of the file to load
  95669. */
  95670. url) {
  95671. var _this = _super.call(this, name) || this;
  95672. _this.name = name;
  95673. _this.url = url;
  95674. return _this;
  95675. }
  95676. /**
  95677. * Execute the current task
  95678. * @param scene defines the scene where you want your assets to be loaded
  95679. * @param onSuccess is a callback called when the task is successfully executed
  95680. * @param onError is a callback called if an error occurs
  95681. */
  95682. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95683. var _this = this;
  95684. scene._loadFile(this.url, function (data) {
  95685. _this.data = data;
  95686. onSuccess();
  95687. }, undefined, true, true, function (request, exception) {
  95688. if (request) {
  95689. onError(request.status + " " + request.statusText, exception);
  95690. }
  95691. });
  95692. };
  95693. return BinaryFileAssetTask;
  95694. }(AbstractAssetTask));
  95695. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95696. /**
  95697. * Define a task used by {BABYLON.AssetsManager} to load images
  95698. */
  95699. var ImageAssetTask = /** @class */ (function (_super) {
  95700. __extends(ImageAssetTask, _super);
  95701. /**
  95702. * Creates a new ImageAssetTask
  95703. * @param name defines the name of the task
  95704. * @param url defines the location of the image to load
  95705. */
  95706. function ImageAssetTask(
  95707. /**
  95708. * Defines the name of the task
  95709. */
  95710. name,
  95711. /**
  95712. * Defines the location of the image to load
  95713. */
  95714. url) {
  95715. var _this = _super.call(this, name) || this;
  95716. _this.name = name;
  95717. _this.url = url;
  95718. return _this;
  95719. }
  95720. /**
  95721. * Execute the current task
  95722. * @param scene defines the scene where you want your assets to be loaded
  95723. * @param onSuccess is a callback called when the task is successfully executed
  95724. * @param onError is a callback called if an error occurs
  95725. */
  95726. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95727. var _this = this;
  95728. var img = new Image();
  95729. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95730. img.onload = function () {
  95731. _this.image = img;
  95732. onSuccess();
  95733. };
  95734. img.onerror = function (err) {
  95735. onError("Error loading image", err);
  95736. };
  95737. img.src = this.url;
  95738. };
  95739. return ImageAssetTask;
  95740. }(AbstractAssetTask));
  95741. BABYLON.ImageAssetTask = ImageAssetTask;
  95742. /**
  95743. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95744. */
  95745. var TextureAssetTask = /** @class */ (function (_super) {
  95746. __extends(TextureAssetTask, _super);
  95747. /**
  95748. * Creates a new TextureAssetTask object
  95749. * @param name defines the name of the task
  95750. * @param url defines the location of the file to load
  95751. * @param noMipmap defines if mipmap should not be generated (default is false)
  95752. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95753. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95754. */
  95755. function TextureAssetTask(
  95756. /**
  95757. * Defines the name of the task
  95758. */
  95759. name,
  95760. /**
  95761. * Defines the location of the file to load
  95762. */
  95763. url,
  95764. /**
  95765. * Defines if mipmap should not be generated (default is false)
  95766. */
  95767. noMipmap,
  95768. /**
  95769. * Defines if texture must be inverted on Y axis (default is false)
  95770. */
  95771. invertY,
  95772. /**
  95773. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95774. */
  95775. samplingMode) {
  95776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95777. var _this = _super.call(this, name) || this;
  95778. _this.name = name;
  95779. _this.url = url;
  95780. _this.noMipmap = noMipmap;
  95781. _this.invertY = invertY;
  95782. _this.samplingMode = samplingMode;
  95783. return _this;
  95784. }
  95785. /**
  95786. * Execute the current task
  95787. * @param scene defines the scene where you want your assets to be loaded
  95788. * @param onSuccess is a callback called when the task is successfully executed
  95789. * @param onError is a callback called if an error occurs
  95790. */
  95791. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95792. var onload = function () {
  95793. onSuccess();
  95794. };
  95795. var onerror = function (message, exception) {
  95796. onError(message, exception);
  95797. };
  95798. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95799. };
  95800. return TextureAssetTask;
  95801. }(AbstractAssetTask));
  95802. BABYLON.TextureAssetTask = TextureAssetTask;
  95803. /**
  95804. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95805. */
  95806. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95807. __extends(CubeTextureAssetTask, _super);
  95808. /**
  95809. * Creates a new CubeTextureAssetTask
  95810. * @param name defines the name of the task
  95811. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95812. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95813. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95814. * @param files defines the explicit list of files (undefined by default)
  95815. */
  95816. function CubeTextureAssetTask(
  95817. /**
  95818. * Defines the name of the task
  95819. */
  95820. name,
  95821. /**
  95822. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95823. */
  95824. url,
  95825. /**
  95826. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95827. */
  95828. extensions,
  95829. /**
  95830. * Defines if mipmaps should not be generated (default is false)
  95831. */
  95832. noMipmap,
  95833. /**
  95834. * Defines the explicit list of files (undefined by default)
  95835. */
  95836. files) {
  95837. var _this = _super.call(this, name) || this;
  95838. _this.name = name;
  95839. _this.url = url;
  95840. _this.extensions = extensions;
  95841. _this.noMipmap = noMipmap;
  95842. _this.files = files;
  95843. return _this;
  95844. }
  95845. /**
  95846. * Execute the current task
  95847. * @param scene defines the scene where you want your assets to be loaded
  95848. * @param onSuccess is a callback called when the task is successfully executed
  95849. * @param onError is a callback called if an error occurs
  95850. */
  95851. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95852. var onload = function () {
  95853. onSuccess();
  95854. };
  95855. var onerror = function (message, exception) {
  95856. onError(message, exception);
  95857. };
  95858. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95859. };
  95860. return CubeTextureAssetTask;
  95861. }(AbstractAssetTask));
  95862. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95863. /**
  95864. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95865. */
  95866. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95867. __extends(HDRCubeTextureAssetTask, _super);
  95868. /**
  95869. * Creates a new HDRCubeTextureAssetTask object
  95870. * @param name defines the name of the task
  95871. * @param url defines the location of the file to load
  95872. * @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.
  95873. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95874. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95875. * @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)
  95876. * @param reserved Internal use only
  95877. */
  95878. function HDRCubeTextureAssetTask(
  95879. /**
  95880. * Defines the name of the task
  95881. */
  95882. name,
  95883. /**
  95884. * Defines the location of the file to load
  95885. */
  95886. url,
  95887. /**
  95888. * Defines the desired size (the more it increases the longer the generation will be)
  95889. */
  95890. size,
  95891. /**
  95892. * Defines if mipmaps should not be generated (default is false)
  95893. */
  95894. noMipmap,
  95895. /**
  95896. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95897. */
  95898. generateHarmonics,
  95899. /**
  95900. * 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)
  95901. */
  95902. gammaSpace,
  95903. /**
  95904. * Internal Use Only
  95905. */
  95906. reserved) {
  95907. if (noMipmap === void 0) { noMipmap = false; }
  95908. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95909. if (gammaSpace === void 0) { gammaSpace = false; }
  95910. if (reserved === void 0) { reserved = false; }
  95911. var _this = _super.call(this, name) || this;
  95912. _this.name = name;
  95913. _this.url = url;
  95914. _this.size = size;
  95915. _this.noMipmap = noMipmap;
  95916. _this.generateHarmonics = generateHarmonics;
  95917. _this.gammaSpace = gammaSpace;
  95918. _this.reserved = reserved;
  95919. return _this;
  95920. }
  95921. /**
  95922. * Execute the current task
  95923. * @param scene defines the scene where you want your assets to be loaded
  95924. * @param onSuccess is a callback called when the task is successfully executed
  95925. * @param onError is a callback called if an error occurs
  95926. */
  95927. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95928. var onload = function () {
  95929. onSuccess();
  95930. };
  95931. var onerror = function (message, exception) {
  95932. onError(message, exception);
  95933. };
  95934. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95935. };
  95936. return HDRCubeTextureAssetTask;
  95937. }(AbstractAssetTask));
  95938. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95939. /**
  95940. * This class can be used to easily import assets into a scene
  95941. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95942. */
  95943. var AssetsManager = /** @class */ (function () {
  95944. /**
  95945. * Creates a new AssetsManager
  95946. * @param scene defines the scene to work on
  95947. */
  95948. function AssetsManager(scene) {
  95949. this._isLoading = false;
  95950. this._tasks = new Array();
  95951. this._waitingTasksCount = 0;
  95952. this._totalTasksCount = 0;
  95953. /**
  95954. * Observable called when all tasks are processed
  95955. */
  95956. this.onTaskSuccessObservable = new BABYLON.Observable();
  95957. /**
  95958. * Observable called when a task had an error
  95959. */
  95960. this.onTaskErrorObservable = new BABYLON.Observable();
  95961. /**
  95962. * Observable called when a task is successful
  95963. */
  95964. this.onTasksDoneObservable = new BABYLON.Observable();
  95965. /**
  95966. * Observable called when a task is done (whatever the result is)
  95967. */
  95968. this.onProgressObservable = new BABYLON.Observable();
  95969. /**
  95970. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95971. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95972. */
  95973. this.useDefaultLoadingScreen = true;
  95974. this._scene = scene;
  95975. }
  95976. /**
  95977. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95978. * @param taskName defines the name of the new task
  95979. * @param meshesNames defines the name of meshes to load
  95980. * @param rootUrl defines the root url to use to locate files
  95981. * @param sceneFilename defines the filename of the scene file
  95982. * @returns a new {BABYLON.MeshAssetTask} object
  95983. */
  95984. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95985. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95986. this._tasks.push(task);
  95987. return task;
  95988. };
  95989. /**
  95990. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95991. * @param taskName defines the name of the new task
  95992. * @param url defines the url of the file to load
  95993. * @returns a new {BABYLON.TextFileAssetTask} object
  95994. */
  95995. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95996. var task = new TextFileAssetTask(taskName, url);
  95997. this._tasks.push(task);
  95998. return task;
  95999. };
  96000. /**
  96001. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  96002. * @param taskName defines the name of the new task
  96003. * @param url defines the url of the file to load
  96004. * @returns a new {BABYLON.BinaryFileAssetTask} object
  96005. */
  96006. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  96007. var task = new BinaryFileAssetTask(taskName, url);
  96008. this._tasks.push(task);
  96009. return task;
  96010. };
  96011. /**
  96012. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  96013. * @param taskName defines the name of the new task
  96014. * @param url defines the url of the file to load
  96015. * @returns a new {BABYLON.ImageAssetTask} object
  96016. */
  96017. AssetsManager.prototype.addImageTask = function (taskName, url) {
  96018. var task = new ImageAssetTask(taskName, url);
  96019. this._tasks.push(task);
  96020. return task;
  96021. };
  96022. /**
  96023. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  96024. * @param taskName defines the name of the new task
  96025. * @param url defines the url of the file to load
  96026. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96027. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  96028. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  96029. * @returns a new {BABYLON.TextureAssetTask} object
  96030. */
  96031. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  96032. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96033. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  96034. this._tasks.push(task);
  96035. return task;
  96036. };
  96037. /**
  96038. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  96039. * @param taskName defines the name of the new task
  96040. * @param url defines the url of the file to load
  96041. * @param extensions defines the extension to use to load the cube map (can be null)
  96042. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96043. * @param files defines the list of files to load (can be null)
  96044. * @returns a new {BABYLON.CubeTextureAssetTask} object
  96045. */
  96046. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  96047. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  96048. this._tasks.push(task);
  96049. return task;
  96050. };
  96051. /**
  96052. *
  96053. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  96054. * @param taskName defines the name of the new task
  96055. * @param url defines the url of the file to load
  96056. * @param size defines the size you want for the cubemap (can be null)
  96057. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  96058. * @param generateHarmonics defines if you want to automatically generate (true by default)
  96059. * @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)
  96060. * @param reserved Internal use only
  96061. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  96062. */
  96063. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  96064. if (noMipmap === void 0) { noMipmap = false; }
  96065. if (generateHarmonics === void 0) { generateHarmonics = true; }
  96066. if (gammaSpace === void 0) { gammaSpace = false; }
  96067. if (reserved === void 0) { reserved = false; }
  96068. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  96069. this._tasks.push(task);
  96070. return task;
  96071. };
  96072. /**
  96073. * Remove a task from the assets manager.
  96074. * @param task the task to remove
  96075. */
  96076. AssetsManager.prototype.removeTask = function (task) {
  96077. var index = this._tasks.indexOf(task);
  96078. if (index > -1) {
  96079. this._tasks.splice(index, 1);
  96080. }
  96081. };
  96082. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  96083. this._waitingTasksCount--;
  96084. try {
  96085. if (this.onProgress) {
  96086. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  96087. }
  96088. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  96089. }
  96090. catch (e) {
  96091. BABYLON.Tools.Error("Error running progress callbacks.");
  96092. console.log(e);
  96093. }
  96094. if (this._waitingTasksCount === 0) {
  96095. try {
  96096. if (this.onFinish) {
  96097. this.onFinish(this._tasks);
  96098. }
  96099. // Let's remove successfull tasks
  96100. var currentTasks = this._tasks.slice();
  96101. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  96102. var task = currentTasks_1[_i];
  96103. if (task.taskState === AssetTaskState.DONE) {
  96104. var index = this._tasks.indexOf(task);
  96105. if (index > -1) {
  96106. this._tasks.splice(index, 1);
  96107. }
  96108. }
  96109. }
  96110. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96111. }
  96112. catch (e) {
  96113. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  96114. console.log(e);
  96115. }
  96116. this._isLoading = false;
  96117. this._scene.getEngine().hideLoadingUI();
  96118. }
  96119. };
  96120. AssetsManager.prototype._runTask = function (task) {
  96121. var _this = this;
  96122. var done = function () {
  96123. try {
  96124. if (_this.onTaskSuccess) {
  96125. _this.onTaskSuccess(task);
  96126. }
  96127. _this.onTaskSuccessObservable.notifyObservers(task);
  96128. _this._decreaseWaitingTasksCount(task);
  96129. }
  96130. catch (e) {
  96131. error("Error executing task success callbacks", e);
  96132. }
  96133. };
  96134. var error = function (message, exception) {
  96135. task._setErrorObject(message, exception);
  96136. if (_this.onTaskError) {
  96137. _this.onTaskError(task);
  96138. }
  96139. _this.onTaskErrorObservable.notifyObservers(task);
  96140. _this._decreaseWaitingTasksCount(task);
  96141. };
  96142. task.run(this._scene, done, error);
  96143. };
  96144. /**
  96145. * Reset the {BABYLON.AssetsManager} and remove all tasks
  96146. * @return the current instance of the {BABYLON.AssetsManager}
  96147. */
  96148. AssetsManager.prototype.reset = function () {
  96149. this._isLoading = false;
  96150. this._tasks = new Array();
  96151. return this;
  96152. };
  96153. /**
  96154. * Start the loading process
  96155. * @return the current instance of the {BABYLON.AssetsManager}
  96156. */
  96157. AssetsManager.prototype.load = function () {
  96158. if (this._isLoading) {
  96159. return this;
  96160. }
  96161. this._isLoading = true;
  96162. this._waitingTasksCount = this._tasks.length;
  96163. this._totalTasksCount = this._tasks.length;
  96164. if (this._waitingTasksCount === 0) {
  96165. this._isLoading = false;
  96166. if (this.onFinish) {
  96167. this.onFinish(this._tasks);
  96168. }
  96169. this.onTasksDoneObservable.notifyObservers(this._tasks);
  96170. return this;
  96171. }
  96172. if (this.useDefaultLoadingScreen) {
  96173. this._scene.getEngine().displayLoadingUI();
  96174. }
  96175. for (var index = 0; index < this._tasks.length; index++) {
  96176. var task = this._tasks[index];
  96177. if (task.taskState === AssetTaskState.INIT) {
  96178. this._runTask(task);
  96179. }
  96180. }
  96181. return this;
  96182. };
  96183. return AssetsManager;
  96184. }());
  96185. BABYLON.AssetsManager = AssetsManager;
  96186. })(BABYLON || (BABYLON = {}));
  96187. //# sourceMappingURL=babylon.assetsManager.js.map
  96188. var BABYLON;
  96189. (function (BABYLON) {
  96190. var serializedGeometries = [];
  96191. var serializeGeometry = function (geometry, serializationGeometries) {
  96192. if (serializedGeometries[geometry.id]) {
  96193. return;
  96194. }
  96195. if (geometry.doNotSerialize) {
  96196. return;
  96197. }
  96198. if (geometry instanceof BABYLON.BoxGeometry) {
  96199. serializationGeometries.boxes.push(geometry.serialize());
  96200. }
  96201. else if (geometry instanceof BABYLON.SphereGeometry) {
  96202. serializationGeometries.spheres.push(geometry.serialize());
  96203. }
  96204. else if (geometry instanceof BABYLON.CylinderGeometry) {
  96205. serializationGeometries.cylinders.push(geometry.serialize());
  96206. }
  96207. else if (geometry instanceof BABYLON.TorusGeometry) {
  96208. serializationGeometries.toruses.push(geometry.serialize());
  96209. }
  96210. else if (geometry instanceof BABYLON.GroundGeometry) {
  96211. serializationGeometries.grounds.push(geometry.serialize());
  96212. }
  96213. else if (geometry instanceof BABYLON.Plane) {
  96214. serializationGeometries.planes.push(geometry.serialize());
  96215. }
  96216. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  96217. serializationGeometries.torusKnots.push(geometry.serialize());
  96218. }
  96219. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  96220. throw new Error("Unknown primitive type");
  96221. }
  96222. else {
  96223. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  96224. }
  96225. serializedGeometries[geometry.id] = true;
  96226. };
  96227. var serializeMesh = function (mesh, serializationScene) {
  96228. var serializationObject = {};
  96229. // Geometry
  96230. var geometry = mesh._geometry;
  96231. if (geometry) {
  96232. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  96233. // 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
  96234. serializeGeometry(geometry, serializationScene.geometries);
  96235. }
  96236. }
  96237. // Custom
  96238. if (mesh.serialize) {
  96239. mesh.serialize(serializationObject);
  96240. }
  96241. return serializationObject;
  96242. };
  96243. var finalizeSingleMesh = function (mesh, serializationObject) {
  96244. //only works if the mesh is already loaded
  96245. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96246. //serialize material
  96247. if (mesh.material) {
  96248. if (mesh.material instanceof BABYLON.MultiMaterial) {
  96249. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  96250. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96251. serializationObject.multiMaterials.push(mesh.material.serialize());
  96252. }
  96253. }
  96254. else {
  96255. serializationObject.materials = serializationObject.materials || [];
  96256. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  96257. serializationObject.materials.push(mesh.material.serialize());
  96258. }
  96259. }
  96260. }
  96261. //serialize geometry
  96262. var geometry = mesh._geometry;
  96263. if (geometry) {
  96264. if (!serializationObject.geometries) {
  96265. serializationObject.geometries = {};
  96266. serializationObject.geometries.boxes = [];
  96267. serializationObject.geometries.spheres = [];
  96268. serializationObject.geometries.cylinders = [];
  96269. serializationObject.geometries.toruses = [];
  96270. serializationObject.geometries.grounds = [];
  96271. serializationObject.geometries.planes = [];
  96272. serializationObject.geometries.torusKnots = [];
  96273. serializationObject.geometries.vertexData = [];
  96274. }
  96275. serializeGeometry(geometry, serializationObject.geometries);
  96276. }
  96277. // Skeletons
  96278. if (mesh.skeleton) {
  96279. serializationObject.skeletons = serializationObject.skeletons || [];
  96280. serializationObject.skeletons.push(mesh.skeleton.serialize());
  96281. }
  96282. //serialize the actual mesh
  96283. serializationObject.meshes = serializationObject.meshes || [];
  96284. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96285. }
  96286. };
  96287. var SceneSerializer = /** @class */ (function () {
  96288. function SceneSerializer() {
  96289. }
  96290. SceneSerializer.ClearCache = function () {
  96291. serializedGeometries = [];
  96292. };
  96293. SceneSerializer.Serialize = function (scene) {
  96294. var serializationObject = {};
  96295. SceneSerializer.ClearCache();
  96296. // Scene
  96297. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  96298. serializationObject.autoClear = scene.autoClear;
  96299. serializationObject.clearColor = scene.clearColor.asArray();
  96300. serializationObject.ambientColor = scene.ambientColor.asArray();
  96301. serializationObject.gravity = scene.gravity.asArray();
  96302. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  96303. serializationObject.workerCollisions = scene.workerCollisions;
  96304. // Fog
  96305. if (scene.fogMode && scene.fogMode !== 0) {
  96306. serializationObject.fogMode = scene.fogMode;
  96307. serializationObject.fogColor = scene.fogColor.asArray();
  96308. serializationObject.fogStart = scene.fogStart;
  96309. serializationObject.fogEnd = scene.fogEnd;
  96310. serializationObject.fogDensity = scene.fogDensity;
  96311. }
  96312. //Physics
  96313. if (scene.isPhysicsEnabled()) {
  96314. var physicEngine = scene.getPhysicsEngine();
  96315. if (physicEngine) {
  96316. serializationObject.physicsEnabled = true;
  96317. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  96318. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  96319. }
  96320. }
  96321. // Metadata
  96322. if (scene.metadata) {
  96323. serializationObject.metadata = scene.metadata;
  96324. }
  96325. // Morph targets
  96326. serializationObject.morphTargetManagers = [];
  96327. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  96328. var abstractMesh = _a[_i];
  96329. var manager = abstractMesh.morphTargetManager;
  96330. if (manager) {
  96331. serializationObject.morphTargetManagers.push(manager.serialize());
  96332. }
  96333. }
  96334. // Lights
  96335. serializationObject.lights = [];
  96336. var index;
  96337. var light;
  96338. for (index = 0; index < scene.lights.length; index++) {
  96339. light = scene.lights[index];
  96340. if (!light.doNotSerialize) {
  96341. serializationObject.lights.push(light.serialize());
  96342. }
  96343. }
  96344. // Cameras
  96345. serializationObject.cameras = [];
  96346. for (index = 0; index < scene.cameras.length; index++) {
  96347. var camera = scene.cameras[index];
  96348. if (!camera.doNotSerialize) {
  96349. serializationObject.cameras.push(camera.serialize());
  96350. }
  96351. }
  96352. if (scene.activeCamera) {
  96353. serializationObject.activeCameraID = scene.activeCamera.id;
  96354. }
  96355. // Animations
  96356. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  96357. // Materials
  96358. serializationObject.materials = [];
  96359. serializationObject.multiMaterials = [];
  96360. var material;
  96361. for (index = 0; index < scene.materials.length; index++) {
  96362. material = scene.materials[index];
  96363. if (!material.doNotSerialize) {
  96364. serializationObject.materials.push(material.serialize());
  96365. }
  96366. }
  96367. // MultiMaterials
  96368. serializationObject.multiMaterials = [];
  96369. for (index = 0; index < scene.multiMaterials.length; index++) {
  96370. var multiMaterial = scene.multiMaterials[index];
  96371. serializationObject.multiMaterials.push(multiMaterial.serialize());
  96372. }
  96373. // Environment texture
  96374. if (scene.environmentTexture) {
  96375. serializationObject.environmentTexture = scene.environmentTexture.name;
  96376. }
  96377. // Skeletons
  96378. serializationObject.skeletons = [];
  96379. for (index = 0; index < scene.skeletons.length; index++) {
  96380. var skeleton = scene.skeletons[index];
  96381. if (!skeleton.doNotSerialize) {
  96382. serializationObject.skeletons.push(skeleton.serialize());
  96383. }
  96384. }
  96385. // Transform nodes
  96386. serializationObject.transformNodes = [];
  96387. for (index = 0; index < scene.transformNodes.length; index++) {
  96388. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  96389. }
  96390. // Geometries
  96391. serializationObject.geometries = {};
  96392. serializationObject.geometries.boxes = [];
  96393. serializationObject.geometries.spheres = [];
  96394. serializationObject.geometries.cylinders = [];
  96395. serializationObject.geometries.toruses = [];
  96396. serializationObject.geometries.grounds = [];
  96397. serializationObject.geometries.planes = [];
  96398. serializationObject.geometries.torusKnots = [];
  96399. serializationObject.geometries.vertexData = [];
  96400. serializedGeometries = [];
  96401. var geometries = scene.getGeometries();
  96402. for (index = 0; index < geometries.length; index++) {
  96403. var geometry = geometries[index];
  96404. if (geometry.isReady()) {
  96405. serializeGeometry(geometry, serializationObject.geometries);
  96406. }
  96407. }
  96408. // Meshes
  96409. serializationObject.meshes = [];
  96410. for (index = 0; index < scene.meshes.length; index++) {
  96411. var abstractMesh = scene.meshes[index];
  96412. if (abstractMesh instanceof BABYLON.Mesh) {
  96413. var mesh = abstractMesh;
  96414. if (!mesh.doNotSerialize) {
  96415. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  96416. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  96417. }
  96418. }
  96419. }
  96420. }
  96421. // Particles Systems
  96422. serializationObject.particleSystems = [];
  96423. for (index = 0; index < scene.particleSystems.length; index++) {
  96424. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  96425. }
  96426. // Lens flares
  96427. serializationObject.lensFlareSystems = [];
  96428. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  96429. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  96430. }
  96431. // Shadows
  96432. serializationObject.shadowGenerators = [];
  96433. for (index = 0; index < scene.lights.length; index++) {
  96434. light = scene.lights[index];
  96435. var shadowGenerator = light.getShadowGenerator();
  96436. if (shadowGenerator) {
  96437. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  96438. }
  96439. }
  96440. // Action Manager
  96441. if (scene.actionManager) {
  96442. serializationObject.actions = scene.actionManager.serialize("scene");
  96443. }
  96444. // Audio
  96445. serializationObject.sounds = [];
  96446. for (index = 0; index < scene.soundTracks.length; index++) {
  96447. var soundtrack = scene.soundTracks[index];
  96448. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  96449. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  96450. }
  96451. }
  96452. // Effect layers
  96453. serializationObject.effectLayers = [];
  96454. for (index = 0; index < scene.effectLayers.length; index++) {
  96455. var layer = scene.effectLayers[index];
  96456. if (layer.serialize) {
  96457. serializationObject.effectLayers.push(layer.serialize());
  96458. }
  96459. }
  96460. return serializationObject;
  96461. };
  96462. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  96463. if (withParents === void 0) { withParents = false; }
  96464. if (withChildren === void 0) { withChildren = false; }
  96465. var serializationObject = {};
  96466. SceneSerializer.ClearCache();
  96467. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96468. if (withParents || withChildren) {
  96469. //deliberate for loop! not for each, appended should be processed as well.
  96470. for (var i = 0; i < toSerialize.length; ++i) {
  96471. if (withChildren) {
  96472. toSerialize[i].getDescendants().forEach(function (node) {
  96473. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96474. toSerialize.push(node);
  96475. }
  96476. });
  96477. }
  96478. //make sure the array doesn't contain the object already
  96479. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96480. toSerialize.push(toSerialize[i].parent);
  96481. }
  96482. }
  96483. }
  96484. toSerialize.forEach(function (mesh) {
  96485. finalizeSingleMesh(mesh, serializationObject);
  96486. });
  96487. return serializationObject;
  96488. };
  96489. return SceneSerializer;
  96490. }());
  96491. BABYLON.SceneSerializer = SceneSerializer;
  96492. })(BABYLON || (BABYLON = {}));
  96493. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96494. var BABYLON;
  96495. (function (BABYLON) {
  96496. var ReflectionProbe = /** @class */ (function () {
  96497. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96498. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96499. var _this = this;
  96500. this.name = name;
  96501. this._viewMatrix = BABYLON.Matrix.Identity();
  96502. this._target = BABYLON.Vector3.Zero();
  96503. this._add = BABYLON.Vector3.Zero();
  96504. this._invertYAxis = false;
  96505. this.position = BABYLON.Vector3.Zero();
  96506. this._scene = scene;
  96507. this._scene.reflectionProbes.push(this);
  96508. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96509. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96510. switch (faceIndex) {
  96511. case 0:
  96512. _this._add.copyFromFloats(1, 0, 0);
  96513. break;
  96514. case 1:
  96515. _this._add.copyFromFloats(-1, 0, 0);
  96516. break;
  96517. case 2:
  96518. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96519. break;
  96520. case 3:
  96521. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96522. break;
  96523. case 4:
  96524. _this._add.copyFromFloats(0, 0, 1);
  96525. break;
  96526. case 5:
  96527. _this._add.copyFromFloats(0, 0, -1);
  96528. break;
  96529. }
  96530. if (_this._attachedMesh) {
  96531. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96532. }
  96533. _this.position.addToRef(_this._add, _this._target);
  96534. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96535. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96536. scene._forcedViewPosition = _this.position;
  96537. });
  96538. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96539. scene._forcedViewPosition = null;
  96540. scene.updateTransformMatrix(true);
  96541. });
  96542. if (scene.activeCamera) {
  96543. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96544. }
  96545. }
  96546. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96547. get: function () {
  96548. return this._renderTargetTexture.samples;
  96549. },
  96550. set: function (value) {
  96551. this._renderTargetTexture.samples = value;
  96552. },
  96553. enumerable: true,
  96554. configurable: true
  96555. });
  96556. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96557. get: function () {
  96558. return this._renderTargetTexture.refreshRate;
  96559. },
  96560. set: function (value) {
  96561. this._renderTargetTexture.refreshRate = value;
  96562. },
  96563. enumerable: true,
  96564. configurable: true
  96565. });
  96566. ReflectionProbe.prototype.getScene = function () {
  96567. return this._scene;
  96568. };
  96569. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96570. get: function () {
  96571. return this._renderTargetTexture;
  96572. },
  96573. enumerable: true,
  96574. configurable: true
  96575. });
  96576. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96577. get: function () {
  96578. return this._renderTargetTexture.renderList;
  96579. },
  96580. enumerable: true,
  96581. configurable: true
  96582. });
  96583. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96584. this._attachedMesh = mesh;
  96585. };
  96586. /**
  96587. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96588. *
  96589. * @param renderingGroupId The rendering group id corresponding to its index
  96590. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96591. */
  96592. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96593. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96594. };
  96595. ReflectionProbe.prototype.dispose = function () {
  96596. var index = this._scene.reflectionProbes.indexOf(this);
  96597. if (index !== -1) {
  96598. // Remove from the scene if found
  96599. this._scene.reflectionProbes.splice(index, 1);
  96600. }
  96601. if (this._renderTargetTexture) {
  96602. this._renderTargetTexture.dispose();
  96603. this._renderTargetTexture = null;
  96604. }
  96605. };
  96606. return ReflectionProbe;
  96607. }());
  96608. BABYLON.ReflectionProbe = ReflectionProbe;
  96609. })(BABYLON || (BABYLON = {}));
  96610. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96611. var BABYLON;
  96612. (function (BABYLON) {
  96613. var Layer = /** @class */ (function () {
  96614. function Layer(name, imgUrl, scene, isBackground, color) {
  96615. this.name = name;
  96616. this.scale = new BABYLON.Vector2(1, 1);
  96617. this.offset = new BABYLON.Vector2(0, 0);
  96618. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96619. this.layerMask = 0x0FFFFFFF;
  96620. this._vertexBuffers = {};
  96621. // Events
  96622. /**
  96623. * An event triggered when the layer is disposed.
  96624. */
  96625. this.onDisposeObservable = new BABYLON.Observable();
  96626. /**
  96627. * An event triggered before rendering the scene
  96628. */
  96629. this.onBeforeRenderObservable = new BABYLON.Observable();
  96630. /**
  96631. * An event triggered after rendering the scene
  96632. */
  96633. this.onAfterRenderObservable = new BABYLON.Observable();
  96634. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96635. this.isBackground = isBackground === undefined ? true : isBackground;
  96636. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96637. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96638. this._scene.layers.push(this);
  96639. var engine = this._scene.getEngine();
  96640. // VBO
  96641. var vertices = [];
  96642. vertices.push(1, 1);
  96643. vertices.push(-1, 1);
  96644. vertices.push(-1, -1);
  96645. vertices.push(1, -1);
  96646. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96647. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96648. this._createIndexBuffer();
  96649. // Effects
  96650. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96651. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96652. }
  96653. Object.defineProperty(Layer.prototype, "onDispose", {
  96654. set: function (callback) {
  96655. if (this._onDisposeObserver) {
  96656. this.onDisposeObservable.remove(this._onDisposeObserver);
  96657. }
  96658. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96659. },
  96660. enumerable: true,
  96661. configurable: true
  96662. });
  96663. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96664. set: function (callback) {
  96665. if (this._onBeforeRenderObserver) {
  96666. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96667. }
  96668. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96669. },
  96670. enumerable: true,
  96671. configurable: true
  96672. });
  96673. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96674. set: function (callback) {
  96675. if (this._onAfterRenderObserver) {
  96676. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96677. }
  96678. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96679. },
  96680. enumerable: true,
  96681. configurable: true
  96682. });
  96683. Layer.prototype._createIndexBuffer = function () {
  96684. var engine = this._scene.getEngine();
  96685. // Indices
  96686. var indices = [];
  96687. indices.push(0);
  96688. indices.push(1);
  96689. indices.push(2);
  96690. indices.push(0);
  96691. indices.push(2);
  96692. indices.push(3);
  96693. this._indexBuffer = engine.createIndexBuffer(indices);
  96694. };
  96695. Layer.prototype._rebuild = function () {
  96696. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96697. if (vb) {
  96698. vb._rebuild();
  96699. }
  96700. this._createIndexBuffer();
  96701. };
  96702. Layer.prototype.render = function () {
  96703. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96704. // Check
  96705. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96706. return;
  96707. var engine = this._scene.getEngine();
  96708. this.onBeforeRenderObservable.notifyObservers(this);
  96709. // Render
  96710. engine.enableEffect(currentEffect);
  96711. engine.setState(false);
  96712. // Texture
  96713. currentEffect.setTexture("textureSampler", this.texture);
  96714. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96715. // Color
  96716. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96717. // Scale / offset
  96718. currentEffect.setVector2("offset", this.offset);
  96719. currentEffect.setVector2("scale", this.scale);
  96720. // VBOs
  96721. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96722. // Draw order
  96723. if (!this.alphaTest) {
  96724. engine.setAlphaMode(this.alphaBlendingMode);
  96725. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96726. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96727. }
  96728. else {
  96729. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96730. }
  96731. this.onAfterRenderObservable.notifyObservers(this);
  96732. };
  96733. Layer.prototype.dispose = function () {
  96734. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96735. if (vertexBuffer) {
  96736. vertexBuffer.dispose();
  96737. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96738. }
  96739. if (this._indexBuffer) {
  96740. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96741. this._indexBuffer = null;
  96742. }
  96743. if (this.texture) {
  96744. this.texture.dispose();
  96745. this.texture = null;
  96746. }
  96747. // Remove from scene
  96748. var index = this._scene.layers.indexOf(this);
  96749. this._scene.layers.splice(index, 1);
  96750. // Callback
  96751. this.onDisposeObservable.notifyObservers(this);
  96752. this.onDisposeObservable.clear();
  96753. this.onAfterRenderObservable.clear();
  96754. this.onBeforeRenderObservable.clear();
  96755. };
  96756. return Layer;
  96757. }());
  96758. BABYLON.Layer = Layer;
  96759. })(BABYLON || (BABYLON = {}));
  96760. //# sourceMappingURL=babylon.layer.js.map
  96761. var BABYLON;
  96762. (function (BABYLON) {
  96763. var TextureTools = /** @class */ (function () {
  96764. function TextureTools() {
  96765. }
  96766. /**
  96767. * Uses the GPU to create a copy texture rescaled at a given size
  96768. * @param texture Texture to copy from
  96769. * @param width Desired width
  96770. * @param height Desired height
  96771. * @return Generated texture
  96772. */
  96773. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96774. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96775. var scene = texture.getScene();
  96776. var engine = scene.getEngine();
  96777. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96778. rtt.wrapU = texture.wrapU;
  96779. rtt.wrapV = texture.wrapV;
  96780. rtt.uOffset = texture.uOffset;
  96781. rtt.vOffset = texture.vOffset;
  96782. rtt.uScale = texture.uScale;
  96783. rtt.vScale = texture.vScale;
  96784. rtt.uAng = texture.uAng;
  96785. rtt.vAng = texture.vAng;
  96786. rtt.wAng = texture.wAng;
  96787. rtt.coordinatesIndex = texture.coordinatesIndex;
  96788. rtt.level = texture.level;
  96789. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96790. rtt._texture.isReady = false;
  96791. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96792. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96793. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96794. passPostProcess.getEffect().executeWhenCompiled(function () {
  96795. passPostProcess.onApply = function (effect) {
  96796. effect.setTexture("textureSampler", texture);
  96797. };
  96798. var internalTexture = rtt.getInternalTexture();
  96799. if (internalTexture) {
  96800. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96801. engine.unBindFramebuffer(internalTexture);
  96802. rtt.disposeFramebufferObjects();
  96803. passPostProcess.dispose();
  96804. internalTexture.isReady = true;
  96805. }
  96806. });
  96807. return rtt;
  96808. };
  96809. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96810. if (!scene._environmentBRDFTexture) {
  96811. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96812. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96813. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96814. scene._environmentBRDFTexture = texture;
  96815. }
  96816. return scene._environmentBRDFTexture;
  96817. };
  96818. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iV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rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  96819. return TextureTools;
  96820. }());
  96821. BABYLON.TextureTools = TextureTools;
  96822. })(BABYLON || (BABYLON = {}));
  96823. //# sourceMappingURL=babylon.textureTools.js.map
  96824. var BABYLON;
  96825. (function (BABYLON) {
  96826. var FramingBehavior = /** @class */ (function () {
  96827. function FramingBehavior() {
  96828. this._mode = FramingBehavior.FitFrustumSidesMode;
  96829. this._radiusScale = 1.0;
  96830. this._positionScale = 0.5;
  96831. this._defaultElevation = 0.3;
  96832. this._elevationReturnTime = 1500;
  96833. this._elevationReturnWaitTime = 1000;
  96834. this._zoomStopsAnimation = false;
  96835. this._framingTime = 1500;
  96836. this._isPointerDown = false;
  96837. this._lastInteractionTime = -Infinity;
  96838. // Framing control
  96839. this._animatables = new Array();
  96840. this._betaIsAnimating = false;
  96841. }
  96842. Object.defineProperty(FramingBehavior.prototype, "name", {
  96843. get: function () {
  96844. return "Framing";
  96845. },
  96846. enumerable: true,
  96847. configurable: true
  96848. });
  96849. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96850. /**
  96851. * Gets current mode used by the behavior.
  96852. */
  96853. get: function () {
  96854. return this._mode;
  96855. },
  96856. /**
  96857. * Sets the current mode used by the behavior
  96858. */
  96859. set: function (mode) {
  96860. this._mode = mode;
  96861. },
  96862. enumerable: true,
  96863. configurable: true
  96864. });
  96865. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96866. /**
  96867. * Gets the scale applied to the radius
  96868. */
  96869. get: function () {
  96870. return this._radiusScale;
  96871. },
  96872. /**
  96873. * Sets the scale applied to the radius (1 by default)
  96874. */
  96875. set: function (radius) {
  96876. this._radiusScale = radius;
  96877. },
  96878. enumerable: true,
  96879. configurable: true
  96880. });
  96881. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96882. /**
  96883. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96884. */
  96885. get: function () {
  96886. return this._positionScale;
  96887. },
  96888. /**
  96889. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96890. */
  96891. set: function (scale) {
  96892. this._positionScale = scale;
  96893. },
  96894. enumerable: true,
  96895. configurable: true
  96896. });
  96897. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96898. /**
  96899. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96900. * behaviour is triggered, in radians.
  96901. */
  96902. get: function () {
  96903. return this._defaultElevation;
  96904. },
  96905. /**
  96906. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96907. * behaviour is triggered, in radians.
  96908. */
  96909. set: function (elevation) {
  96910. this._defaultElevation = elevation;
  96911. },
  96912. enumerable: true,
  96913. configurable: true
  96914. });
  96915. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96916. /**
  96917. * Gets the time (in milliseconds) taken to return to the default beta position.
  96918. * Negative value indicates camera should not return to default.
  96919. */
  96920. get: function () {
  96921. return this._elevationReturnTime;
  96922. },
  96923. /**
  96924. * Sets the time (in milliseconds) taken to return to the default beta position.
  96925. * Negative value indicates camera should not return to default.
  96926. */
  96927. set: function (speed) {
  96928. this._elevationReturnTime = speed;
  96929. },
  96930. enumerable: true,
  96931. configurable: true
  96932. });
  96933. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96934. /**
  96935. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96936. */
  96937. get: function () {
  96938. return this._elevationReturnWaitTime;
  96939. },
  96940. /**
  96941. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96942. */
  96943. set: function (time) {
  96944. this._elevationReturnWaitTime = time;
  96945. },
  96946. enumerable: true,
  96947. configurable: true
  96948. });
  96949. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96950. /**
  96951. * Gets the flag that indicates if user zooming should stop animation.
  96952. */
  96953. get: function () {
  96954. return this._zoomStopsAnimation;
  96955. },
  96956. /**
  96957. * Sets the flag that indicates if user zooming should stop animation.
  96958. */
  96959. set: function (flag) {
  96960. this._zoomStopsAnimation = flag;
  96961. },
  96962. enumerable: true,
  96963. configurable: true
  96964. });
  96965. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96966. /**
  96967. * Gets the transition time when framing the mesh, in milliseconds
  96968. */
  96969. get: function () {
  96970. return this._framingTime;
  96971. },
  96972. /**
  96973. * Sets the transition time when framing the mesh, in milliseconds
  96974. */
  96975. set: function (time) {
  96976. this._framingTime = time;
  96977. },
  96978. enumerable: true,
  96979. configurable: true
  96980. });
  96981. FramingBehavior.prototype.init = function () {
  96982. // Do notihng
  96983. };
  96984. FramingBehavior.prototype.attach = function (camera) {
  96985. var _this = this;
  96986. this._attachedCamera = camera;
  96987. var scene = this._attachedCamera.getScene();
  96988. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96989. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96990. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96991. _this._isPointerDown = true;
  96992. return;
  96993. }
  96994. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96995. _this._isPointerDown = false;
  96996. }
  96997. });
  96998. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96999. if (mesh) {
  97000. _this.zoomOnMesh(mesh);
  97001. }
  97002. });
  97003. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97004. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97005. _this._applyUserInteraction();
  97006. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  97007. // back to the default position after a given timeout
  97008. _this._maintainCameraAboveGround();
  97009. });
  97010. };
  97011. FramingBehavior.prototype.detach = function () {
  97012. if (!this._attachedCamera) {
  97013. return;
  97014. }
  97015. var scene = this._attachedCamera.getScene();
  97016. if (this._onPrePointerObservableObserver) {
  97017. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97018. }
  97019. if (this._onAfterCheckInputsObserver) {
  97020. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97021. }
  97022. if (this._onMeshTargetChangedObserver) {
  97023. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97024. }
  97025. this._attachedCamera = null;
  97026. };
  97027. /**
  97028. * Targets the given mesh and updates zoom level accordingly.
  97029. * @param mesh The mesh to target.
  97030. * @param radius Optional. If a cached radius position already exists, overrides default.
  97031. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97032. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97033. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97034. */
  97035. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  97036. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97037. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97038. mesh.computeWorldMatrix(true);
  97039. var boundingBox = mesh.getBoundingInfo().boundingBox;
  97040. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  97041. };
  97042. /**
  97043. * Targets the given mesh with its children and updates zoom level accordingly.
  97044. * @param mesh The mesh to target.
  97045. * @param radius Optional. If a cached radius position already exists, overrides default.
  97046. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97047. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97048. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97049. */
  97050. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  97051. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97052. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97053. mesh.computeWorldMatrix(true);
  97054. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  97055. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  97056. };
  97057. /**
  97058. * Targets the given meshes with their children and updates zoom level accordingly.
  97059. * @param meshes The mesh to target.
  97060. * @param radius Optional. If a cached radius position already exists, overrides default.
  97061. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97062. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97063. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97064. */
  97065. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  97066. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97067. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97068. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  97069. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  97070. for (var i = 0; i < meshes.length; i++) {
  97071. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  97072. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  97073. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  97074. }
  97075. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  97076. };
  97077. /**
  97078. * Targets the given mesh and updates zoom level accordingly.
  97079. * @param mesh The mesh to target.
  97080. * @param radius Optional. If a cached radius position already exists, overrides default.
  97081. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  97082. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  97083. * @param onAnimationEnd Callback triggered at the end of the framing animation
  97084. */
  97085. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  97086. var _this = this;
  97087. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  97088. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  97089. var zoomTarget;
  97090. if (!this._attachedCamera) {
  97091. return;
  97092. }
  97093. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  97094. var bottom = minimumWorld.y;
  97095. var top = maximumWorld.y;
  97096. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  97097. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  97098. if (focusOnOriginXZ) {
  97099. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  97100. }
  97101. else {
  97102. var centerWorld = minimumWorld.add(radiusWorld);
  97103. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  97104. }
  97105. if (!this._vectorTransition) {
  97106. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  97107. }
  97108. this._betaIsAnimating = true;
  97109. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  97110. if (animatable) {
  97111. this._animatables.push(animatable);
  97112. }
  97113. // sets the radius and lower radius bounds
  97114. // Small delta ensures camera is not always at lower zoom limit.
  97115. var radius = 0;
  97116. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  97117. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97118. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  97119. radius = position;
  97120. }
  97121. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97122. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  97123. if (this._attachedCamera.lowerRadiusLimit === null) {
  97124. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  97125. }
  97126. }
  97127. // Set sensibilities
  97128. var extend = maximumWorld.subtract(minimumWorld).length();
  97129. this._attachedCamera.panningSensibility = 5000 / extend;
  97130. this._attachedCamera.wheelPrecision = 100 / radius;
  97131. // transition to new radius
  97132. if (!this._radiusTransition) {
  97133. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97134. }
  97135. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  97136. _this.stopAllAnimations();
  97137. if (onAnimationEnd) {
  97138. onAnimationEnd();
  97139. }
  97140. if (_this._attachedCamera) {
  97141. _this._attachedCamera.storeState();
  97142. }
  97143. });
  97144. if (animatable) {
  97145. this._animatables.push(animatable);
  97146. }
  97147. };
  97148. /**
  97149. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  97150. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  97151. * frustum width.
  97152. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  97153. * to fully enclose the mesh in the viewing frustum.
  97154. */
  97155. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  97156. var size = maximumWorld.subtract(minimumWorld);
  97157. var boxVectorGlobalDiagonal = size.length();
  97158. var frustumSlope = this._getFrustumSlope();
  97159. // Formula for setting distance
  97160. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  97161. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  97162. // Horizon distance
  97163. var radius = radiusWithoutFraming * this._radiusScale;
  97164. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  97165. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  97166. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  97167. var camera = this._attachedCamera;
  97168. if (!camera) {
  97169. return 0;
  97170. }
  97171. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  97172. // Don't exceed the requested limit
  97173. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  97174. }
  97175. // Don't exceed the upper radius limit
  97176. if (camera.upperRadiusLimit) {
  97177. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  97178. }
  97179. return distance;
  97180. };
  97181. /**
  97182. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  97183. * is automatically returned to its default position (expected to be above ground plane).
  97184. */
  97185. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  97186. var _this = this;
  97187. if (this._elevationReturnTime < 0) {
  97188. return;
  97189. }
  97190. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  97191. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  97192. var limitBeta = Math.PI * 0.5;
  97193. // Bring the camera back up if below the ground plane
  97194. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  97195. this._betaIsAnimating = true;
  97196. //Transition to new position
  97197. this.stopAllAnimations();
  97198. if (!this._betaTransition) {
  97199. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  97200. }
  97201. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  97202. _this._clearAnimationLocks();
  97203. _this.stopAllAnimations();
  97204. });
  97205. if (animatabe) {
  97206. this._animatables.push(animatabe);
  97207. }
  97208. }
  97209. };
  97210. /**
  97211. * Returns the frustum slope based on the canvas ratio and camera FOV
  97212. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  97213. */
  97214. FramingBehavior.prototype._getFrustumSlope = function () {
  97215. // Calculate the viewport ratio
  97216. // Aspect Ratio is Height/Width.
  97217. var camera = this._attachedCamera;
  97218. if (!camera) {
  97219. return BABYLON.Vector2.Zero();
  97220. }
  97221. var engine = camera.getScene().getEngine();
  97222. var aspectRatio = engine.getAspectRatio(camera);
  97223. // Camera FOV is the vertical field of view (top-bottom) in radians.
  97224. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  97225. var frustumSlopeY = Math.tan(camera.fov / 2);
  97226. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  97227. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  97228. // along the forward vector.
  97229. var frustumSlopeX = frustumSlopeY * aspectRatio;
  97230. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  97231. };
  97232. /**
  97233. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  97234. */
  97235. FramingBehavior.prototype._clearAnimationLocks = function () {
  97236. this._betaIsAnimating = false;
  97237. };
  97238. /**
  97239. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97240. */
  97241. FramingBehavior.prototype._applyUserInteraction = function () {
  97242. if (this.isUserIsMoving) {
  97243. this._lastInteractionTime = BABYLON.Tools.Now;
  97244. this.stopAllAnimations();
  97245. this._clearAnimationLocks();
  97246. }
  97247. };
  97248. /**
  97249. * Stops and removes all animations that have been applied to the camera
  97250. */
  97251. FramingBehavior.prototype.stopAllAnimations = function () {
  97252. if (this._attachedCamera) {
  97253. this._attachedCamera.animations = [];
  97254. }
  97255. while (this._animatables.length) {
  97256. if (this._animatables[0]) {
  97257. this._animatables[0].onAnimationEnd = null;
  97258. this._animatables[0].stop();
  97259. }
  97260. this._animatables.shift();
  97261. }
  97262. };
  97263. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  97264. /**
  97265. * Gets a value indicating if the user is moving the camera
  97266. */
  97267. get: function () {
  97268. if (!this._attachedCamera) {
  97269. return false;
  97270. }
  97271. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97272. this._attachedCamera.inertialBetaOffset !== 0 ||
  97273. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97274. this._attachedCamera.inertialPanningX !== 0 ||
  97275. this._attachedCamera.inertialPanningY !== 0 ||
  97276. this._isPointerDown;
  97277. },
  97278. enumerable: true,
  97279. configurable: true
  97280. });
  97281. /**
  97282. * The easing function used by animations
  97283. */
  97284. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  97285. /**
  97286. * The easing mode used by animations
  97287. */
  97288. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  97289. // Statics
  97290. /**
  97291. * The camera can move all the way towards the mesh.
  97292. */
  97293. FramingBehavior.IgnoreBoundsSizeMode = 0;
  97294. /**
  97295. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  97296. */
  97297. FramingBehavior.FitFrustumSidesMode = 1;
  97298. return FramingBehavior;
  97299. }());
  97300. BABYLON.FramingBehavior = FramingBehavior;
  97301. })(BABYLON || (BABYLON = {}));
  97302. //# sourceMappingURL=babylon.framingBehavior.js.map
  97303. var BABYLON;
  97304. (function (BABYLON) {
  97305. /**
  97306. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  97307. */
  97308. var BouncingBehavior = /** @class */ (function () {
  97309. function BouncingBehavior() {
  97310. /**
  97311. * The duration of the animation, in milliseconds
  97312. */
  97313. this.transitionDuration = 450;
  97314. /**
  97315. * Length of the distance animated by the transition when lower radius is reached
  97316. */
  97317. this.lowerRadiusTransitionRange = 2;
  97318. /**
  97319. * Length of the distance animated by the transition when upper radius is reached
  97320. */
  97321. this.upperRadiusTransitionRange = -2;
  97322. this._autoTransitionRange = false;
  97323. // Animations
  97324. this._radiusIsAnimating = false;
  97325. this._radiusBounceTransition = null;
  97326. this._animatables = new Array();
  97327. }
  97328. Object.defineProperty(BouncingBehavior.prototype, "name", {
  97329. get: function () {
  97330. return "Bouncing";
  97331. },
  97332. enumerable: true,
  97333. configurable: true
  97334. });
  97335. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  97336. /**
  97337. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97338. */
  97339. get: function () {
  97340. return this._autoTransitionRange;
  97341. },
  97342. /**
  97343. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  97344. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  97345. */
  97346. set: function (value) {
  97347. var _this = this;
  97348. if (this._autoTransitionRange === value) {
  97349. return;
  97350. }
  97351. this._autoTransitionRange = value;
  97352. var camera = this._attachedCamera;
  97353. if (!camera) {
  97354. return;
  97355. }
  97356. if (value) {
  97357. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  97358. if (!mesh) {
  97359. return;
  97360. }
  97361. mesh.computeWorldMatrix(true);
  97362. var diagonal = mesh.getBoundingInfo().diagonalLength;
  97363. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  97364. _this.upperRadiusTransitionRange = diagonal * 0.05;
  97365. });
  97366. }
  97367. else if (this._onMeshTargetChangedObserver) {
  97368. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97369. }
  97370. },
  97371. enumerable: true,
  97372. configurable: true
  97373. });
  97374. BouncingBehavior.prototype.init = function () {
  97375. // Do notihng
  97376. };
  97377. BouncingBehavior.prototype.attach = function (camera) {
  97378. var _this = this;
  97379. this._attachedCamera = camera;
  97380. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97381. if (!_this._attachedCamera) {
  97382. return;
  97383. }
  97384. // Add the bounce animation to the lower radius limit
  97385. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  97386. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  97387. }
  97388. // Add the bounce animation to the upper radius limit
  97389. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  97390. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  97391. }
  97392. });
  97393. };
  97394. BouncingBehavior.prototype.detach = function () {
  97395. if (!this._attachedCamera) {
  97396. return;
  97397. }
  97398. if (this._onAfterCheckInputsObserver) {
  97399. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97400. }
  97401. if (this._onMeshTargetChangedObserver) {
  97402. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  97403. }
  97404. this._attachedCamera = null;
  97405. };
  97406. /**
  97407. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  97408. * @param radiusLimit The limit to check against.
  97409. * @return Bool to indicate if at limit.
  97410. */
  97411. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  97412. if (!this._attachedCamera) {
  97413. return false;
  97414. }
  97415. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  97416. return true;
  97417. }
  97418. return false;
  97419. };
  97420. /**
  97421. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  97422. * @param radiusDelta The delta by which to animate to. Can be negative.
  97423. */
  97424. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  97425. var _this = this;
  97426. if (!this._attachedCamera) {
  97427. return;
  97428. }
  97429. if (!this._radiusBounceTransition) {
  97430. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  97431. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  97432. }
  97433. // Prevent zoom until bounce has completed
  97434. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  97435. this._attachedCamera.wheelPrecision = Infinity;
  97436. this._attachedCamera.inertialRadiusOffset = 0;
  97437. // Animate to the radius limit
  97438. this.stopAllAnimations();
  97439. this._radiusIsAnimating = true;
  97440. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  97441. if (animatable) {
  97442. this._animatables.push(animatable);
  97443. }
  97444. };
  97445. /**
  97446. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  97447. */
  97448. BouncingBehavior.prototype._clearAnimationLocks = function () {
  97449. this._radiusIsAnimating = false;
  97450. if (this._attachedCamera) {
  97451. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  97452. }
  97453. };
  97454. /**
  97455. * Stops and removes all animations that have been applied to the camera
  97456. */
  97457. BouncingBehavior.prototype.stopAllAnimations = function () {
  97458. if (this._attachedCamera) {
  97459. this._attachedCamera.animations = [];
  97460. }
  97461. while (this._animatables.length) {
  97462. this._animatables[0].onAnimationEnd = null;
  97463. this._animatables[0].stop();
  97464. this._animatables.shift();
  97465. }
  97466. };
  97467. /**
  97468. * The easing function used by animations
  97469. */
  97470. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97471. /**
  97472. * The easing mode used by animations
  97473. */
  97474. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97475. return BouncingBehavior;
  97476. }());
  97477. BABYLON.BouncingBehavior = BouncingBehavior;
  97478. })(BABYLON || (BABYLON = {}));
  97479. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97480. var BABYLON;
  97481. (function (BABYLON) {
  97482. var AutoRotationBehavior = /** @class */ (function () {
  97483. function AutoRotationBehavior() {
  97484. this._zoomStopsAnimation = false;
  97485. this._idleRotationSpeed = 0.05;
  97486. this._idleRotationWaitTime = 2000;
  97487. this._idleRotationSpinupTime = 2000;
  97488. this._isPointerDown = false;
  97489. this._lastFrameTime = null;
  97490. this._lastInteractionTime = -Infinity;
  97491. this._cameraRotationSpeed = 0;
  97492. this._lastFrameRadius = 0;
  97493. }
  97494. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97495. get: function () {
  97496. return "AutoRotation";
  97497. },
  97498. enumerable: true,
  97499. configurable: true
  97500. });
  97501. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97502. /**
  97503. * Gets the flag that indicates if user zooming should stop animation.
  97504. */
  97505. get: function () {
  97506. return this._zoomStopsAnimation;
  97507. },
  97508. /**
  97509. * Sets the flag that indicates if user zooming should stop animation.
  97510. */
  97511. set: function (flag) {
  97512. this._zoomStopsAnimation = flag;
  97513. },
  97514. enumerable: true,
  97515. configurable: true
  97516. });
  97517. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97518. /**
  97519. * Gets the default speed at which the camera rotates around the model.
  97520. */
  97521. get: function () {
  97522. return this._idleRotationSpeed;
  97523. },
  97524. /**
  97525. * Sets the default speed at which the camera rotates around the model.
  97526. */
  97527. set: function (speed) {
  97528. this._idleRotationSpeed = speed;
  97529. },
  97530. enumerable: true,
  97531. configurable: true
  97532. });
  97533. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97534. /**
  97535. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97536. */
  97537. get: function () {
  97538. return this._idleRotationWaitTime;
  97539. },
  97540. /**
  97541. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97542. */
  97543. set: function (time) {
  97544. this._idleRotationWaitTime = time;
  97545. },
  97546. enumerable: true,
  97547. configurable: true
  97548. });
  97549. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97550. /**
  97551. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97552. */
  97553. get: function () {
  97554. return this._idleRotationSpinupTime;
  97555. },
  97556. /**
  97557. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97558. */
  97559. set: function (time) {
  97560. this._idleRotationSpinupTime = time;
  97561. },
  97562. enumerable: true,
  97563. configurable: true
  97564. });
  97565. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97566. /**
  97567. * Gets a value indicating if the camera is currently rotating because of this behavior
  97568. */
  97569. get: function () {
  97570. return Math.abs(this._cameraRotationSpeed) > 0;
  97571. },
  97572. enumerable: true,
  97573. configurable: true
  97574. });
  97575. AutoRotationBehavior.prototype.init = function () {
  97576. // Do notihng
  97577. };
  97578. AutoRotationBehavior.prototype.attach = function (camera) {
  97579. var _this = this;
  97580. this._attachedCamera = camera;
  97581. var scene = this._attachedCamera.getScene();
  97582. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97583. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97584. _this._isPointerDown = true;
  97585. return;
  97586. }
  97587. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97588. _this._isPointerDown = false;
  97589. }
  97590. });
  97591. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97592. var now = BABYLON.Tools.Now;
  97593. var dt = 0;
  97594. if (_this._lastFrameTime != null) {
  97595. dt = now - _this._lastFrameTime;
  97596. }
  97597. _this._lastFrameTime = now;
  97598. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97599. _this._applyUserInteraction();
  97600. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97601. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97602. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97603. // Step camera rotation by rotation speed
  97604. if (_this._attachedCamera) {
  97605. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97606. }
  97607. });
  97608. };
  97609. AutoRotationBehavior.prototype.detach = function () {
  97610. if (!this._attachedCamera) {
  97611. return;
  97612. }
  97613. var scene = this._attachedCamera.getScene();
  97614. if (this._onPrePointerObservableObserver) {
  97615. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97616. }
  97617. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97618. this._attachedCamera = null;
  97619. };
  97620. /**
  97621. * Returns true if user is scrolling.
  97622. * @return true if user is scrolling.
  97623. */
  97624. AutoRotationBehavior.prototype._userIsZooming = function () {
  97625. if (!this._attachedCamera) {
  97626. return false;
  97627. }
  97628. return this._attachedCamera.inertialRadiusOffset !== 0;
  97629. };
  97630. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97631. if (!this._attachedCamera) {
  97632. return false;
  97633. }
  97634. var zoomHasHitLimit = false;
  97635. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97636. zoomHasHitLimit = true;
  97637. }
  97638. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97639. this._lastFrameRadius = this._attachedCamera.radius;
  97640. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97641. };
  97642. /**
  97643. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97644. */
  97645. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97646. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97647. this._lastInteractionTime = BABYLON.Tools.Now;
  97648. }
  97649. };
  97650. // Tools
  97651. AutoRotationBehavior.prototype._userIsMoving = function () {
  97652. if (!this._attachedCamera) {
  97653. return false;
  97654. }
  97655. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97656. this._attachedCamera.inertialBetaOffset !== 0 ||
  97657. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97658. this._attachedCamera.inertialPanningX !== 0 ||
  97659. this._attachedCamera.inertialPanningY !== 0 ||
  97660. this._isPointerDown;
  97661. };
  97662. return AutoRotationBehavior;
  97663. }());
  97664. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97665. })(BABYLON || (BABYLON = {}));
  97666. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97667. var BABYLON;
  97668. (function (BABYLON) {
  97669. var NullEngineOptions = /** @class */ (function () {
  97670. function NullEngineOptions() {
  97671. this.renderWidth = 512;
  97672. this.renderHeight = 256;
  97673. this.textureSize = 512;
  97674. this.deterministicLockstep = false;
  97675. this.lockstepMaxSteps = 4;
  97676. }
  97677. return NullEngineOptions;
  97678. }());
  97679. BABYLON.NullEngineOptions = NullEngineOptions;
  97680. /**
  97681. * The null engine class provides support for headless version of babylon.js.
  97682. * This can be used in server side scenario or for testing purposes
  97683. */
  97684. var NullEngine = /** @class */ (function (_super) {
  97685. __extends(NullEngine, _super);
  97686. function NullEngine(options) {
  97687. if (options === void 0) { options = new NullEngineOptions(); }
  97688. var _this = _super.call(this, null) || this;
  97689. if (options.deterministicLockstep === undefined) {
  97690. options.deterministicLockstep = false;
  97691. }
  97692. if (options.lockstepMaxSteps === undefined) {
  97693. options.lockstepMaxSteps = 4;
  97694. }
  97695. _this._options = options;
  97696. // Init caps
  97697. // We consider we are on a webgl1 capable device
  97698. _this._caps = new BABYLON.EngineCapabilities();
  97699. _this._caps.maxTexturesImageUnits = 16;
  97700. _this._caps.maxVertexTextureImageUnits = 16;
  97701. _this._caps.maxTextureSize = 512;
  97702. _this._caps.maxCubemapTextureSize = 512;
  97703. _this._caps.maxRenderTextureSize = 512;
  97704. _this._caps.maxVertexAttribs = 16;
  97705. _this._caps.maxVaryingVectors = 16;
  97706. _this._caps.maxFragmentUniformVectors = 16;
  97707. _this._caps.maxVertexUniformVectors = 16;
  97708. // Extensions
  97709. _this._caps.standardDerivatives = false;
  97710. _this._caps.astc = null;
  97711. _this._caps.s3tc = null;
  97712. _this._caps.pvrtc = null;
  97713. _this._caps.etc1 = null;
  97714. _this._caps.etc2 = null;
  97715. _this._caps.textureAnisotropicFilterExtension = null;
  97716. _this._caps.maxAnisotropy = 0;
  97717. _this._caps.uintIndices = false;
  97718. _this._caps.fragmentDepthSupported = false;
  97719. _this._caps.highPrecisionShaderSupported = true;
  97720. _this._caps.colorBufferFloat = false;
  97721. _this._caps.textureFloat = false;
  97722. _this._caps.textureFloatLinearFiltering = false;
  97723. _this._caps.textureFloatRender = false;
  97724. _this._caps.textureHalfFloat = false;
  97725. _this._caps.textureHalfFloatLinearFiltering = false;
  97726. _this._caps.textureHalfFloatRender = false;
  97727. _this._caps.textureLOD = false;
  97728. _this._caps.drawBuffersExtension = false;
  97729. _this._caps.depthTextureExtension = false;
  97730. _this._caps.vertexArrayObject = false;
  97731. _this._caps.instancedArrays = false;
  97732. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97733. // Wrappers
  97734. if (typeof URL === "undefined") {
  97735. URL = {
  97736. createObjectURL: function () { },
  97737. revokeObjectURL: function () { }
  97738. };
  97739. }
  97740. if (typeof Blob === "undefined") {
  97741. Blob = function () { };
  97742. }
  97743. return _this;
  97744. }
  97745. NullEngine.prototype.isDeterministicLockStep = function () {
  97746. return this._options.deterministicLockstep;
  97747. };
  97748. NullEngine.prototype.getLockstepMaxSteps = function () {
  97749. return this._options.lockstepMaxSteps;
  97750. };
  97751. NullEngine.prototype.getHardwareScalingLevel = function () {
  97752. return 1.0;
  97753. };
  97754. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97755. return {
  97756. capacity: 0,
  97757. references: 1,
  97758. is32Bits: false
  97759. };
  97760. };
  97761. NullEngine.prototype.createIndexBuffer = function (indices) {
  97762. return {
  97763. capacity: 0,
  97764. references: 1,
  97765. is32Bits: false
  97766. };
  97767. };
  97768. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97769. if (stencil === void 0) { stencil = false; }
  97770. };
  97771. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97772. if (useScreen === void 0) { useScreen = false; }
  97773. if (!useScreen && this._currentRenderTarget) {
  97774. return this._currentRenderTarget.width;
  97775. }
  97776. return this._options.renderWidth;
  97777. };
  97778. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97779. if (useScreen === void 0) { useScreen = false; }
  97780. if (!useScreen && this._currentRenderTarget) {
  97781. return this._currentRenderTarget.height;
  97782. }
  97783. return this._options.renderHeight;
  97784. };
  97785. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97786. this._cachedViewport = viewport;
  97787. };
  97788. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97789. return {
  97790. transformFeedback: null,
  97791. __SPECTOR_rebuildProgram: null
  97792. };
  97793. };
  97794. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97795. return [];
  97796. };
  97797. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97798. return [];
  97799. };
  97800. NullEngine.prototype.bindSamplers = function (effect) {
  97801. this._currentEffect = null;
  97802. };
  97803. NullEngine.prototype.enableEffect = function (effect) {
  97804. this._currentEffect = effect;
  97805. if (effect.onBind) {
  97806. effect.onBind(effect);
  97807. }
  97808. effect.onBindObservable.notifyObservers(effect);
  97809. };
  97810. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97811. if (zOffset === void 0) { zOffset = 0; }
  97812. if (reverseSide === void 0) { reverseSide = false; }
  97813. };
  97814. NullEngine.prototype.setIntArray = function (uniform, array) {
  97815. };
  97816. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97817. };
  97818. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97819. };
  97820. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97821. };
  97822. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97823. };
  97824. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97825. };
  97826. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97827. };
  97828. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97829. };
  97830. NullEngine.prototype.setArray = function (uniform, array) {
  97831. };
  97832. NullEngine.prototype.setArray2 = function (uniform, array) {
  97833. };
  97834. NullEngine.prototype.setArray3 = function (uniform, array) {
  97835. };
  97836. NullEngine.prototype.setArray4 = function (uniform, array) {
  97837. };
  97838. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97839. };
  97840. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97841. };
  97842. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97843. };
  97844. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97845. };
  97846. NullEngine.prototype.setFloat = function (uniform, value) {
  97847. };
  97848. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97849. };
  97850. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97851. };
  97852. NullEngine.prototype.setBool = function (uniform, bool) {
  97853. };
  97854. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97855. };
  97856. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97857. };
  97858. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97859. };
  97860. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97861. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97862. if (this._alphaMode === mode) {
  97863. return;
  97864. }
  97865. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97866. if (!noDepthWriteChange) {
  97867. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97868. }
  97869. this._alphaMode = mode;
  97870. };
  97871. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97872. };
  97873. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97874. if (this.preventCacheWipeBetweenFrames) {
  97875. return;
  97876. }
  97877. this.resetTextureCache();
  97878. this._currentEffect = null;
  97879. if (bruteForce) {
  97880. this._currentProgram = null;
  97881. this._stencilState.reset();
  97882. this._depthCullingState.reset();
  97883. this._alphaState.reset();
  97884. }
  97885. this._cachedVertexBuffers = null;
  97886. this._cachedIndexBuffer = null;
  97887. this._cachedEffectForVertexBuffers = null;
  97888. };
  97889. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97890. };
  97891. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97892. };
  97893. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97894. };
  97895. NullEngine.prototype._createTexture = function () {
  97896. return {};
  97897. };
  97898. NullEngine.prototype._releaseTexture = function (texture) {
  97899. };
  97900. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97902. if (onLoad === void 0) { onLoad = null; }
  97903. if (onError === void 0) { onError = null; }
  97904. if (buffer === void 0) { buffer = null; }
  97905. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97906. var url = String(urlArg);
  97907. texture.url = url;
  97908. texture.generateMipMaps = !noMipmap;
  97909. texture.samplingMode = samplingMode;
  97910. texture.invertY = invertY;
  97911. texture.baseWidth = this._options.textureSize;
  97912. texture.baseHeight = this._options.textureSize;
  97913. texture.width = this._options.textureSize;
  97914. texture.height = this._options.textureSize;
  97915. if (format) {
  97916. texture.format = format;
  97917. }
  97918. texture.isReady = true;
  97919. if (onLoad) {
  97920. onLoad();
  97921. }
  97922. this._internalTexturesCache.push(texture);
  97923. return texture;
  97924. };
  97925. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97926. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97927. if (options !== undefined && typeof options === "object") {
  97928. fullOptions.generateMipMaps = options.generateMipMaps;
  97929. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97930. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97931. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97932. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97933. }
  97934. else {
  97935. fullOptions.generateMipMaps = options;
  97936. fullOptions.generateDepthBuffer = true;
  97937. fullOptions.generateStencilBuffer = false;
  97938. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97939. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97940. }
  97941. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97942. var width = size.width || size;
  97943. var height = size.height || size;
  97944. texture._depthStencilBuffer = {};
  97945. texture._framebuffer = {};
  97946. texture.baseWidth = width;
  97947. texture.baseHeight = height;
  97948. texture.width = width;
  97949. texture.height = height;
  97950. texture.isReady = true;
  97951. texture.samples = 1;
  97952. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97953. texture.samplingMode = fullOptions.samplingMode;
  97954. texture.type = fullOptions.type;
  97955. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97956. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97957. this._internalTexturesCache.push(texture);
  97958. return texture;
  97959. };
  97960. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97961. texture.samplingMode = samplingMode;
  97962. };
  97963. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97964. if (this._currentRenderTarget) {
  97965. this.unBindFramebuffer(this._currentRenderTarget);
  97966. }
  97967. this._currentRenderTarget = texture;
  97968. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97969. if (this._cachedViewport && !forceFullscreenViewport) {
  97970. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97971. }
  97972. };
  97973. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97974. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97975. this._currentRenderTarget = null;
  97976. if (onBeforeUnbind) {
  97977. if (texture._MSAAFramebuffer) {
  97978. this._currentFramebuffer = texture._framebuffer;
  97979. }
  97980. onBeforeUnbind();
  97981. }
  97982. this._currentFramebuffer = null;
  97983. };
  97984. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97985. var vbo = {
  97986. capacity: 1,
  97987. references: 1,
  97988. is32Bits: false
  97989. };
  97990. return vbo;
  97991. };
  97992. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97993. if (offset === void 0) { offset = 0; }
  97994. };
  97995. /**
  97996. * Updates a dynamic vertex buffer.
  97997. * @param vertexBuffer the vertex buffer to update
  97998. * @param data the data used to update the vertex buffer
  97999. * @param byteOffset the byte offset of the data (optional)
  98000. * @param byteLength the byte length of the data (optional)
  98001. */
  98002. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  98003. };
  98004. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  98005. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  98006. this._boundTexturesCache[this._activeChannel] = texture;
  98007. }
  98008. };
  98009. NullEngine.prototype._bindTexture = function (channel, texture) {
  98010. if (channel < 0) {
  98011. return;
  98012. }
  98013. this._bindTextureDirectly(0, texture);
  98014. };
  98015. NullEngine.prototype._releaseBuffer = function (buffer) {
  98016. buffer.references--;
  98017. if (buffer.references === 0) {
  98018. return true;
  98019. }
  98020. return false;
  98021. };
  98022. NullEngine.prototype.releaseEffects = function () {
  98023. };
  98024. return NullEngine;
  98025. }(BABYLON.Engine));
  98026. BABYLON.NullEngine = NullEngine;
  98027. })(BABYLON || (BABYLON = {}));
  98028. //# sourceMappingURL=babylon.nullEngine.js.map
  98029. var BABYLON;
  98030. (function (BABYLON) {
  98031. /**
  98032. * This class can be used to get instrumentation data from a Babylon engine
  98033. */
  98034. var EngineInstrumentation = /** @class */ (function () {
  98035. function EngineInstrumentation(engine) {
  98036. this.engine = engine;
  98037. this._captureGPUFrameTime = false;
  98038. this._gpuFrameTime = new BABYLON.PerfCounter();
  98039. this._captureShaderCompilationTime = false;
  98040. this._shaderCompilationTime = new BABYLON.PerfCounter();
  98041. // Observers
  98042. this._onBeginFrameObserver = null;
  98043. this._onEndFrameObserver = null;
  98044. this._onBeforeShaderCompilationObserver = null;
  98045. this._onAfterShaderCompilationObserver = null;
  98046. }
  98047. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  98048. // Properties
  98049. /**
  98050. * Gets the perf counter used for GPU frame time
  98051. */
  98052. get: function () {
  98053. return this._gpuFrameTime;
  98054. },
  98055. enumerable: true,
  98056. configurable: true
  98057. });
  98058. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  98059. /**
  98060. * Gets the GPU frame time capture status
  98061. */
  98062. get: function () {
  98063. return this._captureGPUFrameTime;
  98064. },
  98065. /**
  98066. * Enable or disable the GPU frame time capture
  98067. */
  98068. set: function (value) {
  98069. var _this = this;
  98070. if (value === this._captureGPUFrameTime) {
  98071. return;
  98072. }
  98073. this._captureGPUFrameTime = value;
  98074. if (value) {
  98075. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  98076. if (!_this._gpuFrameTimeToken) {
  98077. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  98078. }
  98079. });
  98080. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  98081. if (!_this._gpuFrameTimeToken) {
  98082. return;
  98083. }
  98084. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  98085. if (time > -1) {
  98086. _this._gpuFrameTimeToken = null;
  98087. _this._gpuFrameTime.fetchNewFrame();
  98088. _this._gpuFrameTime.addCount(time, true);
  98089. }
  98090. });
  98091. }
  98092. else {
  98093. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98094. this._onBeginFrameObserver = null;
  98095. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98096. this._onEndFrameObserver = null;
  98097. }
  98098. },
  98099. enumerable: true,
  98100. configurable: true
  98101. });
  98102. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  98103. /**
  98104. * Gets the perf counter used for shader compilation time
  98105. */
  98106. get: function () {
  98107. return this._shaderCompilationTime;
  98108. },
  98109. enumerable: true,
  98110. configurable: true
  98111. });
  98112. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  98113. /**
  98114. * Gets the shader compilation time capture status
  98115. */
  98116. get: function () {
  98117. return this._captureShaderCompilationTime;
  98118. },
  98119. /**
  98120. * Enable or disable the shader compilation time capture
  98121. */
  98122. set: function (value) {
  98123. var _this = this;
  98124. if (value === this._captureShaderCompilationTime) {
  98125. return;
  98126. }
  98127. this._captureShaderCompilationTime = value;
  98128. if (value) {
  98129. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  98130. _this._shaderCompilationTime.fetchNewFrame();
  98131. _this._shaderCompilationTime.beginMonitoring();
  98132. });
  98133. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  98134. _this._shaderCompilationTime.endMonitoring();
  98135. });
  98136. }
  98137. else {
  98138. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98139. this._onBeforeShaderCompilationObserver = null;
  98140. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98141. this._onAfterShaderCompilationObserver = null;
  98142. }
  98143. },
  98144. enumerable: true,
  98145. configurable: true
  98146. });
  98147. EngineInstrumentation.prototype.dispose = function () {
  98148. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  98149. this._onBeginFrameObserver = null;
  98150. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  98151. this._onEndFrameObserver = null;
  98152. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  98153. this._onBeforeShaderCompilationObserver = null;
  98154. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  98155. this._onAfterShaderCompilationObserver = null;
  98156. this.engine = null;
  98157. };
  98158. return EngineInstrumentation;
  98159. }());
  98160. BABYLON.EngineInstrumentation = EngineInstrumentation;
  98161. })(BABYLON || (BABYLON = {}));
  98162. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  98163. var BABYLON;
  98164. (function (BABYLON) {
  98165. /**
  98166. * This class can be used to get instrumentation data from a Babylon engine
  98167. */
  98168. var SceneInstrumentation = /** @class */ (function () {
  98169. function SceneInstrumentation(scene) {
  98170. var _this = this;
  98171. this.scene = scene;
  98172. this._captureActiveMeshesEvaluationTime = false;
  98173. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  98174. this._captureRenderTargetsRenderTime = false;
  98175. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  98176. this._captureFrameTime = false;
  98177. this._frameTime = new BABYLON.PerfCounter();
  98178. this._captureRenderTime = false;
  98179. this._renderTime = new BABYLON.PerfCounter();
  98180. this._captureInterFrameTime = false;
  98181. this._interFrameTime = new BABYLON.PerfCounter();
  98182. this._captureParticlesRenderTime = false;
  98183. this._particlesRenderTime = new BABYLON.PerfCounter();
  98184. this._captureSpritesRenderTime = false;
  98185. this._spritesRenderTime = new BABYLON.PerfCounter();
  98186. this._capturePhysicsTime = false;
  98187. this._physicsTime = new BABYLON.PerfCounter();
  98188. this._captureAnimationsTime = false;
  98189. this._animationsTime = new BABYLON.PerfCounter();
  98190. // Observers
  98191. this._onBeforeActiveMeshesEvaluationObserver = null;
  98192. this._onAfterActiveMeshesEvaluationObserver = null;
  98193. this._onBeforeRenderTargetsRenderObserver = null;
  98194. this._onAfterRenderTargetsRenderObserver = null;
  98195. this._onAfterRenderObserver = null;
  98196. this._onBeforeDrawPhaseObserver = null;
  98197. this._onAfterDrawPhaseObserver = null;
  98198. this._onBeforeAnimationsObserver = null;
  98199. this._onBeforeParticlesRenderingObserver = null;
  98200. this._onAfterParticlesRenderingObserver = null;
  98201. this._onBeforeSpritesRenderingObserver = null;
  98202. this._onAfterSpritesRenderingObserver = null;
  98203. this._onBeforePhysicsObserver = null;
  98204. this._onAfterPhysicsObserver = null;
  98205. this._onAfterAnimationsObserver = null;
  98206. // Before render
  98207. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  98208. if (_this._captureActiveMeshesEvaluationTime) {
  98209. _this._activeMeshesEvaluationTime.fetchNewFrame();
  98210. }
  98211. if (_this._captureRenderTargetsRenderTime) {
  98212. _this._renderTargetsRenderTime.fetchNewFrame();
  98213. }
  98214. if (_this._captureFrameTime) {
  98215. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  98216. _this._frameTime.beginMonitoring();
  98217. }
  98218. if (_this._captureInterFrameTime) {
  98219. _this._interFrameTime.endMonitoring();
  98220. }
  98221. if (_this._captureParticlesRenderTime) {
  98222. _this._particlesRenderTime.fetchNewFrame();
  98223. }
  98224. if (_this._captureSpritesRenderTime) {
  98225. _this._spritesRenderTime.fetchNewFrame();
  98226. }
  98227. if (_this._captureAnimationsTime) {
  98228. _this._animationsTime.beginMonitoring();
  98229. }
  98230. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  98231. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  98232. });
  98233. // After render
  98234. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  98235. if (_this._captureFrameTime) {
  98236. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  98237. _this._frameTime.endMonitoring();
  98238. }
  98239. if (_this._captureRenderTime) {
  98240. _this._renderTime.endMonitoring(false);
  98241. }
  98242. if (_this._captureInterFrameTime) {
  98243. _this._interFrameTime.beginMonitoring();
  98244. }
  98245. });
  98246. }
  98247. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  98248. // Properties
  98249. /**
  98250. * Gets the perf counter used for active meshes evaluation time
  98251. */
  98252. get: function () {
  98253. return this._activeMeshesEvaluationTime;
  98254. },
  98255. enumerable: true,
  98256. configurable: true
  98257. });
  98258. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  98259. /**
  98260. * Gets the active meshes evaluation time capture status
  98261. */
  98262. get: function () {
  98263. return this._captureActiveMeshesEvaluationTime;
  98264. },
  98265. /**
  98266. * Enable or disable the active meshes evaluation time capture
  98267. */
  98268. set: function (value) {
  98269. var _this = this;
  98270. if (value === this._captureActiveMeshesEvaluationTime) {
  98271. return;
  98272. }
  98273. this._captureActiveMeshesEvaluationTime = value;
  98274. if (value) {
  98275. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  98276. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  98277. _this._activeMeshesEvaluationTime.beginMonitoring();
  98278. });
  98279. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  98280. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  98281. _this._activeMeshesEvaluationTime.endMonitoring();
  98282. });
  98283. }
  98284. else {
  98285. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98286. this._onBeforeActiveMeshesEvaluationObserver = null;
  98287. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98288. this._onAfterActiveMeshesEvaluationObserver = null;
  98289. }
  98290. },
  98291. enumerable: true,
  98292. configurable: true
  98293. });
  98294. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  98295. /**
  98296. * Gets the perf counter used for render targets render time
  98297. */
  98298. get: function () {
  98299. return this._renderTargetsRenderTime;
  98300. },
  98301. enumerable: true,
  98302. configurable: true
  98303. });
  98304. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  98305. /**
  98306. * Gets the render targets render time capture status
  98307. */
  98308. get: function () {
  98309. return this._captureRenderTargetsRenderTime;
  98310. },
  98311. /**
  98312. * Enable or disable the render targets render time capture
  98313. */
  98314. set: function (value) {
  98315. var _this = this;
  98316. if (value === this._captureRenderTargetsRenderTime) {
  98317. return;
  98318. }
  98319. this._captureRenderTargetsRenderTime = value;
  98320. if (value) {
  98321. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  98322. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  98323. _this._renderTargetsRenderTime.beginMonitoring();
  98324. });
  98325. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  98326. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  98327. _this._renderTargetsRenderTime.endMonitoring(false);
  98328. });
  98329. }
  98330. else {
  98331. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98332. this._onBeforeRenderTargetsRenderObserver = null;
  98333. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98334. this._onAfterRenderTargetsRenderObserver = null;
  98335. }
  98336. },
  98337. enumerable: true,
  98338. configurable: true
  98339. });
  98340. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  98341. /**
  98342. * Gets the perf counter used for particles render time
  98343. */
  98344. get: function () {
  98345. return this._particlesRenderTime;
  98346. },
  98347. enumerable: true,
  98348. configurable: true
  98349. });
  98350. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  98351. /**
  98352. * Gets the particles render time capture status
  98353. */
  98354. get: function () {
  98355. return this._captureParticlesRenderTime;
  98356. },
  98357. /**
  98358. * Enable or disable the particles render time capture
  98359. */
  98360. set: function (value) {
  98361. var _this = this;
  98362. if (value === this._captureParticlesRenderTime) {
  98363. return;
  98364. }
  98365. this._captureParticlesRenderTime = value;
  98366. if (value) {
  98367. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  98368. BABYLON.Tools.StartPerformanceCounter("Particles");
  98369. _this._particlesRenderTime.beginMonitoring();
  98370. });
  98371. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  98372. BABYLON.Tools.EndPerformanceCounter("Particles");
  98373. _this._particlesRenderTime.endMonitoring(false);
  98374. });
  98375. }
  98376. else {
  98377. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98378. this._onBeforeParticlesRenderingObserver = null;
  98379. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98380. this._onAfterParticlesRenderingObserver = null;
  98381. }
  98382. },
  98383. enumerable: true,
  98384. configurable: true
  98385. });
  98386. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  98387. /**
  98388. * Gets the perf counter used for sprites render time
  98389. */
  98390. get: function () {
  98391. return this._spritesRenderTime;
  98392. },
  98393. enumerable: true,
  98394. configurable: true
  98395. });
  98396. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  98397. /**
  98398. * Gets the sprites render time capture status
  98399. */
  98400. get: function () {
  98401. return this._captureSpritesRenderTime;
  98402. },
  98403. /**
  98404. * Enable or disable the sprites render time capture
  98405. */
  98406. set: function (value) {
  98407. var _this = this;
  98408. if (value === this._captureSpritesRenderTime) {
  98409. return;
  98410. }
  98411. this._captureSpritesRenderTime = value;
  98412. if (value) {
  98413. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  98414. BABYLON.Tools.StartPerformanceCounter("Sprites");
  98415. _this._spritesRenderTime.beginMonitoring();
  98416. });
  98417. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  98418. BABYLON.Tools.EndPerformanceCounter("Sprites");
  98419. _this._spritesRenderTime.endMonitoring(false);
  98420. });
  98421. }
  98422. else {
  98423. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98424. this._onBeforeSpritesRenderingObserver = null;
  98425. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98426. this._onAfterSpritesRenderingObserver = null;
  98427. }
  98428. },
  98429. enumerable: true,
  98430. configurable: true
  98431. });
  98432. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  98433. /**
  98434. * Gets the perf counter used for physics time
  98435. */
  98436. get: function () {
  98437. return this._physicsTime;
  98438. },
  98439. enumerable: true,
  98440. configurable: true
  98441. });
  98442. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  98443. /**
  98444. * Gets the physics time capture status
  98445. */
  98446. get: function () {
  98447. return this._capturePhysicsTime;
  98448. },
  98449. /**
  98450. * Enable or disable the physics time capture
  98451. */
  98452. set: function (value) {
  98453. var _this = this;
  98454. if (value === this._capturePhysicsTime) {
  98455. return;
  98456. }
  98457. this._capturePhysicsTime = value;
  98458. if (value) {
  98459. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  98460. BABYLON.Tools.StartPerformanceCounter("Physics");
  98461. _this._physicsTime.beginMonitoring();
  98462. });
  98463. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  98464. BABYLON.Tools.EndPerformanceCounter("Physics");
  98465. _this._physicsTime.endMonitoring();
  98466. });
  98467. }
  98468. else {
  98469. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98470. this._onBeforePhysicsObserver = null;
  98471. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98472. this._onAfterPhysicsObserver = null;
  98473. }
  98474. },
  98475. enumerable: true,
  98476. configurable: true
  98477. });
  98478. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98479. /**
  98480. * Gets the perf counter used for animations time
  98481. */
  98482. get: function () {
  98483. return this._animationsTime;
  98484. },
  98485. enumerable: true,
  98486. configurable: true
  98487. });
  98488. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98489. /**
  98490. * Gets the animations time capture status
  98491. */
  98492. get: function () {
  98493. return this._captureAnimationsTime;
  98494. },
  98495. /**
  98496. * Enable or disable the animations time capture
  98497. */
  98498. set: function (value) {
  98499. var _this = this;
  98500. if (value === this._captureAnimationsTime) {
  98501. return;
  98502. }
  98503. this._captureAnimationsTime = value;
  98504. if (value) {
  98505. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98506. _this._animationsTime.endMonitoring();
  98507. });
  98508. }
  98509. else {
  98510. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98511. this._onAfterAnimationsObserver = null;
  98512. }
  98513. },
  98514. enumerable: true,
  98515. configurable: true
  98516. });
  98517. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98518. /**
  98519. * Gets the perf counter used for frame time capture
  98520. */
  98521. get: function () {
  98522. return this._frameTime;
  98523. },
  98524. enumerable: true,
  98525. configurable: true
  98526. });
  98527. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98528. /**
  98529. * Gets the frame time capture status
  98530. */
  98531. get: function () {
  98532. return this._captureFrameTime;
  98533. },
  98534. /**
  98535. * Enable or disable the frame time capture
  98536. */
  98537. set: function (value) {
  98538. this._captureFrameTime = value;
  98539. },
  98540. enumerable: true,
  98541. configurable: true
  98542. });
  98543. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98544. /**
  98545. * Gets the perf counter used for inter-frames time capture
  98546. */
  98547. get: function () {
  98548. return this._interFrameTime;
  98549. },
  98550. enumerable: true,
  98551. configurable: true
  98552. });
  98553. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98554. /**
  98555. * Gets the inter-frames time capture status
  98556. */
  98557. get: function () {
  98558. return this._captureInterFrameTime;
  98559. },
  98560. /**
  98561. * Enable or disable the inter-frames time capture
  98562. */
  98563. set: function (value) {
  98564. this._captureInterFrameTime = value;
  98565. },
  98566. enumerable: true,
  98567. configurable: true
  98568. });
  98569. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98570. /**
  98571. * Gets the perf counter used for render time capture
  98572. */
  98573. get: function () {
  98574. return this._renderTime;
  98575. },
  98576. enumerable: true,
  98577. configurable: true
  98578. });
  98579. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98580. /**
  98581. * Gets the render time capture status
  98582. */
  98583. get: function () {
  98584. return this._captureRenderTime;
  98585. },
  98586. /**
  98587. * Enable or disable the render time capture
  98588. */
  98589. set: function (value) {
  98590. var _this = this;
  98591. if (value === this._captureRenderTime) {
  98592. return;
  98593. }
  98594. this._captureRenderTime = value;
  98595. if (value) {
  98596. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98597. _this._renderTime.beginMonitoring();
  98598. BABYLON.Tools.StartPerformanceCounter("Main render");
  98599. });
  98600. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98601. _this._renderTime.endMonitoring(false);
  98602. BABYLON.Tools.EndPerformanceCounter("Main render");
  98603. });
  98604. }
  98605. else {
  98606. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98607. this._onBeforeDrawPhaseObserver = null;
  98608. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98609. this._onAfterDrawPhaseObserver = null;
  98610. }
  98611. },
  98612. enumerable: true,
  98613. configurable: true
  98614. });
  98615. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98616. /**
  98617. * Gets the perf counter used for draw calls
  98618. */
  98619. get: function () {
  98620. return this.scene.getEngine()._drawCalls;
  98621. },
  98622. enumerable: true,
  98623. configurable: true
  98624. });
  98625. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98626. /**
  98627. * Gets the perf counter used for texture collisions
  98628. */
  98629. get: function () {
  98630. return this.scene.getEngine()._textureCollisions;
  98631. },
  98632. enumerable: true,
  98633. configurable: true
  98634. });
  98635. SceneInstrumentation.prototype.dispose = function () {
  98636. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98637. this._onAfterRenderObserver = null;
  98638. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98639. this._onBeforeActiveMeshesEvaluationObserver = null;
  98640. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98641. this._onAfterActiveMeshesEvaluationObserver = null;
  98642. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98643. this._onBeforeRenderTargetsRenderObserver = null;
  98644. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98645. this._onAfterRenderTargetsRenderObserver = null;
  98646. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98647. this._onBeforeAnimationsObserver = null;
  98648. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98649. this._onBeforeParticlesRenderingObserver = null;
  98650. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98651. this._onAfterParticlesRenderingObserver = null;
  98652. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98653. this._onBeforeSpritesRenderingObserver = null;
  98654. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98655. this._onAfterSpritesRenderingObserver = null;
  98656. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98657. this._onBeforeDrawPhaseObserver = null;
  98658. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98659. this._onAfterDrawPhaseObserver = null;
  98660. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98661. this._onBeforePhysicsObserver = null;
  98662. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98663. this._onAfterPhysicsObserver = null;
  98664. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98665. this._onAfterAnimationsObserver = null;
  98666. this.scene = null;
  98667. };
  98668. return SceneInstrumentation;
  98669. }());
  98670. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98671. })(BABYLON || (BABYLON = {}));
  98672. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98673. var BABYLON;
  98674. (function (BABYLON) {
  98675. /**
  98676. * @hidden
  98677. **/
  98678. var _TimeToken = /** @class */ (function () {
  98679. function _TimeToken() {
  98680. this._timeElapsedQueryEnded = false;
  98681. }
  98682. return _TimeToken;
  98683. }());
  98684. BABYLON._TimeToken = _TimeToken;
  98685. })(BABYLON || (BABYLON = {}));
  98686. //# sourceMappingURL=babylon.timeToken.js.map
  98687. var BABYLON;
  98688. (function (BABYLON) {
  98689. /**
  98690. * Background material defines definition.
  98691. * @hidden Mainly internal Use
  98692. */
  98693. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98694. __extends(BackgroundMaterialDefines, _super);
  98695. /**
  98696. * Constructor of the defines.
  98697. */
  98698. function BackgroundMaterialDefines() {
  98699. var _this = _super.call(this) || this;
  98700. /**
  98701. * True if the diffuse texture is in use.
  98702. */
  98703. _this.DIFFUSE = false;
  98704. /**
  98705. * The direct UV channel to use.
  98706. */
  98707. _this.DIFFUSEDIRECTUV = 0;
  98708. /**
  98709. * True if the diffuse texture is in gamma space.
  98710. */
  98711. _this.GAMMADIFFUSE = false;
  98712. /**
  98713. * True if the diffuse texture has opacity in the alpha channel.
  98714. */
  98715. _this.DIFFUSEHASALPHA = false;
  98716. /**
  98717. * True if you want the material to fade to transparent at grazing angle.
  98718. */
  98719. _this.OPACITYFRESNEL = false;
  98720. /**
  98721. * True if an extra blur needs to be added in the reflection.
  98722. */
  98723. _this.REFLECTIONBLUR = false;
  98724. /**
  98725. * True if you want the material to fade to reflection at grazing angle.
  98726. */
  98727. _this.REFLECTIONFRESNEL = false;
  98728. /**
  98729. * True if you want the material to falloff as far as you move away from the scene center.
  98730. */
  98731. _this.REFLECTIONFALLOFF = false;
  98732. /**
  98733. * False if the current Webgl implementation does not support the texture lod extension.
  98734. */
  98735. _this.TEXTURELODSUPPORT = false;
  98736. /**
  98737. * True to ensure the data are premultiplied.
  98738. */
  98739. _this.PREMULTIPLYALPHA = false;
  98740. /**
  98741. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98742. */
  98743. _this.USERGBCOLOR = false;
  98744. /**
  98745. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98746. * stays aligned with the desired configuration.
  98747. */
  98748. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98749. /**
  98750. * True to add noise in order to reduce the banding effect.
  98751. */
  98752. _this.NOISE = false;
  98753. /**
  98754. * is the reflection texture in BGR color scheme?
  98755. * Mainly used to solve a bug in ios10 video tag
  98756. */
  98757. _this.REFLECTIONBGR = false;
  98758. _this.IMAGEPROCESSING = false;
  98759. _this.VIGNETTE = false;
  98760. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98761. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98762. _this.TONEMAPPING = false;
  98763. _this.CONTRAST = false;
  98764. _this.COLORCURVES = false;
  98765. _this.COLORGRADING = false;
  98766. _this.COLORGRADING3D = false;
  98767. _this.SAMPLER3DGREENDEPTH = false;
  98768. _this.SAMPLER3DBGRMAP = false;
  98769. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98770. _this.EXPOSURE = false;
  98771. // Reflection.
  98772. _this.REFLECTION = false;
  98773. _this.REFLECTIONMAP_3D = false;
  98774. _this.REFLECTIONMAP_SPHERICAL = false;
  98775. _this.REFLECTIONMAP_PLANAR = false;
  98776. _this.REFLECTIONMAP_CUBIC = false;
  98777. _this.REFLECTIONMAP_PROJECTION = false;
  98778. _this.REFLECTIONMAP_SKYBOX = false;
  98779. _this.REFLECTIONMAP_EXPLICIT = false;
  98780. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98781. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98782. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98783. _this.INVERTCUBICMAP = false;
  98784. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98785. _this.LODINREFLECTIONALPHA = false;
  98786. _this.GAMMAREFLECTION = false;
  98787. _this.RGBDREFLECTION = false;
  98788. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98789. // Default BJS.
  98790. _this.MAINUV1 = false;
  98791. _this.MAINUV2 = false;
  98792. _this.UV1 = false;
  98793. _this.UV2 = false;
  98794. _this.CLIPPLANE = false;
  98795. _this.POINTSIZE = false;
  98796. _this.FOG = false;
  98797. _this.NORMAL = false;
  98798. _this.NUM_BONE_INFLUENCERS = 0;
  98799. _this.BonesPerMesh = 0;
  98800. _this.INSTANCES = false;
  98801. _this.SHADOWFLOAT = false;
  98802. _this.rebuild();
  98803. return _this;
  98804. }
  98805. return BackgroundMaterialDefines;
  98806. }(BABYLON.MaterialDefines));
  98807. /**
  98808. * Background material used to create an efficient environement around your scene.
  98809. */
  98810. var BackgroundMaterial = /** @class */ (function (_super) {
  98811. __extends(BackgroundMaterial, _super);
  98812. /**
  98813. * Instantiates a Background Material in the given scene
  98814. * @param name The friendly name of the material
  98815. * @param scene The scene to add the material to
  98816. */
  98817. function BackgroundMaterial(name, scene) {
  98818. var _this = _super.call(this, name, scene) || this;
  98819. /**
  98820. * Key light Color (multiply against the environement texture)
  98821. */
  98822. _this.primaryColor = BABYLON.Color3.White();
  98823. _this._primaryColorShadowLevel = 0;
  98824. _this._primaryColorHighlightLevel = 0;
  98825. /**
  98826. * Reflection Texture used in the material.
  98827. * Should be author in a specific way for the best result (refer to the documentation).
  98828. */
  98829. _this.reflectionTexture = null;
  98830. /**
  98831. * Reflection Texture level of blur.
  98832. *
  98833. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98834. * texture twice.
  98835. */
  98836. _this.reflectionBlur = 0;
  98837. /**
  98838. * Diffuse Texture used in the material.
  98839. * Should be author in a specific way for the best result (refer to the documentation).
  98840. */
  98841. _this.diffuseTexture = null;
  98842. _this._shadowLights = null;
  98843. /**
  98844. * Specify the list of lights casting shadow on the material.
  98845. * All scene shadow lights will be included if null.
  98846. */
  98847. _this.shadowLights = null;
  98848. /**
  98849. * Helps adjusting the shadow to a softer level if required.
  98850. * 0 means black shadows and 1 means no shadows.
  98851. */
  98852. _this.shadowLevel = 0;
  98853. /**
  98854. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98855. * It is usually zero but might be interesting to modify according to your setup.
  98856. */
  98857. _this.sceneCenter = BABYLON.Vector3.Zero();
  98858. /**
  98859. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98860. * This helps ensuring a nice transition when the camera goes under the ground.
  98861. */
  98862. _this.opacityFresnel = true;
  98863. /**
  98864. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98865. * This helps adding a mirror texture on the ground.
  98866. */
  98867. _this.reflectionFresnel = false;
  98868. /**
  98869. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98870. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98871. */
  98872. _this.reflectionFalloffDistance = 0.0;
  98873. /**
  98874. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98875. */
  98876. _this.reflectionAmount = 1.0;
  98877. /**
  98878. * This specifies the weight of the reflection at grazing angle.
  98879. */
  98880. _this.reflectionReflectance0 = 0.05;
  98881. /**
  98882. * This specifies the weight of the reflection at a perpendicular point of view.
  98883. */
  98884. _this.reflectionReflectance90 = 0.5;
  98885. /**
  98886. * Helps to directly use the maps channels instead of their level.
  98887. */
  98888. _this.useRGBColor = true;
  98889. /**
  98890. * This helps reducing the banding effect that could occur on the background.
  98891. */
  98892. _this.enableNoise = false;
  98893. _this._fovMultiplier = 1.0;
  98894. /**
  98895. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98896. */
  98897. _this.useEquirectangularFOV = false;
  98898. _this._maxSimultaneousLights = 4;
  98899. /**
  98900. * Number of Simultaneous lights allowed on the material.
  98901. */
  98902. _this.maxSimultaneousLights = 4;
  98903. /**
  98904. * Keep track of the image processing observer to allow dispose and replace.
  98905. */
  98906. _this._imageProcessingObserver = null;
  98907. /**
  98908. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98909. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98910. */
  98911. _this.switchToBGR = false;
  98912. // Temp values kept as cache in the material.
  98913. _this._renderTargets = new BABYLON.SmartArray(16);
  98914. _this._reflectionControls = BABYLON.Vector4.Zero();
  98915. _this._white = BABYLON.Color3.White();
  98916. _this._primaryShadowColor = BABYLON.Color3.Black();
  98917. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98918. // Setup the default processing configuration to the scene.
  98919. _this._attachImageProcessingConfiguration(null);
  98920. _this.getRenderTargetTextures = function () {
  98921. _this._renderTargets.reset();
  98922. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98923. _this._renderTargets.push(_this._diffuseTexture);
  98924. }
  98925. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98926. _this._renderTargets.push(_this._reflectionTexture);
  98927. }
  98928. return _this._renderTargets;
  98929. };
  98930. return _this;
  98931. }
  98932. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98933. /**
  98934. * Experimental Internal Use Only.
  98935. *
  98936. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98937. * This acts as a helper to set the primary color to a more "human friendly" value.
  98938. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98939. * output color as close as possible from the chosen value.
  98940. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98941. * part of lighting setup.)
  98942. */
  98943. get: function () {
  98944. return this.__perceptualColor;
  98945. },
  98946. set: function (value) {
  98947. this.__perceptualColor = value;
  98948. this._computePrimaryColorFromPerceptualColor();
  98949. this._markAllSubMeshesAsLightsDirty();
  98950. },
  98951. enumerable: true,
  98952. configurable: true
  98953. });
  98954. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98955. /**
  98956. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98957. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98958. */
  98959. get: function () {
  98960. return this._primaryColorShadowLevel;
  98961. },
  98962. set: function (value) {
  98963. this._primaryColorShadowLevel = value;
  98964. this._computePrimaryColors();
  98965. this._markAllSubMeshesAsLightsDirty();
  98966. },
  98967. enumerable: true,
  98968. configurable: true
  98969. });
  98970. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98971. /**
  98972. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98973. * The primary color is used at the level chosen to define what the white area would look.
  98974. */
  98975. get: function () {
  98976. return this._primaryColorHighlightLevel;
  98977. },
  98978. set: function (value) {
  98979. this._primaryColorHighlightLevel = value;
  98980. this._computePrimaryColors();
  98981. this._markAllSubMeshesAsLightsDirty();
  98982. },
  98983. enumerable: true,
  98984. configurable: true
  98985. });
  98986. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98987. /**
  98988. * Sets the reflection reflectance fresnel values according to the default standard
  98989. * empirically know to work well :-)
  98990. */
  98991. set: function (value) {
  98992. var reflectionWeight = value;
  98993. if (reflectionWeight < 0.5) {
  98994. reflectionWeight = reflectionWeight * 2.0;
  98995. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98996. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98997. }
  98998. else {
  98999. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  99000. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  99001. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  99002. }
  99003. },
  99004. enumerable: true,
  99005. configurable: true
  99006. });
  99007. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  99008. /**
  99009. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99010. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  99011. * Recommended to be keep at 1.0 except for special cases.
  99012. */
  99013. get: function () {
  99014. return this._fovMultiplier;
  99015. },
  99016. set: function (value) {
  99017. if (isNaN(value)) {
  99018. value = 1.0;
  99019. }
  99020. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  99021. },
  99022. enumerable: true,
  99023. configurable: true
  99024. });
  99025. /**
  99026. * Attaches a new image processing configuration to the PBR Material.
  99027. * @param configuration (if null the scene configuration will be use)
  99028. */
  99029. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  99030. var _this = this;
  99031. if (configuration === this._imageProcessingConfiguration) {
  99032. return;
  99033. }
  99034. // Detaches observer.
  99035. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99036. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99037. }
  99038. // Pick the scene configuration if needed.
  99039. if (!configuration) {
  99040. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  99041. }
  99042. else {
  99043. this._imageProcessingConfiguration = configuration;
  99044. }
  99045. // Attaches observer.
  99046. if (this._imageProcessingConfiguration) {
  99047. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  99048. _this._computePrimaryColorFromPerceptualColor();
  99049. _this._markAllSubMeshesAsImageProcessingDirty();
  99050. });
  99051. }
  99052. };
  99053. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  99054. /**
  99055. * Gets the image processing configuration used either in this material.
  99056. */
  99057. get: function () {
  99058. return this._imageProcessingConfiguration;
  99059. },
  99060. /**
  99061. * Sets the Default image processing configuration used either in the this material.
  99062. *
  99063. * If sets to null, the scene one is in use.
  99064. */
  99065. set: function (value) {
  99066. this._attachImageProcessingConfiguration(value);
  99067. // Ensure the effect will be rebuilt.
  99068. this._markAllSubMeshesAsTexturesDirty();
  99069. },
  99070. enumerable: true,
  99071. configurable: true
  99072. });
  99073. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  99074. /**
  99075. * Gets wether the color curves effect is enabled.
  99076. */
  99077. get: function () {
  99078. return this.imageProcessingConfiguration.colorCurvesEnabled;
  99079. },
  99080. /**
  99081. * Sets wether the color curves effect is enabled.
  99082. */
  99083. set: function (value) {
  99084. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  99085. },
  99086. enumerable: true,
  99087. configurable: true
  99088. });
  99089. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  99090. /**
  99091. * Gets wether the color grading effect is enabled.
  99092. */
  99093. get: function () {
  99094. return this.imageProcessingConfiguration.colorGradingEnabled;
  99095. },
  99096. /**
  99097. * Gets wether the color grading effect is enabled.
  99098. */
  99099. set: function (value) {
  99100. this.imageProcessingConfiguration.colorGradingEnabled = value;
  99101. },
  99102. enumerable: true,
  99103. configurable: true
  99104. });
  99105. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  99106. /**
  99107. * Gets wether tonemapping is enabled or not.
  99108. */
  99109. get: function () {
  99110. return this._imageProcessingConfiguration.toneMappingEnabled;
  99111. },
  99112. /**
  99113. * Sets wether tonemapping is enabled or not
  99114. */
  99115. set: function (value) {
  99116. this._imageProcessingConfiguration.toneMappingEnabled = value;
  99117. },
  99118. enumerable: true,
  99119. configurable: true
  99120. });
  99121. ;
  99122. ;
  99123. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  99124. /**
  99125. * The camera exposure used on this material.
  99126. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99127. * This corresponds to a photographic exposure.
  99128. */
  99129. get: function () {
  99130. return this._imageProcessingConfiguration.exposure;
  99131. },
  99132. /**
  99133. * The camera exposure used on this material.
  99134. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  99135. * This corresponds to a photographic exposure.
  99136. */
  99137. set: function (value) {
  99138. this._imageProcessingConfiguration.exposure = value;
  99139. },
  99140. enumerable: true,
  99141. configurable: true
  99142. });
  99143. ;
  99144. ;
  99145. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  99146. /**
  99147. * Gets The camera contrast used on this material.
  99148. */
  99149. get: function () {
  99150. return this._imageProcessingConfiguration.contrast;
  99151. },
  99152. /**
  99153. * Sets The camera contrast used on this material.
  99154. */
  99155. set: function (value) {
  99156. this._imageProcessingConfiguration.contrast = value;
  99157. },
  99158. enumerable: true,
  99159. configurable: true
  99160. });
  99161. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  99162. /**
  99163. * Gets the Color Grading 2D Lookup Texture.
  99164. */
  99165. get: function () {
  99166. return this._imageProcessingConfiguration.colorGradingTexture;
  99167. },
  99168. /**
  99169. * Sets the Color Grading 2D Lookup Texture.
  99170. */
  99171. set: function (value) {
  99172. this.imageProcessingConfiguration.colorGradingTexture = value;
  99173. },
  99174. enumerable: true,
  99175. configurable: true
  99176. });
  99177. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  99178. /**
  99179. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99180. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99181. * 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;
  99182. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99183. */
  99184. get: function () {
  99185. return this.imageProcessingConfiguration.colorCurves;
  99186. },
  99187. /**
  99188. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  99189. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  99190. * 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;
  99191. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  99192. */
  99193. set: function (value) {
  99194. this.imageProcessingConfiguration.colorCurves = value;
  99195. },
  99196. enumerable: true,
  99197. configurable: true
  99198. });
  99199. /**
  99200. * The entire material has been created in order to prevent overdraw.
  99201. * @returns false
  99202. */
  99203. BackgroundMaterial.prototype.needAlphaTesting = function () {
  99204. return true;
  99205. };
  99206. /**
  99207. * The entire material has been created in order to prevent overdraw.
  99208. * @returns true if blending is enable
  99209. */
  99210. BackgroundMaterial.prototype.needAlphaBlending = function () {
  99211. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  99212. };
  99213. /**
  99214. * Checks wether the material is ready to be rendered for a given mesh.
  99215. * @param mesh The mesh to render
  99216. * @param subMesh The submesh to check against
  99217. * @param useInstances Specify wether or not the material is used with instances
  99218. * @returns true if all the dependencies are ready (Textures, Effects...)
  99219. */
  99220. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  99221. var _this = this;
  99222. if (useInstances === void 0) { useInstances = false; }
  99223. if (subMesh.effect && this.isFrozen) {
  99224. if (this._wasPreviouslyReady) {
  99225. return true;
  99226. }
  99227. }
  99228. if (!subMesh._materialDefines) {
  99229. subMesh._materialDefines = new BackgroundMaterialDefines();
  99230. }
  99231. var scene = this.getScene();
  99232. var defines = subMesh._materialDefines;
  99233. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  99234. if (defines._renderId === scene.getRenderId()) {
  99235. return true;
  99236. }
  99237. }
  99238. var engine = scene.getEngine();
  99239. // Lights
  99240. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  99241. defines._needNormals = true;
  99242. // Textures
  99243. if (defines._areTexturesDirty) {
  99244. defines._needUVs = false;
  99245. if (scene.texturesEnabled) {
  99246. if (scene.getEngine().getCaps().textureLOD) {
  99247. defines.TEXTURELODSUPPORT = true;
  99248. }
  99249. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99250. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  99251. return false;
  99252. }
  99253. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  99254. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  99255. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  99256. defines.OPACITYFRESNEL = this._opacityFresnel;
  99257. }
  99258. else {
  99259. defines.DIFFUSE = false;
  99260. defines.DIFFUSEHASALPHA = false;
  99261. defines.GAMMADIFFUSE = false;
  99262. defines.OPACITYFRESNEL = false;
  99263. }
  99264. var reflectionTexture = this._reflectionTexture;
  99265. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99266. if (!reflectionTexture.isReadyOrNotBlocking()) {
  99267. return false;
  99268. }
  99269. defines.REFLECTION = true;
  99270. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  99271. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  99272. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  99273. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  99274. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  99275. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  99276. defines.REFLECTIONBGR = this.switchToBGR;
  99277. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  99278. defines.INVERTCUBICMAP = true;
  99279. }
  99280. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  99281. switch (reflectionTexture.coordinatesMode) {
  99282. case BABYLON.Texture.EXPLICIT_MODE:
  99283. defines.REFLECTIONMAP_EXPLICIT = true;
  99284. break;
  99285. case BABYLON.Texture.PLANAR_MODE:
  99286. defines.REFLECTIONMAP_PLANAR = true;
  99287. break;
  99288. case BABYLON.Texture.PROJECTION_MODE:
  99289. defines.REFLECTIONMAP_PROJECTION = true;
  99290. break;
  99291. case BABYLON.Texture.SKYBOX_MODE:
  99292. defines.REFLECTIONMAP_SKYBOX = true;
  99293. break;
  99294. case BABYLON.Texture.SPHERICAL_MODE:
  99295. defines.REFLECTIONMAP_SPHERICAL = true;
  99296. break;
  99297. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  99298. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  99299. break;
  99300. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  99301. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  99302. break;
  99303. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  99304. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  99305. break;
  99306. case BABYLON.Texture.CUBIC_MODE:
  99307. case BABYLON.Texture.INVCUBIC_MODE:
  99308. default:
  99309. defines.REFLECTIONMAP_CUBIC = true;
  99310. break;
  99311. }
  99312. if (this.reflectionFresnel) {
  99313. defines.REFLECTIONFRESNEL = true;
  99314. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  99315. this._reflectionControls.x = this.reflectionAmount;
  99316. this._reflectionControls.y = this.reflectionReflectance0;
  99317. this._reflectionControls.z = this.reflectionReflectance90;
  99318. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  99319. }
  99320. else {
  99321. defines.REFLECTIONFRESNEL = false;
  99322. defines.REFLECTIONFALLOFF = false;
  99323. }
  99324. }
  99325. else {
  99326. defines.REFLECTION = false;
  99327. defines.REFLECTIONFRESNEL = false;
  99328. defines.REFLECTIONFALLOFF = false;
  99329. defines.REFLECTIONBLUR = false;
  99330. defines.REFLECTIONMAP_3D = false;
  99331. defines.REFLECTIONMAP_SPHERICAL = false;
  99332. defines.REFLECTIONMAP_PLANAR = false;
  99333. defines.REFLECTIONMAP_CUBIC = false;
  99334. defines.REFLECTIONMAP_PROJECTION = false;
  99335. defines.REFLECTIONMAP_SKYBOX = false;
  99336. defines.REFLECTIONMAP_EXPLICIT = false;
  99337. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99338. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99339. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99340. defines.INVERTCUBICMAP = false;
  99341. defines.REFLECTIONMAP_OPPOSITEZ = false;
  99342. defines.LODINREFLECTIONALPHA = false;
  99343. defines.GAMMAREFLECTION = false;
  99344. defines.RGBDREFLECTION = false;
  99345. }
  99346. }
  99347. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  99348. defines.USERGBCOLOR = this._useRGBColor;
  99349. defines.NOISE = this._enableNoise;
  99350. }
  99351. if (defines._areLightsDirty) {
  99352. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  99353. }
  99354. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  99355. if (!this._imageProcessingConfiguration.isReady()) {
  99356. return false;
  99357. }
  99358. this._imageProcessingConfiguration.prepareDefines(defines);
  99359. }
  99360. // Misc.
  99361. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  99362. // Values that need to be evaluated on every frame
  99363. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  99364. // Attribs
  99365. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  99366. if (mesh) {
  99367. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  99368. mesh.createNormals(true);
  99369. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  99370. }
  99371. }
  99372. }
  99373. // Get correct effect
  99374. if (defines.isDirty) {
  99375. defines.markAsProcessed();
  99376. scene.resetCachedMaterial();
  99377. // Fallbacks
  99378. var fallbacks = new BABYLON.EffectFallbacks();
  99379. if (defines.FOG) {
  99380. fallbacks.addFallback(0, "FOG");
  99381. }
  99382. if (defines.POINTSIZE) {
  99383. fallbacks.addFallback(1, "POINTSIZE");
  99384. }
  99385. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  99386. if (defines.NUM_BONE_INFLUENCERS > 0) {
  99387. fallbacks.addCPUSkinningFallback(0, mesh);
  99388. }
  99389. //Attributes
  99390. var attribs = [BABYLON.VertexBuffer.PositionKind];
  99391. if (defines.NORMAL) {
  99392. attribs.push(BABYLON.VertexBuffer.NormalKind);
  99393. }
  99394. if (defines.UV1) {
  99395. attribs.push(BABYLON.VertexBuffer.UVKind);
  99396. }
  99397. if (defines.UV2) {
  99398. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99399. }
  99400. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  99401. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  99402. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  99403. "vFogInfos", "vFogColor", "pointSize",
  99404. "vClipPlane", "mBones",
  99405. "vPrimaryColor", "vPrimaryColorShadow",
  99406. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  99407. "shadowLevel", "alpha",
  99408. "vBackgroundCenter", "vReflectionControl",
  99409. "vDiffuseInfos", "diffuseMatrix",
  99410. ];
  99411. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  99412. var uniformBuffers = ["Material", "Scene"];
  99413. if (BABYLON.ImageProcessingConfiguration) {
  99414. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  99415. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  99416. }
  99417. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  99418. uniformsNames: uniforms,
  99419. uniformBuffersNames: uniformBuffers,
  99420. samplers: samplers,
  99421. defines: defines,
  99422. maxSimultaneousLights: this._maxSimultaneousLights
  99423. });
  99424. var onCompiled = function (effect) {
  99425. if (_this.onCompiled) {
  99426. _this.onCompiled(effect);
  99427. }
  99428. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  99429. };
  99430. var join = defines.toString();
  99431. subMesh.setEffect(scene.getEngine().createEffect("background", {
  99432. attributes: attribs,
  99433. uniformsNames: uniforms,
  99434. uniformBuffersNames: uniformBuffers,
  99435. samplers: samplers,
  99436. defines: join,
  99437. fallbacks: fallbacks,
  99438. onCompiled: onCompiled,
  99439. onError: this.onError,
  99440. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  99441. }, engine), defines);
  99442. this.buildUniformLayout();
  99443. }
  99444. if (!subMesh.effect || !subMesh.effect.isReady()) {
  99445. return false;
  99446. }
  99447. defines._renderId = scene.getRenderId();
  99448. this._wasPreviouslyReady = true;
  99449. return true;
  99450. };
  99451. /**
  99452. * Compute the primary color according to the chosen perceptual color.
  99453. */
  99454. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  99455. if (!this.__perceptualColor) {
  99456. return;
  99457. }
  99458. this._primaryColor.copyFrom(this.__perceptualColor);
  99459. // Revert gamma space.
  99460. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  99461. // Revert image processing configuration.
  99462. if (this._imageProcessingConfiguration) {
  99463. // Revert Exposure.
  99464. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  99465. }
  99466. this._computePrimaryColors();
  99467. };
  99468. /**
  99469. * Compute the highlights and shadow colors according to their chosen levels.
  99470. */
  99471. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99472. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99473. return;
  99474. }
  99475. // Find the highlight color based on the configuration.
  99476. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99477. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99478. // Find the shadow color based on the configuration.
  99479. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99480. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99481. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99482. };
  99483. /**
  99484. * Build the uniform buffer used in the material.
  99485. */
  99486. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99487. // Order is important !
  99488. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99489. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99490. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99491. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99492. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99493. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99494. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99495. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99496. this._uniformBuffer.addUniform("pointSize", 1);
  99497. this._uniformBuffer.addUniform("shadowLevel", 1);
  99498. this._uniformBuffer.addUniform("alpha", 1);
  99499. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99500. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99501. this._uniformBuffer.create();
  99502. };
  99503. /**
  99504. * Unbind the material.
  99505. */
  99506. BackgroundMaterial.prototype.unbind = function () {
  99507. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99508. this._uniformBuffer.setTexture("diffuseSampler", null);
  99509. }
  99510. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99511. this._uniformBuffer.setTexture("reflectionSampler", null);
  99512. }
  99513. _super.prototype.unbind.call(this);
  99514. };
  99515. /**
  99516. * Bind only the world matrix to the material.
  99517. * @param world The world matrix to bind.
  99518. */
  99519. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99520. this._activeEffect.setMatrix("world", world);
  99521. };
  99522. /**
  99523. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99524. * @param world The world matrix to bind.
  99525. * @param subMesh The submesh to bind for.
  99526. */
  99527. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99528. var scene = this.getScene();
  99529. var defines = subMesh._materialDefines;
  99530. if (!defines) {
  99531. return;
  99532. }
  99533. var effect = subMesh.effect;
  99534. if (!effect) {
  99535. return;
  99536. }
  99537. this._activeEffect = effect;
  99538. // Matrices
  99539. this.bindOnlyWorldMatrix(world);
  99540. // Bones
  99541. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99542. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99543. if (mustRebind) {
  99544. this._uniformBuffer.bindToEffect(effect, "Material");
  99545. this.bindViewProjection(effect);
  99546. var reflectionTexture = this._reflectionTexture;
  99547. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99548. // Texture uniforms
  99549. if (scene.texturesEnabled) {
  99550. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99551. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99552. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99553. }
  99554. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99555. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99556. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99557. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99558. }
  99559. }
  99560. if (this.shadowLevel > 0) {
  99561. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99562. }
  99563. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99564. // Point size
  99565. if (this.pointsCloud) {
  99566. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99567. }
  99568. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99569. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99570. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99571. }
  99572. else {
  99573. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99574. }
  99575. }
  99576. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99577. // Textures
  99578. if (scene.texturesEnabled) {
  99579. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99580. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99581. }
  99582. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99583. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99584. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99585. }
  99586. else if (!defines.REFLECTIONBLUR) {
  99587. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99588. }
  99589. else {
  99590. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99591. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99592. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99593. }
  99594. if (defines.REFLECTIONFRESNEL) {
  99595. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99596. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99597. }
  99598. }
  99599. }
  99600. // Clip plane
  99601. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99602. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99603. }
  99604. if (mustRebind || !this.isFrozen) {
  99605. if (scene.lightsEnabled) {
  99606. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99607. }
  99608. // View
  99609. this.bindView(effect);
  99610. // Fog
  99611. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99612. // image processing
  99613. if (this._imageProcessingConfiguration) {
  99614. this._imageProcessingConfiguration.bind(this._activeEffect);
  99615. }
  99616. }
  99617. this._uniformBuffer.update();
  99618. this._afterBind(mesh);
  99619. };
  99620. /**
  99621. * Dispose the material.
  99622. * @param forceDisposeEffect Force disposal of the associated effect.
  99623. * @param forceDisposeTextures Force disposal of the associated textures.
  99624. */
  99625. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99626. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99627. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99628. if (forceDisposeTextures) {
  99629. if (this.diffuseTexture) {
  99630. this.diffuseTexture.dispose();
  99631. }
  99632. if (this.reflectionTexture) {
  99633. this.reflectionTexture.dispose();
  99634. }
  99635. }
  99636. this._renderTargets.dispose();
  99637. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99638. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99639. }
  99640. _super.prototype.dispose.call(this, forceDisposeEffect);
  99641. };
  99642. /**
  99643. * Clones the material.
  99644. * @param name The cloned name.
  99645. * @returns The cloned material.
  99646. */
  99647. BackgroundMaterial.prototype.clone = function (name) {
  99648. var _this = this;
  99649. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99650. };
  99651. /**
  99652. * Serializes the current material to its JSON representation.
  99653. * @returns The JSON representation.
  99654. */
  99655. BackgroundMaterial.prototype.serialize = function () {
  99656. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99657. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99658. return serializationObject;
  99659. };
  99660. /**
  99661. * Gets the class name of the material
  99662. * @returns "BackgroundMaterial"
  99663. */
  99664. BackgroundMaterial.prototype.getClassName = function () {
  99665. return "BackgroundMaterial";
  99666. };
  99667. /**
  99668. * Parse a JSON input to create back a background material.
  99669. * @param source The JSON data to parse
  99670. * @param scene The scene to create the parsed material in
  99671. * @param rootUrl The root url of the assets the material depends upon
  99672. * @returns the instantiated BackgroundMaterial.
  99673. */
  99674. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99675. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99676. };
  99677. /**
  99678. * Standard reflectance value at parallel view angle.
  99679. */
  99680. BackgroundMaterial.StandardReflectance0 = 0.05;
  99681. /**
  99682. * Standard reflectance value at grazing angle.
  99683. */
  99684. BackgroundMaterial.StandardReflectance90 = 0.5;
  99685. __decorate([
  99686. BABYLON.serializeAsColor3()
  99687. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99688. __decorate([
  99689. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99690. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99691. __decorate([
  99692. BABYLON.serializeAsColor3()
  99693. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99694. __decorate([
  99695. BABYLON.serialize()
  99696. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99697. __decorate([
  99698. BABYLON.serialize()
  99699. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99700. __decorate([
  99701. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99702. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99703. __decorate([
  99704. BABYLON.serializeAsTexture()
  99705. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99706. __decorate([
  99707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99708. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99709. __decorate([
  99710. BABYLON.serialize()
  99711. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99712. __decorate([
  99713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99714. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99715. __decorate([
  99716. BABYLON.serializeAsTexture()
  99717. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99718. __decorate([
  99719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99720. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99721. __decorate([
  99722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99723. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99724. __decorate([
  99725. BABYLON.serialize()
  99726. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99727. __decorate([
  99728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99729. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99730. __decorate([
  99731. BABYLON.serializeAsVector3()
  99732. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99733. __decorate([
  99734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99735. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99736. __decorate([
  99737. BABYLON.serialize()
  99738. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99739. __decorate([
  99740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99741. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99742. __decorate([
  99743. BABYLON.serialize()
  99744. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99745. __decorate([
  99746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99747. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99748. __decorate([
  99749. BABYLON.serialize()
  99750. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99751. __decorate([
  99752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99753. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99754. __decorate([
  99755. BABYLON.serialize()
  99756. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99757. __decorate([
  99758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99759. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99760. __decorate([
  99761. BABYLON.serialize()
  99762. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99763. __decorate([
  99764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99765. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99766. __decorate([
  99767. BABYLON.serialize()
  99768. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99769. __decorate([
  99770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99771. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99772. __decorate([
  99773. BABYLON.serialize()
  99774. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99775. __decorate([
  99776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99777. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99778. __decorate([
  99779. BABYLON.serialize()
  99780. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99781. __decorate([
  99782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99783. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99784. __decorate([
  99785. BABYLON.serialize()
  99786. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99787. __decorate([
  99788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99789. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99790. __decorate([
  99791. BABYLON.serializeAsImageProcessingConfiguration()
  99792. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99793. return BackgroundMaterial;
  99794. }(BABYLON.PushMaterial));
  99795. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99796. })(BABYLON || (BABYLON = {}));
  99797. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99798. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99799. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99800. s = arguments[i];
  99801. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99802. t[p] = s[p];
  99803. }
  99804. return t;
  99805. };
  99806. var BABYLON;
  99807. (function (BABYLON) {
  99808. /**
  99809. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99810. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99811. * It also helps with the default setup of your imageProcessing configuration.
  99812. */
  99813. var EnvironmentHelper = /** @class */ (function () {
  99814. /**
  99815. * constructor
  99816. * @param options
  99817. * @param scene The scene to add the material to
  99818. */
  99819. function EnvironmentHelper(options, scene) {
  99820. var _this = this;
  99821. this._errorHandler = function (message, exception) {
  99822. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99823. };
  99824. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99825. this._scene = scene;
  99826. this.onErrorObservable = new BABYLON.Observable();
  99827. this._setupBackground();
  99828. this._setupImageProcessing();
  99829. }
  99830. /**
  99831. * Creates the default options for the helper.
  99832. */
  99833. EnvironmentHelper._getDefaultOptions = function () {
  99834. return {
  99835. createGround: true,
  99836. groundSize: 15,
  99837. groundTexture: this._groundTextureCDNUrl,
  99838. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99839. groundOpacity: 0.9,
  99840. enableGroundShadow: true,
  99841. groundShadowLevel: 0.5,
  99842. enableGroundMirror: false,
  99843. groundMirrorSizeRatio: 0.3,
  99844. groundMirrorBlurKernel: 64,
  99845. groundMirrorAmount: 1,
  99846. groundMirrorFresnelWeight: 1,
  99847. groundMirrorFallOffDistance: 0,
  99848. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99849. groundYBias: 0.00001,
  99850. createSkybox: true,
  99851. skyboxSize: 20,
  99852. skyboxTexture: this._skyboxTextureCDNUrl,
  99853. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99854. backgroundYRotation: 0,
  99855. sizeAuto: true,
  99856. rootPosition: BABYLON.Vector3.Zero(),
  99857. setupImageProcessing: true,
  99858. environmentTexture: this._environmentTextureCDNUrl,
  99859. cameraExposure: 0.8,
  99860. cameraContrast: 1.2,
  99861. toneMappingEnabled: true,
  99862. };
  99863. };
  99864. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99865. /**
  99866. * Gets the root mesh created by the helper.
  99867. */
  99868. get: function () {
  99869. return this._rootMesh;
  99870. },
  99871. enumerable: true,
  99872. configurable: true
  99873. });
  99874. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99875. /**
  99876. * Gets the skybox created by the helper.
  99877. */
  99878. get: function () {
  99879. return this._skybox;
  99880. },
  99881. enumerable: true,
  99882. configurable: true
  99883. });
  99884. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99885. /**
  99886. * Gets the skybox texture created by the helper.
  99887. */
  99888. get: function () {
  99889. return this._skyboxTexture;
  99890. },
  99891. enumerable: true,
  99892. configurable: true
  99893. });
  99894. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99895. /**
  99896. * Gets the skybox material created by the helper.
  99897. */
  99898. get: function () {
  99899. return this._skyboxMaterial;
  99900. },
  99901. enumerable: true,
  99902. configurable: true
  99903. });
  99904. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99905. /**
  99906. * Gets the ground mesh created by the helper.
  99907. */
  99908. get: function () {
  99909. return this._ground;
  99910. },
  99911. enumerable: true,
  99912. configurable: true
  99913. });
  99914. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99915. /**
  99916. * Gets the ground texture created by the helper.
  99917. */
  99918. get: function () {
  99919. return this._groundTexture;
  99920. },
  99921. enumerable: true,
  99922. configurable: true
  99923. });
  99924. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99925. /**
  99926. * Gets the ground mirror created by the helper.
  99927. */
  99928. get: function () {
  99929. return this._groundMirror;
  99930. },
  99931. enumerable: true,
  99932. configurable: true
  99933. });
  99934. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99935. /**
  99936. * Gets the ground mirror render list to helps pushing the meshes
  99937. * you wish in the ground reflection.
  99938. */
  99939. get: function () {
  99940. if (this._groundMirror) {
  99941. return this._groundMirror.renderList;
  99942. }
  99943. return null;
  99944. },
  99945. enumerable: true,
  99946. configurable: true
  99947. });
  99948. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99949. /**
  99950. * Gets the ground material created by the helper.
  99951. */
  99952. get: function () {
  99953. return this._groundMaterial;
  99954. },
  99955. enumerable: true,
  99956. configurable: true
  99957. });
  99958. /**
  99959. * Updates the background according to the new options
  99960. * @param options
  99961. */
  99962. EnvironmentHelper.prototype.updateOptions = function (options) {
  99963. var newOptions = __assign({}, this._options, options);
  99964. if (this._ground && !newOptions.createGround) {
  99965. this._ground.dispose();
  99966. this._ground = null;
  99967. }
  99968. if (this._groundMaterial && !newOptions.createGround) {
  99969. this._groundMaterial.dispose();
  99970. this._groundMaterial = null;
  99971. }
  99972. if (this._groundTexture) {
  99973. if (this._options.groundTexture != newOptions.groundTexture) {
  99974. this._groundTexture.dispose();
  99975. this._groundTexture = null;
  99976. }
  99977. }
  99978. if (this._skybox && !newOptions.createSkybox) {
  99979. this._skybox.dispose();
  99980. this._skybox = null;
  99981. }
  99982. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99983. this._skyboxMaterial.dispose();
  99984. this._skyboxMaterial = null;
  99985. }
  99986. if (this._skyboxTexture) {
  99987. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99988. this._skyboxTexture.dispose();
  99989. this._skyboxTexture = null;
  99990. }
  99991. }
  99992. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99993. this._groundMirror.dispose();
  99994. this._groundMirror = null;
  99995. }
  99996. if (this._scene.environmentTexture) {
  99997. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99998. this._scene.environmentTexture.dispose();
  99999. }
  100000. }
  100001. this._options = newOptions;
  100002. this._setupBackground();
  100003. this._setupImageProcessing();
  100004. };
  100005. /**
  100006. * Sets the primary color of all the available elements.
  100007. * @param color the main color to affect to the ground and the background
  100008. */
  100009. EnvironmentHelper.prototype.setMainColor = function (color) {
  100010. if (this.groundMaterial) {
  100011. this.groundMaterial.primaryColor = color;
  100012. }
  100013. if (this.skyboxMaterial) {
  100014. this.skyboxMaterial.primaryColor = color;
  100015. }
  100016. if (this.groundMirror) {
  100017. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  100018. }
  100019. };
  100020. /**
  100021. * Setup the image processing according to the specified options.
  100022. */
  100023. EnvironmentHelper.prototype._setupImageProcessing = function () {
  100024. if (this._options.setupImageProcessing) {
  100025. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  100026. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  100027. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  100028. this._setupEnvironmentTexture();
  100029. }
  100030. };
  100031. /**
  100032. * Setup the environment texture according to the specified options.
  100033. */
  100034. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  100035. if (this._scene.environmentTexture) {
  100036. return;
  100037. }
  100038. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  100039. this._scene.environmentTexture = this._options.environmentTexture;
  100040. return;
  100041. }
  100042. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  100043. this._scene.environmentTexture = environmentTexture;
  100044. };
  100045. /**
  100046. * Setup the background according to the specified options.
  100047. */
  100048. EnvironmentHelper.prototype._setupBackground = function () {
  100049. if (!this._rootMesh) {
  100050. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  100051. }
  100052. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  100053. var sceneSize = this._getSceneSize();
  100054. if (this._options.createGround) {
  100055. this._setupGround(sceneSize);
  100056. this._setupGroundMaterial();
  100057. this._setupGroundDiffuseTexture();
  100058. if (this._options.enableGroundMirror) {
  100059. this._setupGroundMirrorTexture(sceneSize);
  100060. }
  100061. this._setupMirrorInGroundMaterial();
  100062. }
  100063. if (this._options.createSkybox) {
  100064. this._setupSkybox(sceneSize);
  100065. this._setupSkyboxMaterial();
  100066. this._setupSkyboxReflectionTexture();
  100067. }
  100068. this._rootMesh.position.x = sceneSize.rootPosition.x;
  100069. this._rootMesh.position.z = sceneSize.rootPosition.z;
  100070. this._rootMesh.position.y = sceneSize.rootPosition.y;
  100071. };
  100072. /**
  100073. * Get the scene sizes according to the setup.
  100074. */
  100075. EnvironmentHelper.prototype._getSceneSize = function () {
  100076. var _this = this;
  100077. var groundSize = this._options.groundSize;
  100078. var skyboxSize = this._options.skyboxSize;
  100079. var rootPosition = this._options.rootPosition;
  100080. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  100081. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100082. }
  100083. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  100084. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  100085. });
  100086. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  100087. if (this._options.sizeAuto) {
  100088. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  100089. this._scene.activeCamera.upperRadiusLimit) {
  100090. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  100091. skyboxSize = groundSize;
  100092. }
  100093. var sceneDiagonalLenght = sceneDiagonal.length();
  100094. if (sceneDiagonalLenght > groundSize) {
  100095. groundSize = sceneDiagonalLenght * 2;
  100096. skyboxSize = groundSize;
  100097. }
  100098. // 10 % bigger.
  100099. groundSize *= 1.1;
  100100. skyboxSize *= 1.5;
  100101. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  100102. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  100103. }
  100104. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  100105. };
  100106. /**
  100107. * Setup the ground according to the specified options.
  100108. */
  100109. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  100110. var _this = this;
  100111. if (!this._ground) {
  100112. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  100113. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  100114. this._ground.parent = this._rootMesh;
  100115. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  100116. }
  100117. this._ground.receiveShadows = this._options.enableGroundShadow;
  100118. };
  100119. /**
  100120. * Setup the ground material according to the specified options.
  100121. */
  100122. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  100123. if (!this._groundMaterial) {
  100124. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  100125. }
  100126. this._groundMaterial.alpha = this._options.groundOpacity;
  100127. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  100128. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  100129. this._groundMaterial.primaryColor = this._options.groundColor;
  100130. this._groundMaterial.useRGBColor = false;
  100131. this._groundMaterial.enableNoise = true;
  100132. if (this._ground) {
  100133. this._ground.material = this._groundMaterial;
  100134. }
  100135. };
  100136. /**
  100137. * Setup the ground diffuse texture according to the specified options.
  100138. */
  100139. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  100140. if (!this._groundMaterial) {
  100141. return;
  100142. }
  100143. if (this._groundTexture) {
  100144. return;
  100145. }
  100146. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  100147. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  100148. return;
  100149. }
  100150. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100151. diffuseTexture.gammaSpace = false;
  100152. diffuseTexture.hasAlpha = true;
  100153. this._groundMaterial.diffuseTexture = diffuseTexture;
  100154. };
  100155. /**
  100156. * Setup the ground mirror texture according to the specified options.
  100157. */
  100158. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  100159. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100160. if (!this._groundMirror) {
  100161. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  100162. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  100163. this._groundMirror.anisotropicFilteringLevel = 1;
  100164. this._groundMirror.wrapU = wrapping;
  100165. this._groundMirror.wrapV = wrapping;
  100166. this._groundMirror.gammaSpace = false;
  100167. if (this._groundMirror.renderList) {
  100168. for (var i = 0; i < this._scene.meshes.length; i++) {
  100169. var mesh = this._scene.meshes[i];
  100170. if (mesh !== this._ground &&
  100171. mesh !== this._skybox &&
  100172. mesh !== this._rootMesh) {
  100173. this._groundMirror.renderList.push(mesh);
  100174. }
  100175. }
  100176. }
  100177. }
  100178. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  100179. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  100180. };
  100181. /**
  100182. * Setup the ground to receive the mirror texture.
  100183. */
  100184. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  100185. if (this._groundMaterial) {
  100186. this._groundMaterial.reflectionTexture = this._groundMirror;
  100187. this._groundMaterial.reflectionFresnel = true;
  100188. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  100189. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  100190. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  100191. }
  100192. };
  100193. /**
  100194. * Setup the skybox according to the specified options.
  100195. */
  100196. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  100197. var _this = this;
  100198. if (!this._skybox) {
  100199. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  100200. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  100201. }
  100202. this._skybox.parent = this._rootMesh;
  100203. };
  100204. /**
  100205. * Setup the skybox material according to the specified options.
  100206. */
  100207. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  100208. if (!this._skybox) {
  100209. return;
  100210. }
  100211. if (!this._skyboxMaterial) {
  100212. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  100213. }
  100214. this._skyboxMaterial.useRGBColor = false;
  100215. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  100216. this._skyboxMaterial.enableNoise = true;
  100217. this._skybox.material = this._skyboxMaterial;
  100218. };
  100219. /**
  100220. * Setup the skybox reflection texture according to the specified options.
  100221. */
  100222. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  100223. if (!this._skyboxMaterial) {
  100224. return;
  100225. }
  100226. if (this._skyboxTexture) {
  100227. return;
  100228. }
  100229. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  100230. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  100231. return;
  100232. }
  100233. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  100234. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  100235. this._skyboxTexture.gammaSpace = false;
  100236. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  100237. };
  100238. /**
  100239. * Dispose all the elements created by the Helper.
  100240. */
  100241. EnvironmentHelper.prototype.dispose = function () {
  100242. if (this._groundMaterial) {
  100243. this._groundMaterial.dispose(true, true);
  100244. }
  100245. if (this._skyboxMaterial) {
  100246. this._skyboxMaterial.dispose(true, true);
  100247. }
  100248. this._rootMesh.dispose(false);
  100249. };
  100250. /**
  100251. * Default ground texture URL.
  100252. */
  100253. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  100254. /**
  100255. * Default skybox texture URL.
  100256. */
  100257. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  100258. /**
  100259. * Default environment texture URL.
  100260. */
  100261. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  100262. return EnvironmentHelper;
  100263. }());
  100264. BABYLON.EnvironmentHelper = EnvironmentHelper;
  100265. })(BABYLON || (BABYLON = {}));
  100266. //# sourceMappingURL=babylon.environmentHelper.js.map
  100267. var BABYLON;
  100268. (function (BABYLON) {
  100269. /**
  100270. * This class is made for on one-liner static method to help creating particle systems.
  100271. */
  100272. var ParticleHelper = /** @class */ (function () {
  100273. function ParticleHelper() {
  100274. }
  100275. /**
  100276. * This is the main static method (one-liner) of this helper to create different particle systems.
  100277. * @param type This string represents the type to the particle system to create
  100278. * @param emitter The object where the particle system will start to emit from.
  100279. * @param scene The scene where the particle system should live.
  100280. * @param gpu If the system will use gpu.
  100281. * @returns the ParticleSystem created.
  100282. */
  100283. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  100284. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  100285. if (gpu === void 0) { gpu = false; }
  100286. return new Promise(function (resolve, reject) {
  100287. if (!scene) {
  100288. scene = BABYLON.Engine.LastCreatedScene;
  100289. ;
  100290. }
  100291. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  100292. return reject("Particle system with GPU is not supported.");
  100293. }
  100294. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  100295. var newData = JSON.parse(data.toString());
  100296. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  100297. }, undefined, undefined, undefined, function (req, exception) {
  100298. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  100299. });
  100300. });
  100301. };
  100302. /**
  100303. * Static function used to create a new particle system from a IParticleSystemData
  100304. * @param data defines the source data
  100305. * @param scene defines the hosting scene
  100306. * @param emitter defines the particle emitter
  100307. * @returns a new ParticleSystem based on referenced data
  100308. */
  100309. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  100310. // Create a particle system
  100311. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  100312. // Where the particles come from
  100313. system.emitter = emitter; // the starting object, the emitter
  100314. ParticleHelper.UpdateSystem(system, data, scene);
  100315. return system;
  100316. };
  100317. /**
  100318. * Static function used to update a particle system from a IParticleSystemData
  100319. * @param system defines the particle system to update
  100320. * @param data defines the source data
  100321. * @param scene defines the hosting scene
  100322. */
  100323. ParticleHelper.UpdateSystem = function (system, data, scene) {
  100324. // Texture of each particle
  100325. if (data.textureFile) {
  100326. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  100327. }
  100328. // Colors of all particles
  100329. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  100330. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  100331. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  100332. // Size of each particle (random between...
  100333. system.minSize = data.minSize;
  100334. system.maxSize = data.maxSize;
  100335. system.minScaleX = data.minScaleX;
  100336. system.maxScaleX = data.maxScaleX;
  100337. system.minScaleY = data.minScaleY;
  100338. system.maxScaleY = data.maxScaleY;
  100339. // Life time of each particle (random between...
  100340. system.minLifeTime = data.minLifeTime;
  100341. system.maxLifeTime = data.maxLifeTime;
  100342. // Emission rate
  100343. system.emitRate = data.emitRate;
  100344. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100345. system.blendMode = data.blendMode;
  100346. // Set the gravity of all particles
  100347. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  100348. // Angular speed, in radians
  100349. system.minAngularSpeed = data.minAngularSpeed;
  100350. system.maxAngularSpeed = data.maxAngularSpeed;
  100351. // Speed
  100352. system.minEmitPower = data.minEmitPower;
  100353. system.maxEmitPower = data.maxEmitPower;
  100354. system.updateSpeed = data.updateSpeed;
  100355. switch (data.emitterType) {
  100356. case "box":
  100357. if (!data.direction1 || !data.direction2) {
  100358. throw new Error("Directions are missing in this particle system.");
  100359. }
  100360. if (!data.minEmitBox || !data.maxEmitBox) {
  100361. throw new Error("EmitBox is missing in this particle system.");
  100362. }
  100363. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  100364. break;
  100365. case "sphere":
  100366. system.createSphereEmitter(data.radius);
  100367. break;
  100368. case "directed_sphere":
  100369. if (!data.direction1 || !data.direction2) {
  100370. throw new Error("Directions are missing in this particle system.");
  100371. }
  100372. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  100373. break;
  100374. case "cone":
  100375. system.createConeEmitter(data.radius, data.angle);
  100376. break;
  100377. default:
  100378. break;
  100379. }
  100380. };
  100381. /**
  100382. * Static function used to export a particle system to a IParticleSystemData variable.
  100383. * Please note that texture file name is not exported and must be added manually
  100384. * @param system defines the particle system to export
  100385. */
  100386. ParticleHelper.ExportSystem = function (system) {
  100387. var outData = {};
  100388. // Colors of all particles
  100389. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  100390. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  100391. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  100392. // Size of each particle (random between...
  100393. outData.minSize = system.minSize;
  100394. outData.maxSize = system.maxSize;
  100395. outData.minScaleX = system.minScaleX;
  100396. outData.maxScaleX = system.maxScaleX;
  100397. outData.minScaleY = system.minScaleY;
  100398. outData.maxScaleY = system.maxScaleY;
  100399. // Life time of each particle (random between...
  100400. outData.minLifeTime = system.minLifeTime;
  100401. outData.maxLifeTime = system.maxLifeTime;
  100402. // Emission rate
  100403. outData.emitRate = system.emitRate;
  100404. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  100405. outData.blendMode = system.blendMode;
  100406. // Set the gravity of all particles
  100407. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  100408. // Angular speed, in radians
  100409. outData.minAngularSpeed = system.minAngularSpeed;
  100410. outData.maxAngularSpeed = system.maxAngularSpeed;
  100411. // Speed
  100412. outData.minEmitPower = system.minEmitPower;
  100413. outData.maxEmitPower = system.maxEmitPower;
  100414. outData.updateSpeed = system.updateSpeed;
  100415. switch (system.particleEmitterType.getClassName()) {
  100416. case "BoxEmitter":
  100417. outData.emitterType = "box";
  100418. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  100419. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  100420. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  100421. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  100422. break;
  100423. case "SphereParticleEmitter":
  100424. outData.emitterType = "sphere";
  100425. outData.radius = system.particleEmitterType.radius;
  100426. break;
  100427. case "SphereDirectedParticleEmitter":
  100428. outData.emitterType = "directed_sphere";
  100429. var sphereDirectedParticleEmitter = system.particleEmitterType;
  100430. outData.radius = sphereDirectedParticleEmitter.radius;
  100431. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  100432. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  100433. break;
  100434. case "ConeEmitter":
  100435. outData.emitterType = "cone";
  100436. outData.radius = system.particleEmitterType.radius;
  100437. outData.angle = system.particleEmitterType.angle;
  100438. break;
  100439. default:
  100440. break;
  100441. }
  100442. return outData;
  100443. };
  100444. /**
  100445. * Base Assets URL.
  100446. */
  100447. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  100448. return ParticleHelper;
  100449. }());
  100450. BABYLON.ParticleHelper = ParticleHelper;
  100451. })(BABYLON || (BABYLON = {}));
  100452. //# sourceMappingURL=babylon.particleHelper.js.map
  100453. var BABYLON;
  100454. (function (BABYLON) {
  100455. /**
  100456. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  100457. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  100458. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  100459. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100460. */
  100461. var VideoDome = /** @class */ (function (_super) {
  100462. __extends(VideoDome, _super);
  100463. /**
  100464. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  100465. * @param name Element's name, child elements will append suffixes for their own names.
  100466. * @param urlsOrVideo defines the url(s) or the video element to use
  100467. * @param options An object containing optional or exposed sub element properties
  100468. */
  100469. function VideoDome(name, urlsOrVideo, options, scene) {
  100470. var _this = _super.call(this, name, scene) || this;
  100471. // set defaults and manage values
  100472. name = name || "videoDome";
  100473. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100474. options.clickToPlay = Boolean(options.clickToPlay);
  100475. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  100476. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  100477. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100478. // create
  100479. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  100480. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100481. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  100482. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100483. flat: false,
  100484. radius: options.size,
  100485. subdivisions: options.resolution,
  100486. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100487. }, scene);
  100488. // configure material
  100489. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100490. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100491. material.reflectionTexture = _this._videoTexture;
  100492. material.useEquirectangularFOV = true;
  100493. material.fovMultiplier = 1.0;
  100494. // configure mesh
  100495. _this._mesh.material = material;
  100496. _this._mesh.parent = _this;
  100497. // optional configuration
  100498. if (options.clickToPlay) {
  100499. scene.onPointerUp = function () {
  100500. _this._videoTexture.video.play();
  100501. };
  100502. }
  100503. return _this;
  100504. }
  100505. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  100506. /**
  100507. * Gets the video texture being displayed on the sphere
  100508. */
  100509. get: function () {
  100510. return this._videoTexture;
  100511. },
  100512. enumerable: true,
  100513. configurable: true
  100514. });
  100515. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  100516. /**
  100517. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100518. * Also see the options.resolution property.
  100519. */
  100520. get: function () {
  100521. return this._material.fovMultiplier;
  100522. },
  100523. set: function (value) {
  100524. this._material.fovMultiplier = value;
  100525. },
  100526. enumerable: true,
  100527. configurable: true
  100528. });
  100529. /**
  100530. * Releases resources associated with this node.
  100531. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100532. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100533. */
  100534. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100535. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100536. this._videoTexture.dispose();
  100537. this._mesh.dispose();
  100538. this._material.dispose();
  100539. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100540. };
  100541. return VideoDome;
  100542. }(BABYLON.Node));
  100543. BABYLON.VideoDome = VideoDome;
  100544. })(BABYLON || (BABYLON = {}));
  100545. //# sourceMappingURL=babylon.videoDome.js.map
  100546. var BABYLON;
  100547. (function (BABYLON) {
  100548. /**
  100549. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  100550. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  100551. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  100552. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100553. */
  100554. var PhotoDome = /** @class */ (function (_super) {
  100555. __extends(PhotoDome, _super);
  100556. /**
  100557. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  100558. * @param name Element's name, child elements will append suffixes for their own names.
  100559. * @param urlsOfPhoto define the url of the photo to display
  100560. * @param options An object containing optional or exposed sub element properties
  100561. */
  100562. function PhotoDome(name, urlOfPhoto, options, scene) {
  100563. var _this = _super.call(this, name, scene) || this;
  100564. // set defaults and manage values
  100565. name = name || "photoDome";
  100566. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100567. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100568. // create
  100569. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100570. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100571. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100572. flat: false,
  100573. radius: options.size,
  100574. subdivisions: options.resolution,
  100575. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100576. }, scene);
  100577. // configure material
  100578. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100579. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100580. material.reflectionTexture = _this._photoTexture;
  100581. material.useEquirectangularFOV = true;
  100582. material.fovMultiplier = 1.0;
  100583. // configure mesh
  100584. _this._mesh.material = material;
  100585. _this._mesh.parent = _this;
  100586. return _this;
  100587. }
  100588. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  100589. /**
  100590. * Gets the texture being displayed on the sphere
  100591. */
  100592. get: function () {
  100593. return this._photoTexture;
  100594. },
  100595. enumerable: true,
  100596. configurable: true
  100597. });
  100598. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100599. /**
  100600. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100601. * Also see the options.resolution property.
  100602. */
  100603. get: function () {
  100604. return this._material.fovMultiplier;
  100605. },
  100606. set: function (value) {
  100607. this._material.fovMultiplier = value;
  100608. },
  100609. enumerable: true,
  100610. configurable: true
  100611. });
  100612. /**
  100613. * Releases resources associated with this node.
  100614. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100615. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100616. */
  100617. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100618. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100619. this._photoTexture.dispose();
  100620. this._mesh.dispose();
  100621. this._material.dispose();
  100622. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100623. };
  100624. return PhotoDome;
  100625. }(BABYLON.Node));
  100626. BABYLON.PhotoDome = PhotoDome;
  100627. })(BABYLON || (BABYLON = {}));
  100628. //# sourceMappingURL=babylon.photoDome.js.map
  100629. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec3 options;\nattribute vec2 size;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=options.x;\nvec2 offset=options.yz;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\nvec2 cornerPos=offset*size.yz*size.x;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin vec3 size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout vec3 outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=vec3(0.,0.,0.);\noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  100630. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  100631. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  100632. globalObject["BABYLON"] = BABYLON;
  100633. //backwards compatibility
  100634. if(typeof earcut !== 'undefined') {
  100635. globalObject["Earcut"] = {
  100636. earcut: earcut
  100637. };
  100638. }
  100639. return BABYLON;
  100640. });
  100641. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)))
  100642. /***/ }),
  100643. /* 1 */
  100644. /***/ (function(module, exports, __webpack_require__) {
  100645. "use strict";
  100646. Object.defineProperty(exports, "__esModule", { value: true });
  100647. var deepmerge = __webpack_require__(21);
  100648. var expDm = deepmerge['default'];
  100649. exports.deepmerge = expDm;
  100650. /**
  100651. * Is the provided string a URL?
  100652. *
  100653. * @param urlToCheck the url to inspect
  100654. */
  100655. function isUrl(urlToCheck) {
  100656. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  100657. return true;
  100658. }
  100659. return false;
  100660. }
  100661. exports.isUrl = isUrl;
  100662. /**
  100663. * Convert a string from kebab-case to camelCase
  100664. * @param s string to convert
  100665. */
  100666. function kebabToCamel(s) {
  100667. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  100668. }
  100669. exports.kebabToCamel = kebabToCamel;
  100670. //https://gist.github.com/youssman/745578062609e8acac9f
  100671. /**
  100672. * Convert a string from camelCase to kebab-case
  100673. * @param str string to convert
  100674. */
  100675. function camelToKebab(str) {
  100676. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  100677. }
  100678. exports.camelToKebab = camelToKebab;
  100679. /**
  100680. * This will extend an object with configuration values.
  100681. * What it practically does it take the keys from the configuration and set them on the object.
  100682. * I the configuration is a tree, it will traverse into the tree.
  100683. * @param object the object to extend
  100684. * @param config the configuration object that will extend the object
  100685. */
  100686. function extendClassWithConfig(object, config) {
  100687. if (!config)
  100688. return;
  100689. Object.keys(config).forEach(function (key) {
  100690. if (key in object && typeof object[key] !== 'function') {
  100691. // if (typeof object[key] === 'function') return;
  100692. // if it is an object, iterate internally until reaching basic types
  100693. if (typeof object[key] === 'object') {
  100694. extendClassWithConfig(object[key], config[key]);
  100695. }
  100696. else {
  100697. if (config[key] !== undefined) {
  100698. object[key] = config[key];
  100699. }
  100700. }
  100701. }
  100702. });
  100703. }
  100704. exports.extendClassWithConfig = extendClassWithConfig;
  100705. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQVMsQ0FBQyxTQUFTLENBQUMsQ0FBQztBQUNmLDBCQUFTO0FBRTNCOzs7O0dBSUc7QUFDSCxlQUFzQixVQUFrQjtJQUNwQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsS0FBSyxDQUFDLEtBQUssQ0FBQyxFQUFFO1FBQ3hJLE9BQU8sSUFBSSxDQUFDO0tBQ2Y7SUFDRCxPQUFPLEtBQUssQ0FBQztBQUNqQixDQUFD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UM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  100706. /***/ }),
  100707. /* 2 */
  100708. /***/ (function(module, exports, __webpack_require__) {
  100709. "use strict";
  100710. function __export(m) {
  100711. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  100712. }
  100713. Object.defineProperty(exports, "__esModule", { value: true });
  100714. __export(__webpack_require__(31));
  100715. __export(__webpack_require__(33));
  100716. __export(__webpack_require__(39));
  100717. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  100718. /***/ }),
  100719. /* 3 */
  100720. /***/ (function(module, exports, __webpack_require__) {
  100721. "use strict";
  100722. Object.defineProperty(exports, "__esModule", { value: true });
  100723. var babylonjs_1 = __webpack_require__(0);
  100724. var _1 = __webpack_require__(1);
  100725. /**
  100726. * This is a simple HTML mapper.
  100727. * This mapper parses a single HTML element and returns the configuration from its attributes.
  100728. * it parses numbers and boolean values to the corresponding variable types.
  100729. * The following HTML element:
  100730. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  100731. *
  100732. * {
  100733. * test: 1, //a number!
  100734. * randomFlag: boolean, //camelCase and boolean
  100735. * a: {
  100736. * string: {
  100737. * object: "test" //dot-separated object levels
  100738. * }
  100739. * }
  100740. * }
  100741. */
  100742. var HTMLMapper = /** @class */ (function () {
  100743. function HTMLMapper() {
  100744. }
  100745. /**
  100746. * Map a specific element and get configuration from it
  100747. * @param element the HTML element to analyze.
  100748. */
  100749. HTMLMapper.prototype.map = function (element) {
  100750. var config = {};
  100751. var _loop_1 = function (attrIdx) {
  100752. var attr = element.attributes.item(attrIdx);
  100753. if (!attr) {
  100754. return "continue";
  100755. }
  100756. // map "object.property" to the right configuration place.
  100757. var split = attr.nodeName.split('.');
  100758. split.reduce(function (currentConfig, key, idx) {
  100759. //convert html-style to json-style
  100760. var camelKey = _1.kebabToCamel(key);
  100761. if (idx === split.length - 1) {
  100762. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  100763. if (val === "true") {
  100764. val = true;
  100765. }
  100766. else if (val === "false") {
  100767. val = false;
  100768. }
  100769. else {
  100770. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  100771. if (isnum) {
  100772. var number = parseFloat(val);
  100773. if (!isNaN(number)) {
  100774. val = number;
  100775. }
  100776. }
  100777. }
  100778. currentConfig[camelKey] = val;
  100779. }
  100780. else {
  100781. currentConfig[camelKey] = currentConfig[camelKey] || {};
  100782. }
  100783. return currentConfig[camelKey];
  100784. }, config);
  100785. };
  100786. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  100787. _loop_1(attrIdx);
  100788. }
  100789. return config;
  100790. };
  100791. return HTMLMapper;
  100792. }());
  100793. /**
  100794. * A simple string-to-JSON mapper.
  100795. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  100796. */
  100797. var JSONMapper = /** @class */ (function () {
  100798. function JSONMapper() {
  100799. }
  100800. JSONMapper.prototype.map = function (rawSource) {
  100801. return JSON.parse(rawSource);
  100802. };
  100803. return JSONMapper;
  100804. }());
  100805. /**
  100806. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  100807. * DOM elements and attributes.
  100808. */
  100809. var DOMMapper = /** @class */ (function () {
  100810. function DOMMapper() {
  100811. }
  100812. /**
  100813. * The mapping function that will convert HTML data to a viewer configuration object
  100814. * @param baseElement the baseElement from which to start traversing
  100815. * @returns a ViewerCOnfiguration object from the provided HTML Element
  100816. */
  100817. DOMMapper.prototype.map = function (baseElement) {
  100818. var htmlMapper = new HTMLMapper();
  100819. var config = htmlMapper.map(baseElement);
  100820. var traverseChildren = function (element, partConfig) {
  100821. var children = element.children;
  100822. if (children.length) {
  100823. for (var i = 0; i < children.length; ++i) {
  100824. var item = children.item(i);
  100825. // use the HTML Mapper to read configuration from a single element
  100826. var configMapped = htmlMapper.map(item);
  100827. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  100828. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  100829. partConfig[key] = [];
  100830. }
  100831. else {
  100832. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  100833. partConfig.push(configMapped);
  100834. }
  100835. else if (partConfig[key]) {
  100836. //exists already! probably an array
  100837. element.setAttribute('array', 'true');
  100838. var oldItem = partConfig[key];
  100839. partConfig = [oldItem, configMapped];
  100840. }
  100841. else {
  100842. partConfig[key] = configMapped;
  100843. }
  100844. }
  100845. traverseChildren(item, partConfig[key] || configMapped);
  100846. }
  100847. }
  100848. return partConfig;
  100849. };
  100850. traverseChildren(baseElement, config);
  100851. return config;
  100852. };
  100853. return DOMMapper;
  100854. }());
  100855. /**
  100856. * The MapperManager manages the different implemented mappers.
  100857. * It allows the user to register new mappers as well and use them to parse their own configuration data
  100858. */
  100859. var MapperManager = /** @class */ (function () {
  100860. function MapperManager() {
  100861. this._mappers = {
  100862. "html": new HTMLMapper(),
  100863. "json": new JSONMapper(),
  100864. "dom": new DOMMapper()
  100865. };
  100866. }
  100867. /**
  100868. * Get a specific configuration mapper.
  100869. *
  100870. * @param type the name of the mapper to load
  100871. */
  100872. MapperManager.prototype.getMapper = function (type) {
  100873. if (!this._mappers[type]) {
  100874. babylonjs_1.Tools.Error("No mapper defined for " + type);
  100875. }
  100876. return this._mappers[type];
  100877. };
  100878. /**
  100879. * Use this functio to register your own configuration mapper.
  100880. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  100881. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  100882. * @param mapper The implemented mapper
  100883. */
  100884. MapperManager.prototype.registerMapper = function (type, mapper) {
  100885. this._mappers[type] = mapper;
  100886. };
  100887. /**
  100888. * Dispose the mapper manager and all of its mappers.
  100889. */
  100890. MapperManager.prototype.dispose = function () {
  100891. this._mappers = {};
  100892. };
  100893. /**
  100894. * The default mapper is the JSON mapper.
  100895. */
  100896. MapperManager.DefaultMapper = 'json';
  100897. return MapperManager;
  100898. }());
  100899. exports.MapperManager = MapperManager;
  100900. /**
  100901. * mapperManager is a singleton of the type MapperManager.
  100902. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  100903. * or indirectly with using BabylonViewer.disposeAll()
  100904. */
  100905. exports.mapperManager = new MapperManager();
  100906. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBa0M7QUFHbEMsK0JBQTBDO0FBUzFDOzs7Ozs7Ozs7Ozs7Ozs7O0dBZ0JHO0FBQ0g7SUFBQTtJQTRDQSxDQUFDO0lBMUNHOzs7T0FHRztJQUNILHdCQUFHLEdBQUgsVUFBSSxPQUFvQjtRQUVwQixJQUFJLE1BQU0sR0FBRyxFQUFFLENBQUM7Z0NBQ1AsT0FBTztZQUNaLElBQUksSUFBSSxHQUFHLE9BQU8sQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLE9BQU8sQ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DQUFDLEdBQUcsTUFBTSxDQUFDO0lBQ2pDLENBQUM7SUFFRDs7T0FFRztJQUNJLCtCQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUN2QixDQUFDO0lBeENEOztPQUVHO0lBQ1csMkJBQWEsR0FBRyxNQUFNLENBQUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0=
  100907. /***/ }),
  100908. /* 4 */
  100909. /***/ (function(module, exports, __webpack_require__) {
  100910. "use strict";
  100911. Object.defineProperty(exports, "__esModule", { value: true });
  100912. var babylonjs_1 = __webpack_require__(0);
  100913. var ViewerGlobals = /** @class */ (function () {
  100914. function ViewerGlobals() {
  100915. this.disableInit = false;
  100916. this.disableWebGL2Support = false;
  100917. }
  100918. Object.defineProperty(ViewerGlobals.prototype, "version", {
  100919. get: function () {
  100920. return babylonjs_1.Engine.Version;
  100921. },
  100922. enumerable: true,
  100923. configurable: true
  100924. });
  100925. return ViewerGlobals;
  100926. }());
  100927. exports.ViewerGlobals = ViewerGlobals;
  100928. exports.viewerGlobals = new ViewerGlobals();
  100929. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  100930. /***/ }),
  100931. /* 5 */
  100932. /***/ (function(module, exports, __webpack_require__) {
  100933. "use strict";
  100934. Object.defineProperty(exports, "__esModule", { value: true });
  100935. var babylonjs_1 = __webpack_require__(0);
  100936. var modelAnimation_1 = __webpack_require__(23);
  100937. var _1 = __webpack_require__(1);
  100938. /**
  100939. * The current state of the model
  100940. */
  100941. var ModelState;
  100942. (function (ModelState) {
  100943. ModelState[ModelState["INIT"] = 0] = "INIT";
  100944. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  100945. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  100946. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  100947. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  100948. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  100949. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  100950. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  100951. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  100952. /**
  100953. * The viewer model is a container for all assets representing a sngle loaded model.
  100954. */
  100955. var ViewerModel = /** @class */ (function () {
  100956. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  100957. var _this = this;
  100958. this._observablesManager = _observablesManager;
  100959. this._configurationContainer = _configurationContainer;
  100960. /**
  100961. * the list of meshes that are a part of this model
  100962. */
  100963. this._meshes = [];
  100964. /**
  100965. * ParticleSystems connected to this model
  100966. */
  100967. this.particleSystems = [];
  100968. /**
  100969. * Skeletons defined in this model
  100970. */
  100971. this.skeletons = [];
  100972. this._loaderDone = false;
  100973. this._animatables = [];
  100974. this._frameRate = 60;
  100975. this._shadowsRenderedAfterLoad = false;
  100976. this.onLoadedObservable = new babylonjs_1.Observable();
  100977. this.onLoadErrorObservable = new babylonjs_1.Observable();
  100978. this.onLoadProgressObservable = new babylonjs_1.Observable();
  100979. this.onCompleteObservable = new babylonjs_1.Observable();
  100980. this.onAfterConfigure = new babylonjs_1.Observable();
  100981. this.state = ModelState.INIT;
  100982. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh");
  100983. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh");
  100984. this._pivotMesh.parent = this.rootMesh;
  100985. // rotate 180, gltf fun
  100986. this._pivotMesh.rotation.y += Math.PI;
  100987. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100988. this._animations = [];
  100989. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  100990. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  100991. if (this._observablesManager) {
  100992. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  100993. }
  100994. if (this._modelConfiguration.entryAnimation) {
  100995. this.rootMesh.setEnabled(false);
  100996. }
  100997. this.onLoadedObservable.add(function () {
  100998. _this.updateConfiguration(_this._modelConfiguration);
  100999. if (_this._observablesManager) {
  101000. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  101001. }
  101002. _this._initAnimations();
  101003. });
  101004. this.onCompleteObservable.add(function () {
  101005. _this.state = ModelState.COMPLETE;
  101006. });
  101007. }
  101008. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  101009. get: function () {
  101010. return this._shadowsRenderedAfterLoad;
  101011. },
  101012. set: function (rendered) {
  101013. if (!rendered) {
  101014. throw new Error("can only be enabled");
  101015. }
  101016. else {
  101017. this._shadowsRenderedAfterLoad = rendered;
  101018. }
  101019. },
  101020. enumerable: true,
  101021. configurable: true
  101022. });
  101023. ViewerModel.prototype.getViewerId = function () {
  101024. return this._configurationContainer && this._configurationContainer.viewerId;
  101025. };
  101026. Object.defineProperty(ViewerModel.prototype, "enabled", {
  101027. /**
  101028. * Is this model enabled?
  101029. */
  101030. get: function () {
  101031. return this.rootMesh.isEnabled();
  101032. },
  101033. /**
  101034. * Set whether this model is enabled or not.
  101035. */
  101036. set: function (enable) {
  101037. this.rootMesh.setEnabled(enable);
  101038. },
  101039. enumerable: true,
  101040. configurable: true
  101041. });
  101042. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  101043. set: function (done) {
  101044. this._loaderDone = done;
  101045. this._checkCompleteState();
  101046. },
  101047. enumerable: true,
  101048. configurable: true
  101049. });
  101050. ViewerModel.prototype._checkCompleteState = function () {
  101051. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  101052. this._modelComplete();
  101053. }
  101054. };
  101055. /**
  101056. * Add a mesh to this model.
  101057. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  101058. *
  101059. * @param mesh the new mesh to add
  101060. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  101061. */
  101062. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  101063. if (!mesh.parent) {
  101064. mesh.parent = this._pivotMesh;
  101065. }
  101066. mesh.receiveShadows = !!this.configuration.receiveShadows;
  101067. this._meshes.push(mesh);
  101068. if (triggerLoaded) {
  101069. return this.onLoadedObservable.notifyObserversWithPromise(this);
  101070. }
  101071. };
  101072. Object.defineProperty(ViewerModel.prototype, "meshes", {
  101073. /**
  101074. * get the list of meshes (excluding the root mesh)
  101075. */
  101076. get: function () {
  101077. return this._meshes;
  101078. },
  101079. enumerable: true,
  101080. configurable: true
  101081. });
  101082. Object.defineProperty(ViewerModel.prototype, "configuration", {
  101083. /**
  101084. * Get the model's configuration
  101085. */
  101086. get: function () {
  101087. return this._modelConfiguration;
  101088. },
  101089. /**
  101090. * (Re-)set the model's entire configuration
  101091. * @param newConfiguration the new configuration to replace the new one
  101092. */
  101093. set: function (newConfiguration) {
  101094. this._modelConfiguration = newConfiguration;
  101095. this._configureModel();
  101096. },
  101097. enumerable: true,
  101098. configurable: true
  101099. });
  101100. /**
  101101. * Update the current configuration with new values.
  101102. * Configuration will not be overwritten, but merged with the new configuration.
  101103. * Priority is to the new configuration
  101104. * @param newConfiguration the configuration to be merged into the current configuration;
  101105. */
  101106. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  101107. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  101108. this._configureModel();
  101109. };
  101110. ViewerModel.prototype._initAnimations = function () {
  101111. var _this = this;
  101112. // check if this is not a gltf loader and init the animations
  101113. if (this.skeletons.length) {
  101114. this.skeletons.forEach(function (skeleton, idx) {
  101115. var ag = new babylonjs_1.AnimationGroup("animation-" + idx);
  101116. skeleton.getAnimatables().forEach(function (a) {
  101117. if (a.animations[0]) {
  101118. ag.addTargetedAnimation(a.animations[0], a);
  101119. }
  101120. });
  101121. _this.addAnimationGroup(ag);
  101122. });
  101123. }
  101124. var completeCallback = function () {
  101125. };
  101126. if (this._modelConfiguration.animation) {
  101127. if (this._modelConfiguration.animation.playOnce) {
  101128. this._animations.forEach(function (a) {
  101129. a.playMode = 0 /* ONCE */;
  101130. });
  101131. }
  101132. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  101133. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  101134. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  101135. completeCallback = function () {
  101136. _this.playAnimation(animationName_1);
  101137. };
  101138. }
  101139. }
  101140. this._enterScene(completeCallback);
  101141. };
  101142. /**
  101143. * Animates the model from the current position to the default position
  101144. * @param completeCallback A function to call when the animation has completed
  101145. */
  101146. ViewerModel.prototype._enterScene = function (completeCallback) {
  101147. var _this = this;
  101148. var scene = this.rootMesh.getScene();
  101149. var previousValue = scene.animationPropertiesOverride.enableBlending;
  101150. var callback = function () {
  101151. _this.state = ModelState.ENTRYDONE;
  101152. scene.animationPropertiesOverride.enableBlending = previousValue;
  101153. _this._checkCompleteState();
  101154. if (completeCallback)
  101155. completeCallback();
  101156. };
  101157. if (!this._entryAnimation) {
  101158. callback();
  101159. return;
  101160. }
  101161. this.rootMesh.setEnabled(true);
  101162. // disable blending for the sake of the entry animation;
  101163. scene.animationPropertiesOverride.enableBlending = false;
  101164. this._applyAnimation(this._entryAnimation, true, callback);
  101165. };
  101166. /**
  101167. * Animates the model from the current position to the exit-screen position
  101168. * @param completeCallback A function to call when the animation has completed
  101169. */
  101170. ViewerModel.prototype._exitScene = function (completeCallback) {
  101171. if (!this._exitAnimation) {
  101172. completeCallback();
  101173. return;
  101174. }
  101175. this._applyAnimation(this._exitAnimation, false, completeCallback);
  101176. };
  101177. ViewerModel.prototype._modelComplete = function () {
  101178. var _this = this;
  101179. //reapply material defines to be sure:
  101180. var meshes = this._pivotMesh.getChildMeshes(false);
  101181. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  101182. _this._applyModelMaterialConfiguration(mesh.material);
  101183. });
  101184. this.state = ModelState.COMPLETE;
  101185. this.onCompleteObservable.notifyObservers(this);
  101186. };
  101187. /**
  101188. * Add a new animation group to this model.
  101189. * @param animationGroup the new animation group to be added
  101190. */
  101191. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  101192. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  101193. };
  101194. /**
  101195. * Get the ModelAnimation array
  101196. */
  101197. ViewerModel.prototype.getAnimations = function () {
  101198. return this._animations;
  101199. };
  101200. /**
  101201. * Get the animations' names. Using the names you can play a specific animation.
  101202. */
  101203. ViewerModel.prototype.getAnimationNames = function () {
  101204. return this._animations.map(function (a) { return a.name; });
  101205. };
  101206. /**
  101207. * Get an animation by the provided name. Used mainly when playing n animation.
  101208. * @param name the name of the animation to find
  101209. */
  101210. ViewerModel.prototype._getAnimationByName = function (name) {
  101211. // can't use .find, noe available on IE
  101212. var filtered = this._animations.filter(function (a) { return a.name === name; });
  101213. // what the next line means - if two animations have the same name, they will not be returned!
  101214. if (filtered.length === 1) {
  101215. return filtered[0];
  101216. }
  101217. else {
  101218. return null;
  101219. }
  101220. };
  101221. /**
  101222. * Choose an initialized animation using its name and start playing it
  101223. * @param name the name of the animation to play
  101224. * @returns The model aniamtion to be played.
  101225. */
  101226. ViewerModel.prototype.playAnimation = function (name) {
  101227. var animation = this.setCurrentAnimationByName(name);
  101228. if (animation) {
  101229. animation.start();
  101230. }
  101231. return animation;
  101232. };
  101233. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  101234. var animation = this._getAnimationByName(name);
  101235. if (animation) {
  101236. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  101237. this.currentAnimation.stop();
  101238. }
  101239. this.currentAnimation = animation;
  101240. return animation;
  101241. }
  101242. else {
  101243. throw new Error("animation not found - " + name);
  101244. }
  101245. };
  101246. ViewerModel.prototype._configureModel = function () {
  101247. var _this = this;
  101248. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  101249. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  101250. var updateMeshesWithNoParent = function (variable, value, param) {
  101251. meshesWithNoParent.forEach(function (mesh) {
  101252. if (param) {
  101253. mesh[variable][param] = value;
  101254. }
  101255. else {
  101256. mesh[variable] = value;
  101257. }
  101258. });
  101259. };
  101260. var updateXYZ = function (variable, configValues) {
  101261. if (configValues.x !== undefined) {
  101262. updateMeshesWithNoParent(variable, configValues.x, 'x');
  101263. }
  101264. if (configValues.y !== undefined) {
  101265. updateMeshesWithNoParent(variable, configValues.y, 'y');
  101266. }
  101267. if (configValues.z !== undefined) {
  101268. updateMeshesWithNoParent(variable, configValues.z, 'z');
  101269. }
  101270. if (configValues.w !== undefined) {
  101271. updateMeshesWithNoParent(variable, configValues.w, 'w');
  101272. }
  101273. };
  101274. if (this._modelConfiguration.normalize) {
  101275. var center = false;
  101276. var unitSize = false;
  101277. var parentIndex = void 0;
  101278. if (this._modelConfiguration.normalize === true) {
  101279. center = true;
  101280. unitSize = true;
  101281. }
  101282. else {
  101283. center = !!this._modelConfiguration.normalize.center;
  101284. unitSize = !!this._modelConfiguration.normalize.unitSize;
  101285. parentIndex = this._modelConfiguration.normalize.parentIndex;
  101286. }
  101287. var meshesToNormalize = [];
  101288. if (parentIndex !== undefined) {
  101289. meshesToNormalize.push(this._meshes[parentIndex]);
  101290. }
  101291. else {
  101292. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  101293. }
  101294. if (unitSize) {
  101295. meshesToNormalize.forEach(function (mesh) {
  101296. mesh.normalizeToUnitCube(true);
  101297. mesh.computeWorldMatrix(true);
  101298. });
  101299. }
  101300. if (center) {
  101301. meshesToNormalize.forEach(function (mesh) {
  101302. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  101303. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  101304. var halfSizeVec = sizeVec.scale(0.5);
  101305. var center = boundingInfo.min.add(halfSizeVec);
  101306. mesh.position = center.scale(-1);
  101307. mesh.position.y += halfSizeVec.y;
  101308. // Recompute Info.
  101309. mesh.computeWorldMatrix(true);
  101310. });
  101311. }
  101312. }
  101313. else {
  101314. // if centered, should be done here
  101315. }
  101316. // position?
  101317. if (this._modelConfiguration.position) {
  101318. updateXYZ('position', this._modelConfiguration.position);
  101319. }
  101320. if (this._modelConfiguration.rotation) {
  101321. //quaternion?
  101322. if (this._modelConfiguration.rotation.w) {
  101323. meshesWithNoParent.forEach(function (mesh) {
  101324. if (!mesh.rotationQuaternion) {
  101325. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  101326. }
  101327. });
  101328. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  101329. }
  101330. else {
  101331. updateXYZ('rotation', this._modelConfiguration.rotation);
  101332. }
  101333. }
  101334. if (this._modelConfiguration.rotationOffsetAxis) {
  101335. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  101336. meshesWithNoParent.forEach(function (m) {
  101337. if (_this._modelConfiguration.rotationOffsetAngle) {
  101338. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  101339. }
  101340. });
  101341. }
  101342. if (this._modelConfiguration.scaling) {
  101343. updateXYZ('scaling', this._modelConfiguration.scaling);
  101344. }
  101345. if (this._modelConfiguration.castShadow) {
  101346. this._meshes.forEach(function (mesh) {
  101347. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  101348. });
  101349. }
  101350. var meshes = this._pivotMesh.getChildMeshes(false);
  101351. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  101352. _this._applyModelMaterialConfiguration(mesh.material);
  101353. });
  101354. if (this._modelConfiguration.entryAnimation) {
  101355. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  101356. }
  101357. if (this._modelConfiguration.exitAnimation) {
  101358. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  101359. }
  101360. this.onAfterConfigure.notifyObservers(this);
  101361. };
  101362. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  101363. var anim = {
  101364. time: 0.5
  101365. };
  101366. if (animConfig.scaling) {
  101367. anim.scaling = babylonjs_1.Vector3.Zero();
  101368. }
  101369. if (animConfig.easingFunction !== undefined) {
  101370. anim.easingFunction = animConfig.easingFunction;
  101371. }
  101372. if (animConfig.easingMode !== undefined) {
  101373. anim.easingMode = animConfig.easingMode;
  101374. }
  101375. _1.extendClassWithConfig(anim, animConfig);
  101376. return anim;
  101377. };
  101378. /**
  101379. * Apply a material configuration to a material
  101380. * @param material Material to apply configuration to
  101381. */
  101382. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  101383. if (!this._modelConfiguration.material)
  101384. return;
  101385. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  101386. if (material instanceof babylonjs_1.PBRMaterial) {
  101387. if (this._modelConfiguration.material.directIntensity !== undefined) {
  101388. material.directIntensity = this._modelConfiguration.material.directIntensity;
  101389. }
  101390. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  101391. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  101392. }
  101393. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  101394. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  101395. }
  101396. if (this._modelConfiguration.material.directEnabled !== undefined) {
  101397. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  101398. }
  101399. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  101400. material.reflectionColor = this._configurationContainer.reflectionColor;
  101401. }
  101402. }
  101403. else if (material instanceof babylonjs_1.MultiMaterial) {
  101404. for (var i = 0; i < material.subMaterials.length; i++) {
  101405. var subMaterial = material.subMaterials[i];
  101406. if (subMaterial) {
  101407. this._applyModelMaterialConfiguration(subMaterial);
  101408. }
  101409. }
  101410. }
  101411. };
  101412. /**
  101413. * Start entry/exit animation given an animation configuration
  101414. * @param animationConfiguration Entry/Exit animation configuration
  101415. * @param isEntry Pass true if the animation is an entry animation
  101416. * @param completeCallback Callback to execute when the animation completes
  101417. */
  101418. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  101419. var animations = [];
  101420. //scale
  101421. if (animationConfiguration.scaling) {
  101422. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  101423. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  101424. if (!scaleStart.equals(scaleEnd)) {
  101425. this.rootMesh.scaling = scaleStart;
  101426. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  101427. animations.push(this._scaleTransition);
  101428. }
  101429. }
  101430. //Start the animation(s)
  101431. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  101432. completeCallback(); });
  101433. };
  101434. /**
  101435. * Begin @animations with the specified @easingFunction
  101436. * @param animations The BABYLON Animations to begin
  101437. * @param duration of transition, in seconds
  101438. * @param easingFunction An easing function to apply
  101439. * @param easingMode A easing mode to apply to the easingFunction
  101440. * @param onAnimationEnd Call back trigger at the end of the animation.
  101441. */
  101442. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  101443. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  101444. if (easingFunction) {
  101445. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  101446. var animation = animations_1[_i];
  101447. easingFunction.setEasingMode(easingMode);
  101448. animation.setEasingFunction(easingFunction);
  101449. }
  101450. }
  101451. //Stop any current animations before starting the new one - merging not yet supported.
  101452. this.stopAllAnimations();
  101453. this.rootMesh.animations = animations;
  101454. if (this.rootMesh.getScene().beginAnimation) {
  101455. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  101456. if (onAnimationEnd) {
  101457. onAnimationEnd();
  101458. }
  101459. });
  101460. this._animatables.push(animatable);
  101461. }
  101462. };
  101463. /**
  101464. * Sets key values on an Animation from first to last frame.
  101465. * @param animation The Babylon animation object to set keys on
  101466. * @param startValue The value of the first key
  101467. * @param endValue The value of the last key
  101468. * @param duration The duration of the animation, used to determine the end frame
  101469. */
  101470. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  101471. animation.setKeys([
  101472. {
  101473. frame: 0,
  101474. value: startValue
  101475. },
  101476. {
  101477. frame: this._frameRate * duration,
  101478. value: endValue
  101479. }
  101480. ]);
  101481. };
  101482. /**
  101483. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  101484. * @param easingFunctionID The enum of the easing funtion to create
  101485. * @return The newly created Babylon easing function object
  101486. */
  101487. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  101488. var easingFunction;
  101489. switch (easingFunctionID) {
  101490. case 1 /* CircleEase */:
  101491. easingFunction = new babylonjs_1.CircleEase();
  101492. break;
  101493. case 2 /* BackEase */:
  101494. easingFunction = new babylonjs_1.BackEase(0.3);
  101495. break;
  101496. case 3 /* BounceEase */:
  101497. easingFunction = new babylonjs_1.BounceEase();
  101498. break;
  101499. case 4 /* CubicEase */:
  101500. easingFunction = new babylonjs_1.CubicEase();
  101501. break;
  101502. case 5 /* ElasticEase */:
  101503. easingFunction = new babylonjs_1.ElasticEase();
  101504. break;
  101505. case 6 /* ExponentialEase */:
  101506. easingFunction = new babylonjs_1.ExponentialEase();
  101507. break;
  101508. case 7 /* PowerEase */:
  101509. easingFunction = new babylonjs_1.PowerEase();
  101510. break;
  101511. case 8 /* QuadraticEase */:
  101512. easingFunction = new babylonjs_1.QuadraticEase();
  101513. break;
  101514. case 9 /* QuarticEase */:
  101515. easingFunction = new babylonjs_1.QuarticEase();
  101516. break;
  101517. case 10 /* QuinticEase */:
  101518. easingFunction = new babylonjs_1.QuinticEase();
  101519. break;
  101520. case 11 /* SineEase */:
  101521. easingFunction = new babylonjs_1.SineEase();
  101522. break;
  101523. default:
  101524. babylonjs_1.Tools.Log("No ease function found");
  101525. break;
  101526. }
  101527. return easingFunction;
  101528. };
  101529. /**
  101530. * Stops and removes all animations that have been applied to the model
  101531. */
  101532. ViewerModel.prototype.stopAllAnimations = function () {
  101533. if (this.rootMesh) {
  101534. this.rootMesh.animations = [];
  101535. }
  101536. if (this.currentAnimation) {
  101537. this.currentAnimation.stop();
  101538. }
  101539. while (this._animatables.length) {
  101540. this._animatables[0].onAnimationEnd = null;
  101541. this._animatables[0].stop();
  101542. this._animatables.shift();
  101543. }
  101544. };
  101545. /**
  101546. * Will remove this model from the viewer (but NOT dispose it).
  101547. */
  101548. ViewerModel.prototype.remove = function () {
  101549. this.stopAllAnimations();
  101550. // hide it
  101551. this.rootMesh.isVisible = false;
  101552. if (this._observablesManager) {
  101553. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  101554. }
  101555. };
  101556. /**
  101557. * Dispose this model, including all of its associated assets.
  101558. */
  101559. ViewerModel.prototype.dispose = function () {
  101560. this.remove();
  101561. this.onAfterConfigure.clear();
  101562. this.onLoadedObservable.clear();
  101563. this.onLoadErrorObservable.clear();
  101564. this.onLoadProgressObservable.clear();
  101565. if (this.loader && this.loader.name === "gltf") {
  101566. this.loader.dispose();
  101567. }
  101568. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  101569. this.particleSystems.length = 0;
  101570. this.skeletons.forEach(function (s) { return s.dispose(); });
  101571. this.skeletons.length = 0;
  101572. this._animations.forEach(function (ag) { return ag.dispose(); });
  101573. this._animations.length = 0;
  101574. this.rootMesh.dispose(false, true);
  101575. };
  101576. return ViewerModel;
  101577. }());
  101578. exports.ViewerModel = ViewerModel;
  101579. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTW9kZWwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvdmlld2VyTW9kZWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBc2Q7QUFJdGQsbURBQXdKO0FBRXhKLCtCQUE4RDtBQUs5RDs7R0FFRztBQUNILElBQVksVUFTWDtBQVRELFdBQVksVUFBVTtJQUNsQiwyQ0FBSSxDQUFBO0lBQ0osaURBQU8sQ0FBQTtJQUNQLCtDQUFNLENBQUE7SUFDTiw2Q0FBSyxDQUFBO0lBQ0wscURBQVMsQ0FBQTtJQUNULG1EQUFRLENBQUE7SUFDUixtREFBUSxDQUFBO0lBQ1IsNkNBQUssQ0FBQTtBQUNULENBQUMsRUFUVyxVQUFVLEdBQVYsa0JBQVUsS0FBVixrQkFBVSxRQVNyQjtBQUVEOztHQUVHO0FBQ0g7SUErRUkscUJBQW9CLG1CQUF1QyxFQUFFLGtCQUF1QyxFQU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RSxFQUFYLENBQVcsQ0FBQyxDQUFDO1FBQ3pDLElBQUksQ0FBQyxTQUFTLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztRQUMxQixJQUFJLENBQUMsV0FBVyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEVBQUUsSUFBSSxPQUFBLEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBWixDQUFZLENBQUMsQ0FBQztRQUM3QyxJQUFJLENBQUMsV0FBVyxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUM7UUFDNUIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUE1dEJELElBNHRCQztBQTV0Qlksa0NBQVcifQ==
  101580. /***/ }),
  101581. /* 6 */
  101582. /***/ (function(module, exports, __webpack_require__) {
  101583. "use strict";
  101584. Object.defineProperty(exports, "__esModule", { value: true });
  101585. var babylonjs_1 = __webpack_require__(0);
  101586. /**
  101587. * Receives Telemetry events and raises events to the API
  101588. */
  101589. var TelemetryManager = /** @class */ (function () {
  101590. function TelemetryManager() {
  101591. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  101592. this._event = this._eventEnabled;
  101593. }
  101594. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  101595. /**
  101596. * Receives a telemetry event
  101597. * @param event The name of the Telemetry event
  101598. * @param details An additional value, or an object containing a list of property/value pairs
  101599. */
  101600. get: function () {
  101601. return this._event;
  101602. },
  101603. enumerable: true,
  101604. configurable: true
  101605. });
  101606. /**
  101607. * Log a Telemetry event for errors raised on the WebGL context.
  101608. * @param engine The Babylon engine with the WebGL context.
  101609. */
  101610. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  101611. if (!engine) {
  101612. return;
  101613. }
  101614. var logErrors = true;
  101615. while (logErrors) {
  101616. var gl = engine._gl;
  101617. if (gl && gl.getError) {
  101618. var error = gl.getError();
  101619. if (error === gl.NO_ERROR) {
  101620. logErrors = false;
  101621. }
  101622. else {
  101623. this.broadcast("WebGL Error", viewerId, { error: error });
  101624. }
  101625. }
  101626. else {
  101627. logErrors = false;
  101628. }
  101629. }
  101630. };
  101631. Object.defineProperty(TelemetryManager.prototype, "enable", {
  101632. /**
  101633. * Enable or disable telemetry events
  101634. * @param enabled Boolan, true if events are enabled
  101635. */
  101636. set: function (enabled) {
  101637. if (enabled) {
  101638. this._event = this._eventEnabled;
  101639. }
  101640. else {
  101641. this._event = this._eventDisabled;
  101642. }
  101643. },
  101644. enumerable: true,
  101645. configurable: true
  101646. });
  101647. /**
  101648. * Called on event when disabled, typically do nothing here
  101649. */
  101650. TelemetryManager.prototype._eventDisabled = function () {
  101651. // nothing to do
  101652. };
  101653. /**
  101654. * Called on event when enabled
  101655. * @param event - The name of the Telemetry event
  101656. * @param details An additional value, or an object containing a list of property/value pairs
  101657. */
  101658. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  101659. var telemetryData = {
  101660. viewerId: viewerId,
  101661. event: event,
  101662. session: this.session,
  101663. date: new Date(),
  101664. now: window.performance ? window.performance.now() : Date.now(),
  101665. detail: null
  101666. };
  101667. if (typeof details === "object") {
  101668. for (var attr in details) {
  101669. if (details.hasOwnProperty(attr)) {
  101670. telemetryData[attr] = details[attr];
  101671. }
  101672. }
  101673. }
  101674. else if (details) {
  101675. telemetryData.detail = details;
  101676. }
  101677. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  101678. };
  101679. Object.defineProperty(TelemetryManager.prototype, "session", {
  101680. /**
  101681. * Returns the current session ID or creates one if it doesn't exixt
  101682. * @return The current session ID
  101683. */
  101684. get: function () {
  101685. if (!this._currentSessionId) {
  101686. //String + Timestamp + Random Integer
  101687. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  101688. }
  101689. return this._currentSessionId;
  101690. },
  101691. enumerable: true,
  101692. configurable: true
  101693. });
  101694. /**
  101695. * Disposes the telemetry manager
  101696. */
  101697. TelemetryManager.prototype.dispose = function () {
  101698. this.onEventBroadcastedObservable.clear();
  101699. delete this.onEventBroadcastedObservable;
  101700. };
  101701. return TelemetryManager;
  101702. }());
  101703. exports.TelemetryManager = TelemetryManager;
  101704. exports.telemetryManager = new TelemetryManager();
  101705. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9tYW5hZ2Vycy90ZWxlbWV0cnlNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQStDO0FBYy9DOztHQUVHO0FBQ0g7SUFBQTtRQUVXLGlDQUE0QixHQUE4QixJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUkxRSxXQUFNLEdBQThELElBQUksQ0FBQyxhQUFhLENBQUM7SUFzR25HLENBQUM7SUEvRkcsc0JBQVcsdUNBQVM7UUFMcEI7Ozs7V0FJRzthQUNIO1lBQ0ksT0FBTyxJQUFJLENBQUMsTUFBTSxDQUFDO1FBQ3ZCLENBQUM7OztPQUFBO0lBRUQ7OztPQUdHO0lBQ0ksMkNBQWdCLEdBQXZCLFVBQXdCLE1BQWMsRUFBRSxRQUFpQjtRQUNyRCxJQUFJLENBQUMsTUFBTSxFQUFFO1lBQ1QsT0FBTztTQUNWO1FBQ0QsSUFBSSxTQUFTLEdBQUcsSUFBSSxDQUFDO1FBRXJCLE9BQU8sU0FBUyxFQUFFO1lBQ2QsSUFBSSxFQUFFLEdBQVMsTUFBTyxDQUFDLEdBQUcsQ0FBQztZQUMzQixJQUFJLEVBQUUsSUFBSSxFQUFFLENBQUMsUUFBUSxFQUFFO2dCQUNuQixJQUFJLEtBQUssR0FBRyxFQUFFLENBQUMsUUFBUSxFQUFFLENBQUM7Z0JBQzFCLElBQ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SxnQkFBZ0IsRUFBRSxDQUFDIn0=
  101706. /***/ }),
  101707. /* 7 */
  101708. /***/ (function(module, exports, __webpack_require__) {
  101709. "use strict";
  101710. Object.defineProperty(exports, "__esModule", { value: true });
  101711. var babylonjs_1 = __webpack_require__(0);
  101712. /**
  101713. * The viewer manager is the container for all viewers currently registered on this page.
  101714. * It is possible to have more than one viewer on a single page.
  101715. */
  101716. var ViewerManager = /** @class */ (function () {
  101717. function ViewerManager() {
  101718. this._viewers = {};
  101719. this.onViewerAddedObservable = new babylonjs_1.Observable();
  101720. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  101721. }
  101722. /**
  101723. * Adding a new viewer to the viewer manager and start tracking it.
  101724. * @param viewer the viewer to add
  101725. */
  101726. ViewerManager.prototype.addViewer = function (viewer) {
  101727. this._viewers[viewer.getBaseId()] = viewer;
  101728. this._onViewerAdded(viewer);
  101729. };
  101730. /**
  101731. * remove a viewer from the viewer manager
  101732. * @param viewer the viewer to remove
  101733. */
  101734. ViewerManager.prototype.removeViewer = function (viewer) {
  101735. var id = viewer.getBaseId();
  101736. delete this._viewers[id];
  101737. this.onViewerRemovedObservable.notifyObservers(id);
  101738. };
  101739. /**
  101740. * 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)
  101741. * @param id the id of the HTMl element (or the viewer's, if none provided)
  101742. */
  101743. ViewerManager.prototype.getViewerById = function (id) {
  101744. return this._viewers[id];
  101745. };
  101746. /**
  101747. * Get a viewer using a container element
  101748. * @param element the HTML element to search viewers associated with
  101749. */
  101750. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  101751. for (var id in this._viewers) {
  101752. if (this._viewers[id].containerElement === element) {
  101753. return this.getViewerById(id);
  101754. }
  101755. }
  101756. };
  101757. /**
  101758. * Get a promise that will fullfil when this viewer was initialized.
  101759. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  101760. * you will get the viewer after everything was already configured.
  101761. * @param id the viewer id to find
  101762. */
  101763. ViewerManager.prototype.getViewerPromiseById = function (id) {
  101764. var _this = this;
  101765. return new Promise(function (resolve, reject) {
  101766. var localViewer = _this.getViewerById(id);
  101767. if (localViewer) {
  101768. return resolve(localViewer);
  101769. }
  101770. var viewerFunction = function (viewer) {
  101771. if (viewer.getBaseId() === id) {
  101772. resolve(viewer);
  101773. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  101774. }
  101775. };
  101776. _this.onViewerAddedObservable.add(viewerFunction);
  101777. });
  101778. };
  101779. ViewerManager.prototype._onViewerAdded = function (viewer) {
  101780. this.onViewerAdded && this.onViewerAdded(viewer);
  101781. this.onViewerAddedObservable.notifyObservers(viewer);
  101782. };
  101783. /**
  101784. * dispose the manager and all of its associated viewers
  101785. */
  101786. ViewerManager.prototype.dispose = function () {
  101787. delete this._onViewerAdded;
  101788. for (var id in this._viewers) {
  101789. this._viewers[id].dispose();
  101790. }
  101791. this.onViewerAddedObservable.clear();
  101792. this.onViewerRemovedObservable.clear();
  101793. };
  101794. return ViewerManager;
  101795. }());
  101796. exports.ViewerManager = ViewerManager;
  101797. exports.viewerManager = new ViewerManager();
  101798. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGlDQUF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JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  101799. /***/ }),
  101800. /* 8 */
  101801. /***/ (function(module, exports, __webpack_require__) {
  101802. "use strict";
  101803. var __extends = (this && this.__extends) || (function () {
  101804. var extendStatics = Object.setPrototypeOf ||
  101805. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  101806. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  101807. return function (d, b) {
  101808. extendStatics(d, b);
  101809. function __() { this.constructor = d; }
  101810. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  101811. };
  101812. })();
  101813. Object.defineProperty(exports, "__esModule", { value: true });
  101814. var viewer_1 = __webpack_require__(9);
  101815. var babylonjs_1 = __webpack_require__(0);
  101816. /**
  101817. * The Default viewer is the default implementation of the AbstractViewer.
  101818. * It uses the templating system to render a new canvas and controls.
  101819. */
  101820. var DefaultViewer = /** @class */ (function (_super) {
  101821. __extends(DefaultViewer, _super);
  101822. /**
  101823. * Create a new default viewer
  101824. * @param containerElement the element in which the templates will be rendered
  101825. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  101826. */
  101827. function DefaultViewer(containerElement, initialConfiguration) {
  101828. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  101829. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  101830. _this.containerElement = containerElement;
  101831. _this._handlePointerDown = function (event) {
  101832. var pointerDown = event.event;
  101833. if (pointerDown.button !== 0)
  101834. return;
  101835. var element = event.event.target;
  101836. if (!element) {
  101837. return;
  101838. }
  101839. var parentClasses = element.parentElement.classList;
  101840. switch (element.id) {
  101841. case "speed-button":
  101842. case "types-button":
  101843. if (parentClasses.contains("open")) {
  101844. parentClasses.remove("open");
  101845. }
  101846. else {
  101847. parentClasses.add("open");
  101848. }
  101849. break;
  101850. case "play-pause-button":
  101851. _this._togglePlayPause();
  101852. break;
  101853. case "label-option-button":
  101854. var label = element.dataset["value"];
  101855. if (label) {
  101856. _this._updateAnimationType(label);
  101857. }
  101858. break;
  101859. case "speed-option-button":
  101860. if (!_this._currentAnimation) {
  101861. return;
  101862. }
  101863. var speed = element.dataset["value"];
  101864. if (speed)
  101865. _this._updateAnimationSpeed(speed);
  101866. break;
  101867. case "progress-wrapper":
  101868. _this._resumePlay = !_this._isAnimationPaused;
  101869. if (_this._resumePlay) {
  101870. _this._togglePlayPause(true);
  101871. }
  101872. break;
  101873. case "fullscreen-button":
  101874. _this.toggleFullscreen();
  101875. break;
  101876. default:
  101877. return;
  101878. }
  101879. };
  101880. /**
  101881. * Plays or Pauses animation
  101882. */
  101883. _this._togglePlayPause = function (noUiUpdate) {
  101884. if (!_this._currentAnimation) {
  101885. return;
  101886. }
  101887. if (_this._isAnimationPaused) {
  101888. _this._currentAnimation.restart();
  101889. }
  101890. else {
  101891. _this._currentAnimation.pause();
  101892. }
  101893. _this._isAnimationPaused = !_this._isAnimationPaused;
  101894. if (noUiUpdate)
  101895. return;
  101896. var navbar = _this.templateManager.getTemplate('navBar');
  101897. if (!navbar)
  101898. return;
  101899. navbar.updateParams({
  101900. paused: _this._isAnimationPaused,
  101901. });
  101902. };
  101903. /**
  101904. * Control progress bar position based on animation current frame
  101905. */
  101906. _this._updateProgressBar = function () {
  101907. var navbar = _this.templateManager.getTemplate('navBar');
  101908. if (!navbar)
  101909. return;
  101910. var progressSlider = navbar.parent.querySelector("input#progress-wrapper");
  101911. if (progressSlider && _this._currentAnimation) {
  101912. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  101913. var currentValue = progressSlider.valueAsNumber;
  101914. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  101915. progressSlider.value = '' + progress;
  101916. }
  101917. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  101918. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  101919. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  101920. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  101921. }
  101922. }
  101923. else {
  101924. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  101925. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  101926. _this._oldIdleRotationValue = 0;
  101927. }
  101928. }
  101929. }
  101930. };
  101931. /**
  101932. * Update Current Animation Speed
  101933. */
  101934. _this._updateAnimationSpeed = function (speed, paramsObject) {
  101935. var navbar = _this.templateManager.getTemplate('navBar');
  101936. if (!navbar)
  101937. return;
  101938. if (speed && _this._currentAnimation) {
  101939. _this._currentAnimation.speedRatio = parseFloat(speed);
  101940. if (!_this._isAnimationPaused) {
  101941. _this._currentAnimation.restart();
  101942. }
  101943. if (paramsObject) {
  101944. paramsObject.selectedSpeed = speed + "x";
  101945. }
  101946. else {
  101947. navbar.updateParams({
  101948. selectedSpeed: speed + "x",
  101949. });
  101950. }
  101951. }
  101952. };
  101953. /**
  101954. * Update Current Animation Type
  101955. */
  101956. _this._updateAnimationType = function (label, paramsObject) {
  101957. var navbar = _this.templateManager.getTemplate('navBar');
  101958. if (!navbar)
  101959. return;
  101960. if (label) {
  101961. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  101962. }
  101963. if (paramsObject) {
  101964. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  101965. paramsObject.selectedAnimationName = label;
  101966. }
  101967. else {
  101968. navbar.updateParams({
  101969. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  101970. selectedAnimationName: label
  101971. });
  101972. }
  101973. _this._updateAnimationSpeed("1.0", paramsObject);
  101974. };
  101975. /**
  101976. * Toggle fullscreen of the entire viewer
  101977. */
  101978. _this.toggleFullscreen = function () {
  101979. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  101980. var viewerElement = viewerTemplate && viewerTemplate.parent;
  101981. if (viewerElement) {
  101982. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  101983. if (!fullscreenElement) {
  101984. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  101985. requestFullScreen.call(viewerElement);
  101986. }
  101987. else {
  101988. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  101989. exitFullscreen.call(document);
  101990. }
  101991. }
  101992. };
  101993. _this._onModelLoaded = function (model) {
  101994. _this._configureTemplate(model);
  101995. // with a short timeout, making sure everything is there already.
  101996. var hideLoadingDelay = 20;
  101997. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  101998. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  101999. }
  102000. setTimeout(function () {
  102001. _this.sceneManager.scene.executeWhenReady(function () {
  102002. _this.hideLoadingScreen();
  102003. });
  102004. }, hideLoadingDelay);
  102005. return;
  102006. };
  102007. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  102008. _this.onModelRemovedObservable.add(function () {
  102009. _this._configureTemplate();
  102010. });
  102011. _this.onEngineInitObservable.add(function () {
  102012. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  102013. _this._configureLights(data.newConfiguration, data.model);
  102014. });
  102015. });
  102016. return _this;
  102017. }
  102018. /**
  102019. * This will be executed when the templates initialize.
  102020. */
  102021. DefaultViewer.prototype._onTemplatesLoaded = function () {
  102022. var _this = this;
  102023. this.showLoadingScreen();
  102024. // navbar
  102025. this._initNavbar();
  102026. // close overlay button
  102027. var closeButton = document.getElementById('close-button');
  102028. if (closeButton) {
  102029. closeButton.addEventListener('pointerdown', function () {
  102030. _this.hideOverlayScreen();
  102031. });
  102032. }
  102033. if (this.configuration.templates && this.configuration.templates.viewer) {
  102034. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  102035. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  102036. }, function () {
  102037. }, function () {
  102038. }, function () {
  102039. }, function () {
  102040. }, function (file) {
  102041. _this.loadModel(file);
  102042. }, function () {
  102043. });
  102044. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  102045. }
  102046. }
  102047. return _super.prototype._onTemplatesLoaded.call(this);
  102048. };
  102049. DefaultViewer.prototype._dropped = function (evt) {
  102050. };
  102051. DefaultViewer.prototype._initNavbar = function () {
  102052. var _this = this;
  102053. var navbar = this.templateManager.getTemplate('navBar');
  102054. if (navbar) {
  102055. this.onFrameRenderedObservable.add(this._updateProgressBar);
  102056. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  102057. // an example how to trigger the help button. publiclly available
  102058. this.templateManager.eventManager.registerCallback("navBar", function () {
  102059. // do your thing
  102060. }, "pointerdown", "#help-button");
  102061. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  102062. var evt = event.event;
  102063. var element = (evt.target);
  102064. if (!_this._currentAnimation)
  102065. return;
  102066. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  102067. if (isNaN(gotoFrame))
  102068. return;
  102069. _this._currentAnimation.goToFrame(gotoFrame);
  102070. }, "input");
  102071. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  102072. if (_this._resumePlay) {
  102073. _this._togglePlayPause(true);
  102074. }
  102075. _this._resumePlay = false;
  102076. }, "pointerup", "#progress-wrapper");
  102077. }
  102078. };
  102079. /**
  102080. * Preparing the container element to present the viewer
  102081. */
  102082. DefaultViewer.prototype._prepareContainerElement = function () {
  102083. this.containerElement.style.position = 'relative';
  102084. this.containerElement.style.height = '100%';
  102085. this.containerElement.style.display = 'flex';
  102086. };
  102087. /**
  102088. * This function will configure the templates and update them after a model was loaded
  102089. * It is mainly responsible to changing the title and subtitle etc'.
  102090. * @param model the model to be used to configure the templates by
  102091. */
  102092. DefaultViewer.prototype._configureTemplate = function (model) {
  102093. var navbar = this.templateManager.getTemplate('navBar');
  102094. if (!navbar)
  102095. return;
  102096. var newParams = navbar.configuration.params || {};
  102097. if (!model) {
  102098. newParams.animations = null;
  102099. }
  102100. else {
  102101. var animationNames = model.getAnimationNames();
  102102. newParams.animations = animationNames;
  102103. if (animationNames.length) {
  102104. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  102105. this._animationList = animationNames;
  102106. newParams.paused = this._isAnimationPaused;
  102107. var animationIndex = 0;
  102108. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  102109. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  102110. if (animationIndex === -1) {
  102111. animationIndex = 0;
  102112. }
  102113. }
  102114. this._updateAnimationType(animationNames[animationIndex], newParams);
  102115. }
  102116. else {
  102117. newParams.animations = null;
  102118. }
  102119. if (model.configuration.thumbnail) {
  102120. newParams.logoImage = model.configuration.thumbnail;
  102121. }
  102122. }
  102123. navbar.updateParams(newParams, false);
  102124. };
  102125. /**
  102126. * This will load a new model to the default viewer
  102127. * overriding the AbstractViewer's loadModel.
  102128. * The scene will automatically be cleared of the old models, if exist.
  102129. * @param model the configuration object (or URL) to load.
  102130. */
  102131. DefaultViewer.prototype.loadModel = function (model) {
  102132. var _this = this;
  102133. if (!model) {
  102134. model = this.configuration.model;
  102135. }
  102136. this.showLoadingScreen();
  102137. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  102138. console.log(error);
  102139. _this.hideLoadingScreen();
  102140. _this.showOverlayScreen('error');
  102141. return Promise.reject(error);
  102142. });
  102143. };
  102144. /**
  102145. * Show the overlay and the defined sub-screen.
  102146. * Mainly used for help and errors
  102147. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  102148. */
  102149. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  102150. var _this = this;
  102151. var template = this.templateManager.getTemplate('overlay');
  102152. if (!template)
  102153. return Promise.resolve('Overlay template not found');
  102154. return template.show((function (template) {
  102155. var canvasRect = _this.containerElement.getBoundingClientRect();
  102156. template.parent.style.display = 'flex';
  102157. template.parent.style.width = canvasRect.width + "px";
  102158. template.parent.style.height = canvasRect.height + "px";
  102159. template.parent.style.opacity = "1";
  102160. var subTemplate = _this.templateManager.getTemplate(subScreen);
  102161. if (!subTemplate) {
  102162. return Promise.reject(subScreen + ' template not found');
  102163. }
  102164. return subTemplate.show((function (template) {
  102165. template.parent.style.display = 'flex';
  102166. return Promise.resolve(template);
  102167. }));
  102168. }));
  102169. };
  102170. /**
  102171. * Hide the overlay screen.
  102172. */
  102173. DefaultViewer.prototype.hideOverlayScreen = function () {
  102174. var template = this.templateManager.getTemplate('overlay');
  102175. if (!template)
  102176. return Promise.resolve('Overlay template not found');
  102177. return template.hide((function (template) {
  102178. template.parent.style.opacity = "0";
  102179. var onTransitionEnd = function () {
  102180. template.parent.removeEventListener("transitionend", onTransitionEnd);
  102181. template.parent.style.display = 'none';
  102182. };
  102183. template.parent.addEventListener("transitionend", onTransitionEnd);
  102184. var overlays = template.parent.querySelectorAll('.overlay');
  102185. if (overlays) {
  102186. for (var i = 0; i < overlays.length; ++i) {
  102187. var htmlElement = overlays.item(i);
  102188. htmlElement.style.display = 'none';
  102189. }
  102190. }
  102191. return Promise.resolve(template);
  102192. }));
  102193. };
  102194. /**
  102195. * show the viewer (in case it was hidden)
  102196. *
  102197. * @param visibilityFunction an optional function to execute in order to show the container
  102198. */
  102199. DefaultViewer.prototype.show = function (visibilityFunction) {
  102200. var template = this.templateManager.getTemplate('main');
  102201. //not possible, but yet:
  102202. if (!template)
  102203. return Promise.reject('Main template not found');
  102204. return template.show(visibilityFunction);
  102205. };
  102206. /**
  102207. * hide the viewer (in case it is visible)
  102208. *
  102209. * @param visibilityFunction an optional function to execute in order to hide the container
  102210. */
  102211. DefaultViewer.prototype.hide = function (visibilityFunction) {
  102212. var template = this.templateManager.getTemplate('main');
  102213. //not possible, but yet:
  102214. if (!template)
  102215. return Promise.reject('Main template not found');
  102216. return template.hide(visibilityFunction);
  102217. };
  102218. /**
  102219. * Show the loading screen.
  102220. * The loading screen can be configured using the configuration object
  102221. */
  102222. DefaultViewer.prototype.showLoadingScreen = function () {
  102223. var _this = this;
  102224. var template = this.templateManager.getTemplate('loadingScreen');
  102225. if (!template)
  102226. return Promise.resolve('Loading Screen template not found');
  102227. return template.show((function (template) {
  102228. var canvasRect = _this.containerElement.getBoundingClientRect();
  102229. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  102230. template.parent.style.display = 'flex';
  102231. template.parent.style.width = canvasRect.width + "px";
  102232. template.parent.style.height = canvasRect.height + "px";
  102233. template.parent.style.opacity = "1";
  102234. // from the configuration!!!
  102235. var color = "black";
  102236. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  102237. color = (_this.configuration.templates.loadingScreen.params &&
  102238. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  102239. }
  102240. template.parent.style.backgroundColor = color;
  102241. return Promise.resolve(template);
  102242. }));
  102243. };
  102244. /**
  102245. * Hide the loading screen
  102246. */
  102247. DefaultViewer.prototype.hideLoadingScreen = function () {
  102248. var template = this.templateManager.getTemplate('loadingScreen');
  102249. if (!template)
  102250. return Promise.resolve('Loading Screen template not found');
  102251. return template.hide((function (template) {
  102252. template.parent.style.opacity = "0";
  102253. var onTransitionEnd = function () {
  102254. template.parent.removeEventListener("transitionend", onTransitionEnd);
  102255. template.parent.style.display = 'none';
  102256. };
  102257. template.parent.addEventListener("transitionend", onTransitionEnd);
  102258. return Promise.resolve(template);
  102259. }));
  102260. };
  102261. DefaultViewer.prototype.dispose = function () {
  102262. this.templateManager.dispose();
  102263. _super.prototype.dispose.call(this);
  102264. };
  102265. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  102266. var _this = this;
  102267. _super.prototype._onConfigurationLoaded.call(this, configuration);
  102268. // initialize the templates
  102269. var templateConfiguration = this.configuration.templates || {};
  102270. this.templateManager.initTemplate(templateConfiguration);
  102271. // when done, execute onTemplatesLoaded()
  102272. this.templateManager.onAllLoaded.add(function () {
  102273. var canvas = _this.templateManager.getCanvas();
  102274. if (canvas) {
  102275. _this._canvas = canvas;
  102276. }
  102277. _this._onTemplateLoaded();
  102278. });
  102279. };
  102280. /**
  102281. * An extension of the light configuration of the abstract viewer.
  102282. * @param lightsConfiguration the light configuration to use
  102283. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  102284. */
  102285. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  102286. var _this = this;
  102287. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  102288. // labs feature - flashlight
  102289. if (this.configuration.lab && this.configuration.lab.flashlight) {
  102290. var pointerPosition = babylonjs_1.Vector3.Zero();
  102291. var lightTarget_1;
  102292. var angle = 0.5;
  102293. var exponent = Math.PI / 2;
  102294. if (typeof this.configuration.lab.flashlight === "object") {
  102295. exponent = this.configuration.lab.flashlight.exponent || exponent;
  102296. angle = this.configuration.lab.flashlight.angle || angle;
  102297. }
  102298. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  102299. if (typeof this.configuration.lab.flashlight === "object") {
  102300. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  102301. if (this.configuration.lab.flashlight.diffuse) {
  102302. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  102303. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  102304. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  102305. }
  102306. if (this.configuration.lab.flashlight.specular) {
  102307. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  102308. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  102309. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  102310. }
  102311. }
  102312. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  102313. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  102314. if (eventData.type === 4 && eventData.pickInfo) {
  102315. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  102316. }
  102317. else {
  102318. lightTarget_1 = undefined;
  102319. }
  102320. });
  102321. var updateFlashlightFunction = function () {
  102322. if (_this.sceneManager.camera && flashlight) {
  102323. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  102324. if (lightTarget_1) {
  102325. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  102326. }
  102327. }
  102328. };
  102329. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  102330. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  102331. }
  102332. };
  102333. return DefaultViewer;
  102334. }(viewer_1.AbstractViewer));
  102335. exports.DefaultViewer = DefaultViewer;
  102336. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdFZpZXdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvZGVmYXVsdFZpZXdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFJQSxtQ0FBMEM7QUFDMUMsdUNBQXNZO0FBTXRZOzs7R0FHRztBQUNIO0lBQW1DLGlDQUFjO0lBSTdDOzs7O09BSUc7SUFDSCx1QkFBbUIsZ0JBQTZCLEVBQUUsb0JBQWtFO1FBQWxFLHFDQUFBLEVBQUEseUJBQThDLE9BQU8sRUFBRSxTQUFTLEVBQUU7UUFBcEgsWUFDSSxrQkFBTSxnQkFBZ0IsRUFBRSxvQkFBb0IsQ0FBQyxTQVloRDtRQWJrQixzQkFBZ0IsR0FBaEIsZ0JBQWdCLENBQWE7UUF3RnhDLHdCQUFrQixHQUFHLFVBQUMsS0FBb0I7WUFFOUMsSUFBSSxXQUFXLEdBQWlCLEtBQU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UUFBUSxDQUFDLENBQUM7b0JBQ2hFLElBQUksYUFBVyxFQUFFO3dCQUNiLGFBQVcsQ0FBQyxhQUFhLENBQUMsVUFBVSxDQUFDLFFBQVEsRUFBRSxVQUFVLENBQUMsU0FBUyxDQUFDLENBQUM7cUJBQ3hFO2lCQUNKO1lBQ0wsQ0FBQyxDQUFBO1lBQ0QsSUFBSSxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsb0JBQW9CLENBQUMsd0JBQXdCLENBQUMsQ0FBQztZQUN2RSxJQUFJLENBQUMsa0NBQWtDLENBQUMsSUFBSSxDQUFDLHdCQUF3QixDQUFDLENBQUM7U0FDMUU7SUFDTCxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBemlCRCxDQUFtQyx1QkFBYyxHQXlpQmhEO0FBemlCWSxzQ0FBYSJ9
  102337. /***/ }),
  102338. /* 9 */
  102339. /***/ (function(module, exports, __webpack_require__) {
  102340. "use strict";
  102341. Object.defineProperty(exports, "__esModule", { value: true });
  102342. var viewerManager_1 = __webpack_require__(7);
  102343. var sceneManager_1 = __webpack_require__(22);
  102344. var loader_1 = __webpack_require__(28);
  102345. var babylonjs_1 = __webpack_require__(0);
  102346. var modelLoader_1 = __webpack_require__(13);
  102347. var globals_1 = __webpack_require__(4);
  102348. var telemetryManager_1 = __webpack_require__(6);
  102349. var _1 = __webpack_require__(1);
  102350. var observablesManager_1 = __webpack_require__(59);
  102351. var configurationContainer_1 = __webpack_require__(60);
  102352. var templateManager_1 = __webpack_require__(61);
  102353. /**
  102354. * The AbstractViewr is the center of Babylon's viewer.
  102355. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  102356. */
  102357. var AbstractViewer = /** @class */ (function () {
  102358. function AbstractViewer(containerElement, initialConfiguration) {
  102359. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  102360. var _this = this;
  102361. this.containerElement = containerElement;
  102362. /**
  102363. * A flag that controls whether or not the render loop should be executed
  102364. */
  102365. this.runRenderLoop = true;
  102366. /**
  102367. * is this viewer disposed?
  102368. */
  102369. this._isDisposed = false;
  102370. /**
  102371. * The resize function that will be registered with the window object
  102372. */
  102373. this._resize = function () {
  102374. // Only resize if Canvas is in the DOM
  102375. if (!_this.isCanvasInDOM()) {
  102376. return;
  102377. }
  102378. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  102379. return;
  102380. }
  102381. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  102382. return;
  102383. }
  102384. _this.engine.resize();
  102385. };
  102386. /**
  102387. * render loop that will be executed by the engine
  102388. */
  102389. this._render = function (force) {
  102390. if (force === void 0) { force = false; }
  102391. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  102392. if (_this.runRenderLoop || force) {
  102393. _this.engine.performanceMonitor.enable();
  102394. _this.sceneManager.scene.render();
  102395. _this.onFrameRenderedObservable.notifyObservers(_this);
  102396. }
  102397. else {
  102398. _this.engine.performanceMonitor.disable();
  102399. // update camera instead of rendering
  102400. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  102401. }
  102402. }
  102403. };
  102404. // if exists, use the container id. otherwise, generate a random string.
  102405. if (containerElement.id) {
  102406. this.baseId = containerElement.id;
  102407. }
  102408. else {
  102409. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  102410. }
  102411. this._registeredOnBeforeRenderFunctions = [];
  102412. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  102413. // add this viewer to the viewer manager
  102414. viewerManager_1.viewerManager.addViewer(this);
  102415. this.observablesManager = new observablesManager_1.ObservablesManager();
  102416. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  102417. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  102418. // extend the configuration
  102419. this._configurationLoader = new loader_1.ConfigurationLoader();
  102420. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  102421. _this._onConfigurationLoaded(configuration);
  102422. });
  102423. this.onSceneInitObservable.add(function () {
  102424. _this.updateConfiguration();
  102425. });
  102426. this.onInitDoneObservable.add(function () {
  102427. _this._isInit = true;
  102428. _this.engine.runRenderLoop(_this._render);
  102429. });
  102430. this._prepareContainerElement();
  102431. }
  102432. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  102433. // observables
  102434. /**
  102435. * Will notify when the scene was initialized
  102436. */
  102437. get: function () {
  102438. return this.observablesManager.onSceneInitObservable;
  102439. },
  102440. enumerable: true,
  102441. configurable: true
  102442. });
  102443. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  102444. /**
  102445. * will notify when the engine was initialized
  102446. */
  102447. get: function () {
  102448. return this.observablesManager.onEngineInitObservable;
  102449. },
  102450. enumerable: true,
  102451. configurable: true
  102452. });
  102453. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  102454. /**
  102455. * Will notify when a new model was added to the scene.
  102456. * Note that added does not neccessarily mean loaded!
  102457. */
  102458. get: function () {
  102459. return this.observablesManager.onModelAddedObservable;
  102460. },
  102461. enumerable: true,
  102462. configurable: true
  102463. });
  102464. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  102465. /**
  102466. * will notify after every model load
  102467. */
  102468. get: function () {
  102469. return this.observablesManager.onModelLoadedObservable;
  102470. },
  102471. enumerable: true,
  102472. configurable: true
  102473. });
  102474. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  102475. /**
  102476. * will notify when any model notify of progress
  102477. */
  102478. get: function () {
  102479. return this.observablesManager.onModelLoadProgressObservable;
  102480. },
  102481. enumerable: true,
  102482. configurable: true
  102483. });
  102484. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  102485. /**
  102486. * will notify when any model load failed.
  102487. */
  102488. get: function () {
  102489. return this.observablesManager.onModelLoadErrorObservable;
  102490. },
  102491. enumerable: true,
  102492. configurable: true
  102493. });
  102494. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  102495. /**
  102496. * Will notify when a model was removed from the scene;
  102497. */
  102498. get: function () {
  102499. return this.observablesManager.onModelRemovedObservable;
  102500. },
  102501. enumerable: true,
  102502. configurable: true
  102503. });
  102504. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  102505. /**
  102506. * will notify when a new loader was initialized.
  102507. * Used mainly to know when a model starts loading.
  102508. */
  102509. get: function () {
  102510. return this.observablesManager.onLoaderInitObservable;
  102511. },
  102512. enumerable: true,
  102513. configurable: true
  102514. });
  102515. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  102516. /**
  102517. * Observers registered here will be executed when the entire load process has finished.
  102518. */
  102519. get: function () {
  102520. return this.observablesManager.onViewerInitDoneObservable;
  102521. },
  102522. enumerable: true,
  102523. configurable: true
  102524. });
  102525. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  102526. /**
  102527. * Functions added to this observable will be executed on each frame rendered.
  102528. */
  102529. get: function () {
  102530. return this.observablesManager.onFrameRenderedObservable;
  102531. },
  102532. enumerable: true,
  102533. configurable: true
  102534. });
  102535. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  102536. /**
  102537. * The (single) canvas of this viewer
  102538. */
  102539. get: function () {
  102540. return this._canvas;
  102541. },
  102542. enumerable: true,
  102543. configurable: true
  102544. });
  102545. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  102546. get: function () {
  102547. return this._configurationContainer;
  102548. },
  102549. enumerable: true,
  102550. configurable: true
  102551. });
  102552. /**
  102553. * get the baseId of this viewer
  102554. */
  102555. AbstractViewer.prototype.getBaseId = function () {
  102556. return this.baseId;
  102557. };
  102558. /**
  102559. * Do we have a canvas to render on, and is it a part of the scene
  102560. */
  102561. AbstractViewer.prototype.isCanvasInDOM = function () {
  102562. return !!this._canvas && !!this._canvas.parentElement;
  102563. };
  102564. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  102565. /**
  102566. * Is the engine currently set to rende even when the page is in background
  102567. */
  102568. get: function () {
  102569. return this.engine && this.engine.renderEvenInBackground;
  102570. },
  102571. /**
  102572. * Set the viewer's background rendering flag.
  102573. */
  102574. set: function (value) {
  102575. if (this.engine) {
  102576. this.engine.renderEvenInBackground = value;
  102577. }
  102578. },
  102579. enumerable: true,
  102580. configurable: true
  102581. });
  102582. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  102583. /**
  102584. * Get the configuration object. This is a reference only.
  102585. * The configuration can ONLY be updated using the updateConfiguration function.
  102586. * changing this object will have no direct effect on the scene.
  102587. */
  102588. get: function () {
  102589. return this._configurationContainer.configuration;
  102590. },
  102591. enumerable: true,
  102592. configurable: true
  102593. });
  102594. /**
  102595. * force resizing the engine.
  102596. */
  102597. AbstractViewer.prototype.forceResize = function () {
  102598. this._resize();
  102599. };
  102600. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  102601. var _this = this;
  102602. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  102603. if (this.configuration.observers) {
  102604. this._configureObservers(this.configuration.observers);
  102605. }
  102606. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  102607. if (this.configuration.loaderPlugins) {
  102608. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  102609. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  102610. _this.modelLoader.addPlugin(name);
  102611. }
  102612. }));
  102613. }
  102614. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  102615. };
  102616. /**
  102617. * Force a single render loop execution.
  102618. */
  102619. AbstractViewer.prototype.forceRender = function () {
  102620. this._render(true);
  102621. };
  102622. /**
  102623. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  102624. * @param callback optional callback that will be triggered when screenshot is done.
  102625. * @param width Optional screenshot width (default to 512).
  102626. * @param height Optional screenshot height (default to 512).
  102627. * @returns a promise with the screenshot data
  102628. */
  102629. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  102630. var _this = this;
  102631. if (width === void 0) { width = 0; }
  102632. if (height === void 0) { height = 0; }
  102633. width = width || this.canvas.clientWidth;
  102634. height = height || this.canvas.clientHeight;
  102635. // Create the screenshot
  102636. return new Promise(function (resolve, reject) {
  102637. try {
  102638. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  102639. if (callback) {
  102640. callback(data);
  102641. }
  102642. resolve(data);
  102643. });
  102644. }
  102645. catch (e) {
  102646. reject(e);
  102647. }
  102648. });
  102649. };
  102650. /**
  102651. * Update the current viewer configuration with new values.
  102652. * Only provided information will be updated, old configuration values will be kept.
  102653. * If this.configuration was manually changed, you can trigger this function with no parameters,
  102654. * and the entire configuration will be updated.
  102655. * @param newConfiguration the partial configuration to update
  102656. *
  102657. */
  102658. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  102659. var _this = this;
  102660. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  102661. // update this.configuration with the new data
  102662. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  102663. this.sceneManager.updateConfiguration(newConfiguration);
  102664. // observers in configuration
  102665. if (newConfiguration.observers) {
  102666. this._configureObservers(newConfiguration.observers);
  102667. }
  102668. if (newConfiguration.loaderPlugins) {
  102669. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  102670. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  102671. _this.modelLoader.addPlugin(name);
  102672. }
  102673. }));
  102674. }
  102675. };
  102676. /**
  102677. * this is used to register native functions using the configuration object.
  102678. * This will configure the observers.
  102679. * @param observersConfiguration observers configuration
  102680. */
  102681. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  102682. if (observersConfiguration.onEngineInit) {
  102683. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  102684. }
  102685. else {
  102686. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  102687. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  102688. }
  102689. }
  102690. if (observersConfiguration.onSceneInit) {
  102691. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  102692. }
  102693. else {
  102694. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  102695. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  102696. }
  102697. }
  102698. if (observersConfiguration.onModelLoaded) {
  102699. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  102700. }
  102701. else {
  102702. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  102703. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  102704. }
  102705. }
  102706. };
  102707. /**
  102708. * Dispoe the entire viewer including the scene and the engine
  102709. */
  102710. AbstractViewer.prototype.dispose = function () {
  102711. if (this._isDisposed) {
  102712. return;
  102713. }
  102714. window.removeEventListener('resize', this._resize);
  102715. if (this.sceneManager) {
  102716. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  102717. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  102718. }
  102719. this.sceneManager.dispose();
  102720. }
  102721. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  102722. this.observablesManager.dispose();
  102723. this.modelLoader.dispose();
  102724. if (this.engine) {
  102725. this.engine.dispose();
  102726. }
  102727. viewerManager_1.viewerManager.removeViewer(this);
  102728. this._isDisposed = true;
  102729. };
  102730. /**
  102731. * This function will execute when the HTML templates finished initializing.
  102732. * It should initialize the engine and continue execution.
  102733. *
  102734. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  102735. */
  102736. AbstractViewer.prototype._onTemplatesLoaded = function () {
  102737. return Promise.resolve(this);
  102738. };
  102739. /**
  102740. * This will force the creation of an engine and a scene.
  102741. * It will also load a model if preconfigured.
  102742. * But first - it will load the extendible onTemplateLoaded()!
  102743. */
  102744. AbstractViewer.prototype._onTemplateLoaded = function () {
  102745. var _this = this;
  102746. // check if viewer was disposed right after created
  102747. if (this._isDisposed) {
  102748. return Promise.reject("viewer was disposed");
  102749. }
  102750. return this._onTemplatesLoaded().then(function () {
  102751. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  102752. return _this._initEngine().then(function (engine) {
  102753. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  102754. }).then(function () {
  102755. _this._initTelemetryEvents();
  102756. if (autoLoad) {
  102757. return _this.loadModel(_this.configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  102758. }
  102759. else {
  102760. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  102761. }
  102762. }).then(function () {
  102763. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  102764. }).catch(function (e) {
  102765. babylonjs_1.Tools.Warn(e.toString());
  102766. return _this;
  102767. });
  102768. });
  102769. };
  102770. /**
  102771. * Initialize the engine. Retruns a promise in case async calls are needed.
  102772. *
  102773. * @protected
  102774. * @returns {Promise<Engine>}
  102775. * @memberof Viewer
  102776. */
  102777. AbstractViewer.prototype._initEngine = function () {
  102778. // init custom shaders
  102779. this._injectCustomShaders();
  102780. //let canvasElement = this.templateManager.getCanvas();
  102781. if (!this.canvas) {
  102782. return Promise.reject('Canvas element not found!');
  102783. }
  102784. var config = this.configuration.engine || {};
  102785. // TDO enable further configuration
  102786. // check for webgl2 support, force-disable if needed.
  102787. if (globals_1.viewerGlobals.disableWebGL2Support) {
  102788. config.engineOptions = config.engineOptions || {};
  102789. config.engineOptions.disableWebGL2Support = true;
  102790. }
  102791. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  102792. // Disable manifest checking
  102793. babylonjs_1.Database.IDBStorageEnabled = false;
  102794. if (!config.disableResize) {
  102795. window.addEventListener('resize', this._resize);
  102796. }
  102797. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  102798. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  102799. this.engine.setHardwareScalingLevel(scale);
  102800. }
  102801. // create a new template manager for this viewer
  102802. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  102803. return Promise.resolve(this.engine);
  102804. };
  102805. /**
  102806. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  102807. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  102808. *
  102809. * @param modelConfig model configuration to use when loading the model.
  102810. * @param clearScene should the scene be cleared before loading this model
  102811. * @returns a ViewerModel object that is not yet fully loaded.
  102812. */
  102813. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  102814. var _this = this;
  102815. if (clearScene === void 0) { clearScene = true; }
  102816. var configuration;
  102817. if (typeof modelConfig === 'string') {
  102818. configuration = {
  102819. url: modelConfig
  102820. };
  102821. }
  102822. else if (modelConfig instanceof File) {
  102823. configuration = {
  102824. file: modelConfig,
  102825. root: "file:"
  102826. };
  102827. }
  102828. else {
  102829. configuration = modelConfig;
  102830. }
  102831. if (!configuration.url && !configuration.file) {
  102832. throw new Error("no model provided");
  102833. }
  102834. if (clearScene) {
  102835. this.sceneManager.clearScene(true, false);
  102836. }
  102837. //merge the configuration for future models:
  102838. if (this.configuration.model && typeof this.configuration.model === 'object') {
  102839. var globalConfig = _1.deepmerge({}, this.configuration.model);
  102840. configuration = _1.deepmerge(globalConfig, configuration);
  102841. if (modelConfig instanceof File) {
  102842. configuration.file = modelConfig;
  102843. }
  102844. }
  102845. else {
  102846. this.configuration.model = configuration;
  102847. }
  102848. this._isLoading = true;
  102849. var model = this.modelLoader.load(configuration);
  102850. this.lastUsedLoader = model.loader;
  102851. model.onLoadErrorObservable.add(function (errorObject) {
  102852. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  102853. });
  102854. model.onLoadProgressObservable.add(function (progressEvent) {
  102855. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  102856. });
  102857. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  102858. model.onLoadedObservable.add(function () {
  102859. _this._isLoading = false;
  102860. });
  102861. return model;
  102862. };
  102863. /**
  102864. * load a model using the provided configuration.
  102865. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  102866. * If you want to attach to the observables of the model, use initModle instead.
  102867. *
  102868. * @param modelConfig the model configuration or URL to load.
  102869. * @param clearScene Should the scene be cleared before loading the model
  102870. * @returns a Promise the fulfills when the model finished loading successfully.
  102871. */
  102872. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  102873. var _this = this;
  102874. if (clearScene === void 0) { clearScene = true; }
  102875. if (this._isLoading) {
  102876. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  102877. return Promise.reject("another model is curently being loaded.");
  102878. }
  102879. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  102880. if (!scene)
  102881. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  102882. return scene;
  102883. }).then(function () {
  102884. var model = _this.initModel(modelConfig, clearScene);
  102885. return new Promise(function (resolve, reject) {
  102886. // at this point, configuration.model is an object, not a string
  102887. model.onLoadedObservable.add(function () {
  102888. resolve(model);
  102889. });
  102890. model.onLoadErrorObservable.add(function (error) {
  102891. reject(error);
  102892. });
  102893. });
  102894. });
  102895. };
  102896. AbstractViewer.prototype._initTelemetryEvents = function () {
  102897. var _this = this;
  102898. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  102899. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  102900. userAgent: navigator.userAgent,
  102901. platform: navigator.platform
  102902. });
  102903. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  102904. var trackFPS = function () {
  102905. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  102906. };
  102907. trackFPS();
  102908. // Track the FPS again after 60 seconds
  102909. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  102910. };
  102911. /**
  102912. * Injects all the spectre shader in the babylon shader store
  102913. */
  102914. AbstractViewer.prototype._injectCustomShaders = function () {
  102915. var customShaders = this.configuration.customShaders;
  102916. // Inject all the spectre shader in the babylon shader store.
  102917. if (!customShaders) {
  102918. return;
  102919. }
  102920. if (customShaders.shaders) {
  102921. Object.keys(customShaders.shaders).forEach(function (key) {
  102922. // typescript considers a callback "unsafe", so... '!'
  102923. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  102924. });
  102925. }
  102926. if (customShaders.includes) {
  102927. Object.keys(customShaders.includes).forEach(function (key) {
  102928. // typescript considers a callback "unsafe", so... '!'
  102929. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  102930. });
  102931. }
  102932. };
  102933. return AbstractViewer;
  102934. }());
  102935. exports.AbstractViewer = AbstractViewer;
  102936. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5RCx1Q0FBbWdCO0FBS25nQixxREFBb0Q7QUFFcEQsb0RBQXlEO0FBRXpELGlFQUFnRTtBQUNoRSwrQkFBdUM7QUFDdkMscUVBQW9FO0FBQ3BFLGtGQUFpRjtBQUNqRixpRUFBZ0U7QUFFaEU7OztHQUdHO0FBQ0g7SUFnSkksd0JBQW1CLGdCQUE2QixFQUFFLG9CQUE4QztRQUE5QyxxQ0FBQSxFQUFBLHlCQUE4QztRQUFoRyxpQkFzQ0M7UUF0Q2tCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQXJIaEQ7O1dBRUc7UUFDSSxrQ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DQUFDLENBQUM7WUFDckUsQ0FBQyxDQUFDLENBQUM7U0FDTjtJQUNMLENBQUM7SUFDTCxxQkFBQztBQUFELENBQUMsQUE5bkJELElBOG5CQztBQTluQnFCLHdDQUFjIn0=
  102937. /***/ }),
  102938. /* 10 */
  102939. /***/ (function(module, exports, __webpack_require__) {
  102940. "use strict";
  102941. function __export(m) {
  102942. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  102943. }
  102944. Object.defineProperty(exports, "__esModule", { value: true });
  102945. __export(__webpack_require__(11));
  102946. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  102947. /***/ }),
  102948. /* 11 */
  102949. /***/ (function(module, exports, __webpack_require__) {
  102950. "use strict";
  102951. Object.defineProperty(exports, "__esModule", { value: true });
  102952. function getConfigurationKey(key, configObject) {
  102953. var splits = key.split('.');
  102954. if (splits.length === 0 || !configObject)
  102955. return;
  102956. else if (splits.length === 1) {
  102957. if (configObject[key] !== undefined) {
  102958. return configObject[key];
  102959. }
  102960. }
  102961. else {
  102962. var firstKey = splits.shift();
  102963. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  102964. }
  102965. }
  102966. exports.getConfigurationKey = getConfigurationKey;
  102967. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  102968. /***/ }),
  102969. /* 12 */
  102970. /***/ (function(module, exports, __webpack_require__) {
  102971. "use strict";
  102972. Object.defineProperty(exports, "__esModule", { value: true });
  102973. var babylonjs_1 = __webpack_require__(0);
  102974. /**
  102975. * A minimal WebGL cubemap descriptor
  102976. */
  102977. var TextureCube = /** @class */ (function () {
  102978. /**
  102979. * constructor
  102980. * @param internalFormat WebGL pixel format for the texture on the GPU
  102981. * @param type WebGL pixel type of the supplied data and texture on the GPU
  102982. * @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
  102983. */
  102984. function TextureCube(internalFormat, type, source) {
  102985. if (source === void 0) { source = []; }
  102986. this.internalFormat = internalFormat;
  102987. this.type = type;
  102988. this.source = source;
  102989. }
  102990. Object.defineProperty(TextureCube.prototype, "Width", {
  102991. /**
  102992. * Returns the width of a face of the texture or 0 if not available
  102993. */
  102994. get: function () {
  102995. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  102996. },
  102997. enumerable: true,
  102998. configurable: true
  102999. });
  103000. Object.defineProperty(TextureCube.prototype, "Height", {
  103001. /**
  103002. * Returns the height of a face of the texture or 0 if not available
  103003. */
  103004. get: function () {
  103005. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  103006. },
  103007. enumerable: true,
  103008. configurable: true
  103009. });
  103010. return TextureCube;
  103011. }());
  103012. exports.TextureCube = TextureCube;
  103013. /**
  103014. * A static class providing methods to aid working with Bablyon textures.
  103015. */
  103016. var TextureUtils = /** @class */ (function () {
  103017. function TextureUtils() {
  103018. }
  103019. /**
  103020. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  103021. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  103022. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  103023. * @param scene A Babylon Scene instance
  103024. * @param textureCube A Spectre TextureCube object
  103025. * @param parameters WebGL texture sampling parameters
  103026. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  103027. * @param environment Specifies that the texture will be used as an environment
  103028. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  103029. * @return Babylon cube texture
  103030. */
  103031. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  103032. if (environment === void 0) { environment = false; }
  103033. if (singleLod === void 0) { singleLod = false; }
  103034. if (!textureCube)
  103035. throw new Error("no texture cube provided");
  103036. var parameters;
  103037. if (environment) {
  103038. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  103039. }
  103040. else {
  103041. parameters = {
  103042. magFilter: 9728 /* NEAREST */,
  103043. minFilter: 9728 /* NEAREST */,
  103044. wrapS: 33071 /* CLAMP_TO_EDGE */,
  103045. wrapT: 33071 /* CLAMP_TO_EDGE */
  103046. };
  103047. }
  103048. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  103049. var babylonTexture = textureCube[key];
  103050. if (!babylonTexture) {
  103051. //initialize babylon texture
  103052. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  103053. if (environment) {
  103054. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  103055. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  103056. }
  103057. babylonTexture.gammaSpace = false;
  103058. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  103059. var glTexture_1 = internalTexture_1._webGLTexture;
  103060. //babylon properties
  103061. internalTexture_1.isCube = true;
  103062. internalTexture_1.generateMipMaps = false;
  103063. babylonTexture._texture = internalTexture_1;
  103064. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  103065. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  103066. var texturesUploaded_1 = 0;
  103067. var textureComplete = function () {
  103068. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  103069. };
  103070. var uploadFace = function (i, level, face) {
  103071. if (!glTexture_1)
  103072. return;
  103073. if (i === 0 && level === 0) {
  103074. internalTexture_1.width = face.width;
  103075. internalTexture_1.height = face.height;
  103076. }
  103077. var gl = (scene.getEngine())._gl;
  103078. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  103079. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  103080. if (face instanceof HTMLElement || face instanceof ImageData) {
  103081. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  103082. }
  103083. else {
  103084. var textureData = face;
  103085. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  103086. }
  103087. texturesUploaded_1++;
  103088. if (textureComplete()) {
  103089. //generate mipmaps
  103090. if (automaticMipmaps) {
  103091. var w = face.width;
  103092. var h = face.height;
  103093. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  103094. if (isPot) {
  103095. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  103096. }
  103097. }
  103098. // Upload Separate lods in case there is no support for texture lod.
  103099. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  103100. var mipSlices = 3;
  103101. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  103102. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  103103. var lod = textureCube[lodKey];
  103104. //initialize lod texture if it doesn't already exist
  103105. if (lod == null && textureCube.Width) {
  103106. //compute LOD from even spacing in smoothness (matching shader calculation)
  103107. var smoothness = i_1 / (mipSlices - 1);
  103108. var roughness = 1 - smoothness;
  103109. var kMinimumVariance = 0.0005;
  103110. var alphaG = roughness * roughness + kMinimumVariance;
  103111. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  103112. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  103113. var maxLODIndex = textureCube.source.length - 1;
  103114. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  103115. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  103116. if (i_1 === 0) {
  103117. internalTexture_1._lodTextureLow = lod;
  103118. }
  103119. else if (i_1 === 1) {
  103120. internalTexture_1._lodTextureMid = lod;
  103121. }
  103122. else {
  103123. internalTexture_1._lodTextureHigh = lod;
  103124. }
  103125. textureCube[lodKey] = lod;
  103126. }
  103127. }
  103128. }
  103129. internalTexture_1.isReady = true;
  103130. }
  103131. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  103132. scene.getEngine().resetTextureCache();
  103133. };
  103134. var _loop_1 = function (i) {
  103135. var faces = textureCube.source[i];
  103136. var _loop_2 = function (j) {
  103137. var face = faces[j];
  103138. if (face instanceof HTMLImageElement && !face.complete) {
  103139. face.addEventListener('load', function () {
  103140. uploadFace(j, i, face);
  103141. }, false);
  103142. }
  103143. else {
  103144. uploadFace(j, i, face);
  103145. }
  103146. };
  103147. for (var j = 0; j < faces.length; j++) {
  103148. _loop_2(j);
  103149. }
  103150. };
  103151. for (var i = 0; i <= maxMipLevel_1; i++) {
  103152. _loop_1(i);
  103153. }
  103154. scene.getEngine().resetTextureCache();
  103155. babylonTexture.isReady = function () {
  103156. return textureComplete();
  103157. };
  103158. textureCube[key] = babylonTexture;
  103159. }
  103160. return babylonTexture;
  103161. };
  103162. /**
  103163. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  103164. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  103165. * @param parameters Spectre SamplingParameters to apply
  103166. */
  103167. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  103168. var scene = babylonTexture.getScene();
  103169. if (!scene)
  103170. return;
  103171. var gl = (scene.getEngine())._gl;
  103172. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  103173. var internalTexture = babylonTexture._texture;
  103174. if (!internalTexture)
  103175. return;
  103176. var glTexture = internalTexture._webGLTexture;
  103177. gl.bindTexture(target, glTexture);
  103178. if (parameters.magFilter != null)
  103179. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  103180. if (parameters.minFilter != null)
  103181. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  103182. if (parameters.wrapS != null)
  103183. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  103184. if (parameters.wrapT != null)
  103185. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  103186. //set babylon wrap modes from sampling parameter
  103187. switch (parameters.wrapS) {
  103188. case 10497 /* REPEAT */:
  103189. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  103190. break;
  103191. case 33071 /* CLAMP_TO_EDGE */:
  103192. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  103193. break;
  103194. case 33648 /* MIRRORED_REPEAT */:
  103195. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  103196. break;
  103197. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  103198. }
  103199. switch (parameters.wrapT) {
  103200. case 10497 /* REPEAT */:
  103201. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  103202. break;
  103203. case 33071 /* CLAMP_TO_EDGE */:
  103204. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  103205. break;
  103206. case 33648 /* MIRRORED_REPEAT */:
  103207. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  103208. break;
  103209. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  103210. }
  103211. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  103212. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  103213. if (anisotropicExt) {
  103214. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  103215. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  103216. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  103217. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  103218. }
  103219. }
  103220. gl.bindTexture(target, null);
  103221. scene.getEngine().resetTextureCache();
  103222. };
  103223. /**
  103224. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  103225. */
  103226. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  103227. /**
  103228. * Controls anisotropic filtering for deserialized textures.
  103229. */
  103230. TextureUtils.MaxAnisotropy = 4;
  103231. TextureUtils._EnvironmentSampling = {
  103232. magFilter: 9729 /* LINEAR */,
  103233. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  103234. wrapS: 33071 /* CLAMP_TO_EDGE */,
  103235. wrapT: 33071 /* CLAMP_TO_EDGE */,
  103236. maxAnisotropy: 1
  103237. };
  103238. TextureUtils._EnvironmentSingleMipSampling = {
  103239. magFilter: 9729 /* LINEAR */,
  103240. minFilter: 9729 /* LINEAR */,
  103241. wrapS: 33071 /* CLAMP_TO_EDGE */,
  103242. wrapT: 33071 /* CLAMP_TO_EDGE */,
  103243. maxAnisotropy: 1
  103244. };
  103245. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  103246. /**
  103247. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  103248. */
  103249. TextureUtils.EnvironmentLODScale = 0.8;
  103250. /**
  103251. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  103252. */
  103253. TextureUtils.EnvironmentLODOffset = 1.0;
  103254. return TextureUtils;
  103255. }());
  103256. exports.TextureUtils = TextureUtils;
  103257. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV4dHVyZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3RleHR1cmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBOEY7QUFrSTlGOztHQUVHO0FBQ0g7SUFnQkk7Ozs7O09BS0c7SUFDSCxxQkFBbUIsY0FBMkIsRUFBUyxJQUFlLEVBQVMsTUFBd0I7UUFBeEIsdUJBQUEsRUFBQSxXQUF3Qj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nQkFDbkYsY0FBYyxDQUFDLHlCQUF5QixHQUFHLGFBQWEsQ0FBQzthQUM1RDtTQUNKO1FBRUQsRUFBRSxDQUFDLFdBQVcsQ0FBQyxNQUFNLEVBQUUsSUFBSSxDQUFDLENBQUM7UUFDN0IsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLGlCQUFpQixFQUFFLENBQUM7SUFDMUMsQ0FBQztJQTdORDs7T0FFRztJQUNXLG9DQUF1QixHQUFHLG1CQUFtQixDQUFDO0lBRTVEOztPQUVHO0lBQ1csMEJBQWEsR0FBRyxDQUFDLENBQUM7SUF1TmpCLGlDQUFvQixHQUF1QjtRQUN0RCxTQUFTLG1CQUF5QjtRQUNsQyxTQUFTLGlDQUF1QztRQUNoRCxLQUFLLDJCQUErQjtRQUNwQyxLQUFLLDJCQUErQjtRQUNwQyxhQUFhLEVBQUUsQ0FBQztLQUNuQixDQUFDO0lBRWEsMENBQTZCLEdBQXVCO1FBQy9ELFNBQVMsbUJBQXlCO1FBQ2xDLFNBQVMsbUJBQXlCO1FBQ2xDLEtBQUssMkJBQStCO1FBQ3BDLEtBQUssMkJBQStCO1FBQ3BDLGFBQWEsRUFBRSxDQUFDO0tBQ25CLENBQUM7SUFFRixnRkFBZ0Y7SUFDaEY7O09BRUc7SUFDVyxnQ0FBbUIsR0FBRyxHQUFHLENBQUM7SUFDeEM7O09BRUc7SUFDVyxpQ0FBb0IsR0FBRyxHQUFHLENBQUM7SUFDN0MsbUJBQUM7Q0FBQSxBQTFQRCxJQTBQQztBQTFQWSxvQ0FBWSJ9
  103258. /***/ }),
  103259. /* 13 */
  103260. /***/ (function(module, exports, __webpack_require__) {
  103261. "use strict";
  103262. Object.defineProperty(exports, "__esModule", { value: true });
  103263. var babylonjs_1 = __webpack_require__(0);
  103264. var babylonjs_loaders_1 = __webpack_require__(14);
  103265. var viewerModel_1 = __webpack_require__(5);
  103266. var _1 = __webpack_require__(54);
  103267. /**
  103268. * An instance of the class is in charge of loading the model correctly.
  103269. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  103270. *
  103271. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  103272. */
  103273. var ModelLoader = /** @class */ (function () {
  103274. /**
  103275. * Create a new Model loader
  103276. * @param _viewer the viewer using this model loader
  103277. */
  103278. function ModelLoader(_observablesManager, _configurationContainer) {
  103279. this._observablesManager = _observablesManager;
  103280. this._configurationContainer = _configurationContainer;
  103281. this._disposed = false;
  103282. this._loaders = [];
  103283. this._loadId = 0;
  103284. this._plugins = [];
  103285. }
  103286. /**
  103287. * Adds a new plugin to the loader process.
  103288. *
  103289. * @param plugin the plugin name or the plugin itself
  103290. */
  103291. ModelLoader.prototype.addPlugin = function (plugin) {
  103292. var actualPlugin = {};
  103293. if (typeof plugin === 'string') {
  103294. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  103295. if (loadedPlugin) {
  103296. actualPlugin = loadedPlugin;
  103297. }
  103298. }
  103299. else {
  103300. actualPlugin = plugin;
  103301. }
  103302. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  103303. this._plugins.push(actualPlugin);
  103304. }
  103305. };
  103306. /**
  103307. * Load a model using predefined configuration
  103308. * @param modelConfiguration the modelConfiguration to use to load the model
  103309. */
  103310. ModelLoader.prototype.load = function (modelConfiguration) {
  103311. var _this = this;
  103312. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration);
  103313. model.loadId = this._loadId++;
  103314. if (!modelConfiguration.url) {
  103315. model.state = viewerModel_1.ModelState.ERROR;
  103316. babylonjs_1.Tools.Error("No URL provided");
  103317. return model;
  103318. }
  103319. var base;
  103320. var filename;
  103321. if (modelConfiguration.file) {
  103322. base = "file:";
  103323. filename = modelConfiguration.file;
  103324. }
  103325. else {
  103326. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  103327. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  103328. }
  103329. var plugin = modelConfiguration.loader;
  103330. var scene = model.rootMesh.getScene();
  103331. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  103332. meshes.forEach(function (mesh) {
  103333. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  103334. model.addMesh(mesh);
  103335. });
  103336. model.particleSystems = particleSystems;
  103337. model.skeletons = skeletons;
  103338. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  103339. var animationGroup = animationGroups_1[_i];
  103340. model.addAnimationGroup(animationGroup);
  103341. }
  103342. _this._checkAndRun("onLoaded", model);
  103343. scene.executeWhenReady(function () {
  103344. model.onLoadedObservable.notifyObservers(model);
  103345. });
  103346. }, function (progressEvent) {
  103347. _this._checkAndRun("onProgress", progressEvent);
  103348. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  103349. }, function (scene, m, exception) {
  103350. model.state = viewerModel_1.ModelState.ERROR;
  103351. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  103352. _this._checkAndRun("onError", m, exception);
  103353. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  103354. }, plugin);
  103355. if (model.loader.name === "gltf") {
  103356. var gltfLoader_1 = model.loader;
  103357. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  103358. gltfLoader_1.compileMaterials = true;
  103359. if (!modelConfiguration.file) {
  103360. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  103361. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  103362. };
  103363. }
  103364. // if ground is set to "mirror":
  103365. if (this._configurationContainer
  103366. && this._configurationContainer.configuration
  103367. && this._configurationContainer.configuration.ground
  103368. && typeof this._configurationContainer.configuration.ground === 'object'
  103369. && this._configurationContainer.configuration.ground.mirror) {
  103370. gltfLoader_1.useClipPlane = true;
  103371. }
  103372. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  103373. gltfLoader_1[functionName].add(function (payload) {
  103374. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  103375. });
  103376. });
  103377. gltfLoader_1.onParsedObservable.add(function (data) {
  103378. if (data && data.json && data.json['asset']) {
  103379. model.loadInfo = data.json['asset'];
  103380. }
  103381. });
  103382. gltfLoader_1.onCompleteObservable.add(function () {
  103383. model.loaderDone = true;
  103384. });
  103385. }
  103386. else {
  103387. model.loaderDone = true;
  103388. }
  103389. this._checkAndRun("onInit", model.loader, model);
  103390. this._loaders.push(model.loader);
  103391. return model;
  103392. };
  103393. ModelLoader.prototype.cancelLoad = function (model) {
  103394. var loader = model.loader || this._loaders[model.loadId];
  103395. // ATM only available in the GLTF Loader
  103396. if (loader && loader.name === "gltf") {
  103397. var gltfLoader = loader;
  103398. gltfLoader.dispose();
  103399. model.state = viewerModel_1.ModelState.CANCELED;
  103400. }
  103401. else {
  103402. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  103403. }
  103404. };
  103405. /**
  103406. * dispose the model loader.
  103407. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  103408. */
  103409. ModelLoader.prototype.dispose = function () {
  103410. this._loaders.forEach(function (loader) {
  103411. if (loader.name === "gltf") {
  103412. loader.dispose();
  103413. }
  103414. });
  103415. this._loaders.length = 0;
  103416. this._disposed = true;
  103417. };
  103418. ModelLoader.prototype._checkAndRun = function (functionName) {
  103419. var _this = this;
  103420. var payload = [];
  103421. for (var _i = 1; _i < arguments.length; _i++) {
  103422. payload[_i - 1] = arguments[_i];
  103423. }
  103424. if (this._disposed)
  103425. return;
  103426. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  103427. try {
  103428. plugin[functionName].apply(_this, payload);
  103429. }
  103430. catch (e) { }
  103431. });
  103432. };
  103433. return ModelLoader;
  103434. }());
  103435. exports.ModelLoader = ModelLoader;
  103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UEsTUFBTTtZQUN4QixJQUFJLE1BQU0sQ0FBQyxJQUFJLEtBQUssTUFBTSxFQUFFO2dCQUNQLE1BQU8sQ0FBQyxPQUFPLEVBQUUsQ0FBQzthQUN0QztRQUNMLENBQUMsQ0FBQyxDQUFDO1FBQ0gsSUFBSSxDQUFDLFFBQVEsQ0FBQyxNQUFNLEdBQUcsQ0FBQyxDQUFDO1FBQ3pCLElBQUksQ0FBQyxTQUFTLEdBQUcsSUFBSSxDQUFDO0lBQzFCLENBQUM7SUFFTyxrQ0FBWSxHQUFwQixVQUFxQixZQUFvQjtRQUF6QyxpQkFPQztRQVAwQyxpQkFBc0I7YUFBdEIsVUFBc0IsRUFBdEIscUJBQXNCLEVBQXRCLElBQXNCO1lBQXRCLGdDQUFzQjs7UUFDN0QsSUFBSSxJQUFJLENBQUMsU0FBUztZQUFFLE9BQU87UUFDM0IsSUFBSSxDQUFDLFFBQVEsQ0FBQyxNQUFNLENBQUMsVUFBQSxDQUFDLElBQUksT0FBQSxDQUFDLENBQUMsWUFBWSxDQUFDLEVBQWYsQ0FBZSxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsTUFBTTtZQUNyRCxJQUFJO2dCQUNBLE1BQU0sQ0FBQyxZQUFZLENBQUMsQ0FBQyxLQUFLLENBQUMsS0FBSSxFQUFFLE9BQU8sQ0FBQyxDQUFDO2FBQzdDO1lBQUMsT0FBTyxDQUFDLEVBQUUsR0FBRztRQUNuQixDQUFDLENBQUMsQ0FBQTtJQUNOLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFoTEQsSUFnTEM7QUFoTFksa0NBQVcifQ==
  103437. /***/ }),
  103438. /* 14 */
  103439. /***/ (function(module, exports, __webpack_require__) {
  103440. (function universalModuleDefinition(root, factory) {
  103441. var amdDependencies = [];
  103442. var BABYLON = root.BABYLON || this.BABYLON;
  103443. if(true) {
  103444. BABYLON = BABYLON || __webpack_require__(0);
  103445. module.exports = factory(BABYLON);
  103446. } else if(typeof define === 'function' && define.amd) {
  103447. amdDependencies.push("babylonjs");
  103448. define("babylonjs-loaders", amdDependencies, factory);
  103449. } else if(typeof exports === 'object') {
  103450. BABYLON = BABYLON || require("babylonjs");
  103451. exports["babylonjs-loaders"] = factory(BABYLON);
  103452. } else {
  103453. root["BABYLON"] = factory(BABYLON);
  103454. }
  103455. })(this, function(BABYLON) {
  103456. BABYLON = BABYLON || this.BABYLON;
  103457. 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};
  103458. 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)}}();
  103459. var BABYLON;
  103460. (function (BABYLON) {
  103461. var STLFileLoader = /** @class */ (function () {
  103462. function STLFileLoader() {
  103463. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  103464. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  103465. 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;
  103466. 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;
  103467. this.name = "stl";
  103468. // force data to come in as an ArrayBuffer
  103469. // we'll convert to string if it looks like it's an ASCII .stl
  103470. this.extensions = {
  103471. ".stl": { isBinary: true },
  103472. };
  103473. }
  103474. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103475. var matches;
  103476. if (this.isBinary(data)) {
  103477. // binary .stl
  103478. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  103479. this.parseBinary(babylonMesh, data);
  103480. if (meshes) {
  103481. meshes.push(babylonMesh);
  103482. }
  103483. return true;
  103484. }
  103485. // ASCII .stl
  103486. // convert to string
  103487. var array_buffer = new Uint8Array(data);
  103488. var str = '';
  103489. for (var i = 0; i < data.byteLength; i++) {
  103490. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  103491. }
  103492. data = str;
  103493. while (matches = this.solidPattern.exec(data)) {
  103494. var meshName = matches[1];
  103495. var meshNameFromEnd = matches[3];
  103496. if (meshName != meshNameFromEnd) {
  103497. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  103498. return false;
  103499. }
  103500. // check meshesNames
  103501. if (meshesNames && meshName) {
  103502. if (meshesNames instanceof Array) {
  103503. if (!meshesNames.indexOf(meshName)) {
  103504. continue;
  103505. }
  103506. }
  103507. else {
  103508. if (meshName !== meshesNames) {
  103509. continue;
  103510. }
  103511. }
  103512. }
  103513. // stl mesh name can be empty as well
  103514. meshName = meshName || "stlmesh";
  103515. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  103516. this.parseASCII(babylonMesh, matches[2]);
  103517. if (meshes) {
  103518. meshes.push(babylonMesh);
  103519. }
  103520. }
  103521. return true;
  103522. };
  103523. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  103524. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  103525. if (result) {
  103526. scene.createDefaultCameraOrLight();
  103527. }
  103528. return result;
  103529. };
  103530. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103531. var container = new BABYLON.AssetContainer(scene);
  103532. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103533. container.removeAllFromScene();
  103534. return container;
  103535. };
  103536. STLFileLoader.prototype.isBinary = function (data) {
  103537. // check if file size is correct for binary stl
  103538. var faceSize, nFaces, reader;
  103539. reader = new DataView(data);
  103540. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  103541. nFaces = reader.getUint32(80, true);
  103542. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  103543. return true;
  103544. }
  103545. // check characters higher than ASCII to confirm binary
  103546. var fileLength = reader.byteLength;
  103547. for (var index = 0; index < fileLength; index++) {
  103548. if (reader.getUint8(index) > 127) {
  103549. return true;
  103550. }
  103551. }
  103552. return false;
  103553. };
  103554. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  103555. var reader = new DataView(data);
  103556. var faces = reader.getUint32(80, true);
  103557. var dataOffset = 84;
  103558. var faceLength = 12 * 4 + 2;
  103559. var offset = 0;
  103560. var positions = new Float32Array(faces * 3 * 3);
  103561. var normals = new Float32Array(faces * 3 * 3);
  103562. var indices = new Uint32Array(faces * 3);
  103563. var indicesCount = 0;
  103564. for (var face = 0; face < faces; face++) {
  103565. var start = dataOffset + face * faceLength;
  103566. var normalX = reader.getFloat32(start, true);
  103567. var normalY = reader.getFloat32(start + 4, true);
  103568. var normalZ = reader.getFloat32(start + 8, true);
  103569. for (var i = 1; i <= 3; i++) {
  103570. var vertexstart = start + i * 12;
  103571. // ordering is intentional to match ascii import
  103572. positions[offset] = reader.getFloat32(vertexstart, true);
  103573. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  103574. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  103575. normals[offset] = normalX;
  103576. normals[offset + 2] = normalY;
  103577. normals[offset + 1] = normalZ;
  103578. offset += 3;
  103579. }
  103580. indices[indicesCount] = indicesCount++;
  103581. indices[indicesCount] = indicesCount++;
  103582. indices[indicesCount] = indicesCount++;
  103583. }
  103584. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103585. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103586. mesh.setIndices(indices);
  103587. mesh.computeWorldMatrix(true);
  103588. };
  103589. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  103590. var positions = [];
  103591. var normals = [];
  103592. var indices = [];
  103593. var indicesCount = 0;
  103594. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  103595. var matches;
  103596. while (matches = this.facetsPattern.exec(solidData)) {
  103597. var facet = matches[1];
  103598. //one normal per face
  103599. var normalMatches = this.normalPattern.exec(facet);
  103600. this.normalPattern.lastIndex = 0;
  103601. if (!normalMatches) {
  103602. continue;
  103603. }
  103604. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  103605. var vertexMatch;
  103606. while (vertexMatch = this.vertexPattern.exec(facet)) {
  103607. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  103608. normals.push(normal[0], normal[1], normal[2]);
  103609. }
  103610. indices.push(indicesCount++, indicesCount++, indicesCount++);
  103611. this.vertexPattern.lastIndex = 0;
  103612. }
  103613. this.facetsPattern.lastIndex = 0;
  103614. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  103615. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  103616. mesh.setIndices(indices);
  103617. mesh.computeWorldMatrix(true);
  103618. };
  103619. return STLFileLoader;
  103620. }());
  103621. BABYLON.STLFileLoader = STLFileLoader;
  103622. if (BABYLON.SceneLoader) {
  103623. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  103624. }
  103625. })(BABYLON || (BABYLON = {}));
  103626. //# sourceMappingURL=babylon.stlFileLoader.js.map
  103627. var BABYLON;
  103628. (function (BABYLON) {
  103629. /**
  103630. * Class reading and parsing the MTL file bundled with the obj file.
  103631. */
  103632. var MTLFileLoader = /** @class */ (function () {
  103633. function MTLFileLoader() {
  103634. // All material loaded from the mtl will be set here
  103635. this.materials = [];
  103636. }
  103637. /**
  103638. * This function will read the mtl file and create each material described inside
  103639. * This function could be improve by adding :
  103640. * -some component missing (Ni, Tf...)
  103641. * -including the specific options available
  103642. *
  103643. * @param scene
  103644. * @param data
  103645. * @param rootUrl
  103646. */
  103647. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  103648. if (data instanceof ArrayBuffer) {
  103649. return;
  103650. }
  103651. //Split the lines from the file
  103652. var lines = data.split('\n');
  103653. //Space char
  103654. var delimiter_pattern = /\s+/;
  103655. //Array with RGB colors
  103656. var color;
  103657. //New material
  103658. var material = null;
  103659. //Look at each line
  103660. for (var i = 0; i < lines.length; i++) {
  103661. var line = lines[i].trim();
  103662. // Blank line or comment
  103663. if (line.length === 0 || line.charAt(0) === '#') {
  103664. continue;
  103665. }
  103666. //Get the first parameter (keyword)
  103667. var pos = line.indexOf(' ');
  103668. var key = (pos >= 0) ? line.substring(0, pos) : line;
  103669. key = key.toLowerCase();
  103670. //Get the data following the key
  103671. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  103672. //This mtl keyword will create the new material
  103673. if (key === "newmtl") {
  103674. //Check if it is the first material.
  103675. // Materials specifications are described after this keyword.
  103676. if (material) {
  103677. //Add the previous material in the material array.
  103678. this.materials.push(material);
  103679. }
  103680. //Create a new material.
  103681. // value is the name of the material read in the mtl file
  103682. material = new BABYLON.StandardMaterial(value, scene);
  103683. }
  103684. else if (key === "kd" && material) {
  103685. // Diffuse color (color under white light) using RGB values
  103686. //value = "r g b"
  103687. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103688. //color = [r,g,b]
  103689. //Set tghe color into the material
  103690. material.diffuseColor = BABYLON.Color3.FromArray(color);
  103691. }
  103692. else if (key === "ka" && material) {
  103693. // Ambient color (color under shadow) using RGB values
  103694. //value = "r g b"
  103695. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103696. //color = [r,g,b]
  103697. //Set tghe color into the material
  103698. material.ambientColor = BABYLON.Color3.FromArray(color);
  103699. }
  103700. else if (key === "ks" && material) {
  103701. // Specular color (color when light is reflected from shiny surface) using RGB values
  103702. //value = "r g b"
  103703. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103704. //color = [r,g,b]
  103705. //Set the color into the material
  103706. material.specularColor = BABYLON.Color3.FromArray(color);
  103707. }
  103708. else if (key === "ke" && material) {
  103709. // Emissive color using RGB values
  103710. color = value.split(delimiter_pattern, 3).map(parseFloat);
  103711. material.emissiveColor = BABYLON.Color3.FromArray(color);
  103712. }
  103713. else if (key === "ns" && material) {
  103714. //value = "Integer"
  103715. material.specularPower = parseFloat(value);
  103716. }
  103717. else if (key === "d" && material) {
  103718. //d is dissolve for current material. It mean alpha for BABYLON
  103719. material.alpha = parseFloat(value);
  103720. //Texture
  103721. //This part can be improved by adding the possible options of texture
  103722. }
  103723. else if (key === "map_ka" && material) {
  103724. // ambient texture map with a loaded image
  103725. //We must first get the folder of the image
  103726. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103727. }
  103728. else if (key === "map_kd" && material) {
  103729. // Diffuse texture map with a loaded image
  103730. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103731. }
  103732. else if (key === "map_ks" && material) {
  103733. // Specular texture map with a loaded image
  103734. //We must first get the folder of the image
  103735. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103736. }
  103737. else if (key === "map_ns") {
  103738. //Specular
  103739. //Specular highlight component
  103740. //We must first get the folder of the image
  103741. //
  103742. //Not supported by BABYLON
  103743. //
  103744. // continue;
  103745. }
  103746. else if (key === "map_bump" && material) {
  103747. //The bump texture
  103748. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103749. }
  103750. else if (key === "map_d" && material) {
  103751. // The dissolve of the material
  103752. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  103753. //Options for illumination
  103754. }
  103755. else if (key === "illum") {
  103756. //Illumination
  103757. if (value === "0") {
  103758. //That mean Kd == Kd
  103759. }
  103760. else if (value === "1") {
  103761. //Color on and Ambient on
  103762. }
  103763. else if (value === "2") {
  103764. //Highlight on
  103765. }
  103766. else if (value === "3") {
  103767. //Reflection on and Ray trace on
  103768. }
  103769. else if (value === "4") {
  103770. //Transparency: Glass on, Reflection: Ray trace on
  103771. }
  103772. else if (value === "5") {
  103773. //Reflection: Fresnel on and Ray trace on
  103774. }
  103775. else if (value === "6") {
  103776. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  103777. }
  103778. else if (value === "7") {
  103779. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  103780. }
  103781. else if (value === "8") {
  103782. //Reflection on and Ray trace off
  103783. }
  103784. else if (value === "9") {
  103785. //Transparency: Glass on, Reflection: Ray trace off
  103786. }
  103787. else if (value === "10") {
  103788. //Casts shadows onto invisible surfaces
  103789. }
  103790. }
  103791. else {
  103792. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  103793. }
  103794. }
  103795. //At the end of the file, add the last material
  103796. if (material) {
  103797. this.materials.push(material);
  103798. }
  103799. };
  103800. /**
  103801. * Gets the texture for the material.
  103802. *
  103803. * If the material is imported from input file,
  103804. * We sanitize the url to ensure it takes the textre from aside the material.
  103805. *
  103806. * @param rootUrl The root url to load from
  103807. * @param value The value stored in the mtl
  103808. * @return The Texture
  103809. */
  103810. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  103811. if (!value) {
  103812. return null;
  103813. }
  103814. var url = rootUrl;
  103815. // Load from input file.
  103816. if (rootUrl === "file:") {
  103817. var lastDelimiter = value.lastIndexOf("\\");
  103818. if (lastDelimiter === -1) {
  103819. lastDelimiter = value.lastIndexOf("/");
  103820. }
  103821. if (lastDelimiter > -1) {
  103822. url += value.substr(lastDelimiter + 1);
  103823. }
  103824. else {
  103825. url += value;
  103826. }
  103827. }
  103828. // Not from input file.
  103829. else {
  103830. url += value;
  103831. }
  103832. return new BABYLON.Texture(url, scene);
  103833. };
  103834. return MTLFileLoader;
  103835. }());
  103836. BABYLON.MTLFileLoader = MTLFileLoader;
  103837. var OBJFileLoader = /** @class */ (function () {
  103838. function OBJFileLoader() {
  103839. this.name = "obj";
  103840. this.extensions = ".obj";
  103841. this.obj = /^o/;
  103842. this.group = /^g/;
  103843. this.mtllib = /^mtllib /;
  103844. this.usemtl = /^usemtl /;
  103845. this.smooth = /^s /;
  103846. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103847. // vn float float float
  103848. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103849. // vt float float
  103850. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  103851. // f vertex vertex vertex ...
  103852. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  103853. // f vertex/uvs vertex/uvs vertex/uvs ...
  103854. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103855. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  103856. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  103857. // f vertex//normal vertex//normal vertex//normal ...
  103858. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  103859. }
  103860. /**
  103861. * Calls synchronously the MTL file attached to this obj.
  103862. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  103863. * Without this function materials are not displayed in the first frame (but displayed after).
  103864. * In consequence it is impossible to get material information in your HTML file
  103865. *
  103866. * @param url The URL of the MTL file
  103867. * @param rootUrl
  103868. * @param onSuccess Callback function to be called when the MTL file is loaded
  103869. * @private
  103870. */
  103871. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  103872. //The complete path to the mtl file
  103873. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  103874. // Loads through the babylon tools to allow fileInput search.
  103875. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  103876. };
  103877. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103878. //get the meshes from OBJ file
  103879. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  103880. //Push meshes from OBJ file into the variable mesh of this function
  103881. if (meshes) {
  103882. loadedMeshes.forEach(function (mesh) {
  103883. meshes.push(mesh);
  103884. });
  103885. }
  103886. return true;
  103887. };
  103888. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  103889. //Get the 3D model
  103890. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  103891. };
  103892. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  103893. var container = new BABYLON.AssetContainer(scene);
  103894. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  103895. container.removeAllFromScene();
  103896. return container;
  103897. };
  103898. /**
  103899. * Read the OBJ file and create an Array of meshes.
  103900. * Each mesh contains all information given by the OBJ and the MTL file.
  103901. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  103902. *
  103903. * @param meshesNames
  103904. * @param scene BABYLON.Scene The scene where are displayed the data
  103905. * @param data String The content of the obj file
  103906. * @param rootUrl String The path to the folder
  103907. * @returns Array<AbstractMesh>
  103908. * @private
  103909. */
  103910. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  103911. var positions = []; //values for the positions of vertices
  103912. var normals = []; //Values for the normals
  103913. var uvs = []; //Values for the textures
  103914. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  103915. var handledMesh; //The current mesh of meshes array
  103916. var indicesForBabylon = []; //The list of indices for VertexData
  103917. var wrappedPositionForBabylon = []; //The list of position in vectors
  103918. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  103919. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  103920. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  103921. var curPositionInIndices = 0;
  103922. var hasMeshes = false; //Meshes are defined in the file
  103923. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  103924. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  103925. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  103926. var triangles = []; //Indices from new triangles coming from polygons
  103927. var materialNameFromObj = ""; //The name of the current material
  103928. var fileToLoad = ""; //The name of the mtlFile to load
  103929. var materialsFromMTLFile = new MTLFileLoader();
  103930. var objMeshName = ""; //The name of the current obj mesh
  103931. var increment = 1; //Id for meshes created by the multimaterial
  103932. var isFirstMaterial = true;
  103933. /**
  103934. * Search for obj in the given array.
  103935. * This function is called to check if a couple of data already exists in an array.
  103936. *
  103937. * If found, returns the index of the founded tuple index. Returns -1 if not found
  103938. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  103939. * @param obj Array<number>
  103940. * @returns {boolean}
  103941. */
  103942. var isInArray = function (arr, obj) {
  103943. if (!arr[obj[0]])
  103944. arr[obj[0]] = { normals: [], idx: [] };
  103945. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  103946. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  103947. };
  103948. var isInArrayUV = function (arr, obj) {
  103949. if (!arr[obj[0]])
  103950. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  103951. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  103952. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  103953. return arr[obj[0]].idx[idx];
  103954. }
  103955. return -1;
  103956. };
  103957. /**
  103958. * This function set the data for each triangle.
  103959. * Data are position, normals and uvs
  103960. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  103961. * If the tuple already exist, add only their indice
  103962. *
  103963. * @param indicePositionFromObj Integer The index in positions array
  103964. * @param indiceUvsFromObj Integer The index in uvs array
  103965. * @param indiceNormalFromObj Integer The index in normals array
  103966. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  103967. * @param textureVectorFromOBJ Vector3 The value of uvs
  103968. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  103969. */
  103970. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  103971. //Check if this tuple already exists in the list of tuples
  103972. var _index;
  103973. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  103974. _index = isInArrayUV(tuplePosNorm, [
  103975. indicePositionFromObj,
  103976. indiceNormalFromObj,
  103977. indiceUvsFromObj
  103978. ]);
  103979. }
  103980. else {
  103981. _index = isInArray(tuplePosNorm, [
  103982. indicePositionFromObj,
  103983. indiceNormalFromObj
  103984. ]);
  103985. }
  103986. //If it not exists
  103987. if (_index == -1) {
  103988. //Add an new indice.
  103989. //The array of indices is only an array with his length equal to the number of triangles - 1.
  103990. //We add vertices data in this order
  103991. indicesForBabylon.push(wrappedPositionForBabylon.length);
  103992. //Push the position of vertice for Babylon
  103993. //Each element is a BABYLON.Vector3(x,y,z)
  103994. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  103995. //Push the uvs for Babylon
  103996. //Each element is a BABYLON.Vector3(u,v)
  103997. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  103998. //Push the normals for Babylon
  103999. //Each element is a BABYLON.Vector3(x,y,z)
  104000. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  104001. //Add the tuple in the comparison list
  104002. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  104003. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  104004. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  104005. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  104006. }
  104007. else {
  104008. //The tuple already exists
  104009. //Add the index of the already existing tuple
  104010. //At this index we can get the value of position, normal and uvs of vertex
  104011. indicesForBabylon.push(_index);
  104012. }
  104013. };
  104014. /**
  104015. * Transform BABYLON.Vector() object onto 3 digits in an array
  104016. */
  104017. var unwrapData = function () {
  104018. //Every array has the same length
  104019. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  104020. //Push the x, y, z values of each element in the unwrapped array
  104021. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  104022. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  104023. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  104024. }
  104025. // Reset arrays for the next new meshes
  104026. wrappedPositionForBabylon = [];
  104027. wrappedNormalsForBabylon = [];
  104028. wrappedUvsForBabylon = [];
  104029. tuplePosNorm = [];
  104030. curPositionInIndices = 0;
  104031. };
  104032. /**
  104033. * Create triangles from polygons by recursion
  104034. * The best to understand how it works is to draw it in the same time you get the recursion.
  104035. * It is important to notice that a triangle is a polygon
  104036. * We get 4 patterns of face defined in OBJ File :
  104037. * facePattern1 = ["1","2","3","4","5","6"]
  104038. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  104039. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  104040. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  104041. * Each pattern is divided by the same method
  104042. * @param face Array[String] The indices of elements
  104043. * @param v Integer The variable to increment
  104044. */
  104045. var getTriangles = function (face, v) {
  104046. //Work for each element of the array
  104047. if (v + 1 < face.length) {
  104048. //Add on the triangle variable the indexes to obtain triangles
  104049. triangles.push(face[0], face[v], face[v + 1]);
  104050. //Incrementation for recursion
  104051. v += 1;
  104052. //Recursion
  104053. getTriangles(face, v);
  104054. }
  104055. //Result obtained after 2 iterations:
  104056. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  104057. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  104058. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  104059. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  104060. };
  104061. /**
  104062. * Create triangles and push the data for each polygon for the pattern 1
  104063. * In this pattern we get vertice positions
  104064. * @param face
  104065. * @param v
  104066. */
  104067. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  104068. //Get the indices of triangles for each polygon
  104069. getTriangles(face, v);
  104070. //For each element in the triangles array.
  104071. //This var could contains 1 to an infinity of triangles
  104072. for (var k = 0; k < triangles.length; k++) {
  104073. // Set position indice
  104074. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  104075. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  104076. positions[indicePositionFromObj], //Get the vectors data
  104077. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  104078. );
  104079. }
  104080. //Reset variable for the next line
  104081. triangles = [];
  104082. };
  104083. /**
  104084. * Create triangles and push the data for each polygon for the pattern 2
  104085. * In this pattern we get vertice positions and uvsu
  104086. * @param face
  104087. * @param v
  104088. */
  104089. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  104090. //Get the indices of triangles for each polygon
  104091. getTriangles(face, v);
  104092. for (var k = 0; k < triangles.length; k++) {
  104093. //triangle[k] = "1/1"
  104094. //Split the data for getting position and uv
  104095. var point = triangles[k].split("/"); // ["1", "1"]
  104096. //Set position indice
  104097. var indicePositionFromObj = parseInt(point[0]) - 1;
  104098. //Set uv indice
  104099. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104100. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  104101. positions[indicePositionFromObj], //Get the values for each element
  104102. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  104103. );
  104104. }
  104105. //Reset variable for the next line
  104106. triangles = [];
  104107. };
  104108. /**
  104109. * Create triangles and push the data for each polygon for the pattern 3
  104110. * In this pattern we get vertice positions, uvs and normals
  104111. * @param face
  104112. * @param v
  104113. */
  104114. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  104115. //Get the indices of triangles for each polygon
  104116. getTriangles(face, v);
  104117. for (var k = 0; k < triangles.length; k++) {
  104118. //triangle[k] = "1/1/1"
  104119. //Split the data for getting position, uv, and normals
  104120. var point = triangles[k].split("/"); // ["1", "1", "1"]
  104121. // Set position indice
  104122. var indicePositionFromObj = parseInt(point[0]) - 1;
  104123. // Set uv indice
  104124. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104125. // Set normal indice
  104126. var indiceNormalFromObj = parseInt(point[2]) - 1;
  104127. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  104128. );
  104129. }
  104130. //Reset variable for the next line
  104131. triangles = [];
  104132. };
  104133. /**
  104134. * Create triangles and push the data for each polygon for the pattern 4
  104135. * In this pattern we get vertice positions and normals
  104136. * @param face
  104137. * @param v
  104138. */
  104139. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  104140. getTriangles(face, v);
  104141. for (var k = 0; k < triangles.length; k++) {
  104142. //triangle[k] = "1//1"
  104143. //Split the data for getting position and normals
  104144. var point = triangles[k].split("//"); // ["1", "1"]
  104145. // We check indices, and normals
  104146. var indicePositionFromObj = parseInt(point[0]) - 1;
  104147. var indiceNormalFromObj = parseInt(point[1]) - 1;
  104148. setData(indicePositionFromObj, 1, //Default value for uv
  104149. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  104150. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  104151. }
  104152. //Reset variable for the next line
  104153. triangles = [];
  104154. };
  104155. var addPreviousObjMesh = function () {
  104156. //Check if it is not the first mesh. Otherwise we don't have data.
  104157. if (meshesFromObj.length > 0) {
  104158. //Get the previous mesh for applying the data about the faces
  104159. //=> in obj file, faces definition append after the name of the mesh
  104160. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104161. //Set the data into Array for the mesh
  104162. unwrapData();
  104163. // Reverse tab. Otherwise face are displayed in the wrong sens
  104164. indicesForBabylon.reverse();
  104165. //Set the information for the mesh
  104166. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  104167. handledMesh.indices = indicesForBabylon.slice();
  104168. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  104169. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  104170. handledMesh.uvs = unwrappedUVForBabylon.slice();
  104171. //Reset the array for the next mesh
  104172. indicesForBabylon = [];
  104173. unwrappedPositionsForBabylon = [];
  104174. unwrappedNormalsForBabylon = [];
  104175. unwrappedUVForBabylon = [];
  104176. }
  104177. };
  104178. //Main function
  104179. //Split the file into lines
  104180. var lines = data.split('\n');
  104181. //Look at each line
  104182. for (var i = 0; i < lines.length; i++) {
  104183. var line = lines[i].trim();
  104184. var result;
  104185. //Comment or newLine
  104186. if (line.length === 0 || line.charAt(0) === '#') {
  104187. continue;
  104188. //Get information about one position possible for the vertices
  104189. }
  104190. else if ((result = this.vertexPattern.exec(line)) !== null) {
  104191. //Create a Vector3 with the position x, y, z
  104192. //Value of result:
  104193. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104194. //Add the Vector in the list of positions
  104195. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104196. }
  104197. else if ((result = this.normalPattern.exec(line)) !== null) {
  104198. //Create a Vector3 with the normals x, y, z
  104199. //Value of result
  104200. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104201. //Add the Vector in the list of normals
  104202. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104203. }
  104204. else if ((result = this.uvPattern.exec(line)) !== null) {
  104205. //Create a Vector2 with the normals u, v
  104206. //Value of result
  104207. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  104208. //Add the Vector in the list of uvs
  104209. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  104210. //Identify patterns of faces
  104211. //Face could be defined in different type of pattern
  104212. }
  104213. else if ((result = this.facePattern3.exec(line)) !== null) {
  104214. //Value of result:
  104215. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  104216. //Set the data for this face
  104217. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  104218. 1);
  104219. }
  104220. else if ((result = this.facePattern4.exec(line)) !== null) {
  104221. //Value of result:
  104222. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  104223. //Set the data for this face
  104224. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  104225. 1);
  104226. }
  104227. else if ((result = this.facePattern2.exec(line)) !== null) {
  104228. //Value of result:
  104229. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  104230. //Set the data for this face
  104231. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  104232. 1);
  104233. }
  104234. else if ((result = this.facePattern1.exec(line)) !== null) {
  104235. //Value of result
  104236. //["f 1 2 3", "1 2 3"...]
  104237. //Set the data for this face
  104238. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  104239. 1);
  104240. //Define a mesh or an object
  104241. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  104242. }
  104243. else if (this.group.test(line) || this.obj.test(line)) {
  104244. //Create a new mesh corresponding to the name of the group.
  104245. //Definition of the mesh
  104246. var objMesh =
  104247. //Set the name of the current obj mesh
  104248. {
  104249. name: line.substring(2).trim(),
  104250. indices: undefined,
  104251. positions: undefined,
  104252. normals: undefined,
  104253. uvs: undefined,
  104254. materialName: ""
  104255. };
  104256. addPreviousObjMesh();
  104257. //Push the last mesh created with only the name
  104258. meshesFromObj.push(objMesh);
  104259. //Set this variable to indicate that now meshesFromObj has objects defined inside
  104260. hasMeshes = true;
  104261. isFirstMaterial = true;
  104262. increment = 1;
  104263. //Keyword for applying a material
  104264. }
  104265. else if (this.usemtl.test(line)) {
  104266. //Get the name of the material
  104267. materialNameFromObj = line.substring(7).trim();
  104268. //If this new material is in the same mesh
  104269. if (!isFirstMaterial) {
  104270. //Set the data for the previous mesh
  104271. addPreviousObjMesh();
  104272. //Create a new mesh
  104273. var objMesh =
  104274. //Set the name of the current obj mesh
  104275. {
  104276. name: objMeshName + "_mm" + increment.toString(),
  104277. indices: undefined,
  104278. positions: undefined,
  104279. normals: undefined,
  104280. uvs: undefined,
  104281. materialName: materialNameFromObj
  104282. };
  104283. increment++;
  104284. //If meshes are already defined
  104285. meshesFromObj.push(objMesh);
  104286. }
  104287. //Set the material name if the previous line define a mesh
  104288. if (hasMeshes && isFirstMaterial) {
  104289. //Set the material name to the previous mesh (1 material per mesh)
  104290. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  104291. isFirstMaterial = false;
  104292. }
  104293. //Keyword for loading the mtl file
  104294. }
  104295. else if (this.mtllib.test(line)) {
  104296. //Get the name of mtl file
  104297. fileToLoad = line.substring(7).trim();
  104298. //Apply smoothing
  104299. }
  104300. else if (this.smooth.test(line)) {
  104301. // smooth shading => apply smoothing
  104302. //Toda y I don't know it work with babylon and with obj.
  104303. //With the obj file an integer is set
  104304. }
  104305. else {
  104306. //If there is another possibility
  104307. console.log("Unhandled expression at line : " + line);
  104308. }
  104309. }
  104310. //At the end of the file, add the last mesh into the meshesFromObj array
  104311. if (hasMeshes) {
  104312. //Set the data for the last mesh
  104313. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104314. //Reverse indices for displaying faces in the good sens
  104315. indicesForBabylon.reverse();
  104316. //Get the good array
  104317. unwrapData();
  104318. //Set array
  104319. handledMesh.indices = indicesForBabylon;
  104320. handledMesh.positions = unwrappedPositionsForBabylon;
  104321. handledMesh.normals = unwrappedNormalsForBabylon;
  104322. handledMesh.uvs = unwrappedUVForBabylon;
  104323. }
  104324. //If any o or g keyword found, create a mesj with a random id
  104325. if (!hasMeshes) {
  104326. // reverse tab of indices
  104327. indicesForBabylon.reverse();
  104328. //Get positions normals uvs
  104329. unwrapData();
  104330. //Set data for one mesh
  104331. meshesFromObj.push({
  104332. name: BABYLON.Geometry.RandomId(),
  104333. indices: indicesForBabylon,
  104334. positions: unwrappedPositionsForBabylon,
  104335. normals: unwrappedNormalsForBabylon,
  104336. uvs: unwrappedUVForBabylon,
  104337. materialName: materialNameFromObj
  104338. });
  104339. }
  104340. //Create a BABYLON.Mesh list
  104341. var babylonMeshesArray = []; //The mesh for babylon
  104342. var materialToUse = new Array();
  104343. //Set data for each mesh
  104344. for (var j = 0; j < meshesFromObj.length; j++) {
  104345. //check meshesNames (stlFileLoader)
  104346. if (meshesNames && meshesFromObj[j].name) {
  104347. if (meshesNames instanceof Array) {
  104348. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  104349. continue;
  104350. }
  104351. }
  104352. else {
  104353. if (meshesFromObj[j].name !== meshesNames) {
  104354. continue;
  104355. }
  104356. }
  104357. }
  104358. //Get the current mesh
  104359. //Set the data with VertexBuffer for each mesh
  104360. handledMesh = meshesFromObj[j];
  104361. //Create a BABYLON.Mesh with the name of the obj mesh
  104362. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  104363. //Push the name of the material to an array
  104364. //This is indispensable for the importMesh function
  104365. materialToUse.push(meshesFromObj[j].materialName);
  104366. var vertexData = new BABYLON.VertexData(); //The container for the values
  104367. //Set the data for the babylonMesh
  104368. vertexData.positions = handledMesh.positions;
  104369. vertexData.normals = handledMesh.normals;
  104370. vertexData.uvs = handledMesh.uvs;
  104371. vertexData.indices = handledMesh.indices;
  104372. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  104373. vertexData.applyToMesh(babylonMesh);
  104374. if (OBJFileLoader.INVERT_Y) {
  104375. babylonMesh.scaling.y *= -1;
  104376. }
  104377. //Push the mesh into an array
  104378. babylonMeshesArray.push(babylonMesh);
  104379. }
  104380. //load the materials
  104381. //Check if we have a file to load
  104382. if (fileToLoad !== "") {
  104383. //Load the file synchronously
  104384. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  104385. //Create materials thanks MTLLoader function
  104386. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  104387. //Look at each material loaded in the mtl file
  104388. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  104389. //Three variables to get all meshes with the same material
  104390. var startIndex = 0;
  104391. var _indices = [];
  104392. var _index;
  104393. //The material from MTL file is used in the meshes loaded
  104394. //Push the indice in an array
  104395. //Check if the material is not used for another mesh
  104396. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  104397. _indices.push(_index);
  104398. startIndex = _index + 1;
  104399. }
  104400. //If the material is not used dispose it
  104401. if (_index == -1 && _indices.length == 0) {
  104402. //If the material is not needed, remove it
  104403. materialsFromMTLFile.materials[n].dispose();
  104404. }
  104405. else {
  104406. for (var o = 0; o < _indices.length; o++) {
  104407. //Apply the material to the BABYLON.Mesh for each mesh with the material
  104408. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  104409. }
  104410. }
  104411. }
  104412. });
  104413. }
  104414. //Return an array with all BABYLON.Mesh
  104415. return babylonMeshesArray;
  104416. };
  104417. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  104418. OBJFileLoader.INVERT_Y = false;
  104419. return OBJFileLoader;
  104420. }());
  104421. BABYLON.OBJFileLoader = OBJFileLoader;
  104422. if (BABYLON.SceneLoader) {
  104423. //Add this loader into the register plugin
  104424. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  104425. }
  104426. })(BABYLON || (BABYLON = {}));
  104427. //# sourceMappingURL=babylon.objFileLoader.js.map
  104428. var BABYLON;
  104429. (function (BABYLON) {
  104430. /**
  104431. * Mode that determines the coordinate system to use.
  104432. */
  104433. var GLTFLoaderCoordinateSystemMode;
  104434. (function (GLTFLoaderCoordinateSystemMode) {
  104435. /**
  104436. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  104437. */
  104438. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  104439. /**
  104440. * Sets the useRightHandedSystem flag on the scene.
  104441. */
  104442. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  104443. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  104444. /**
  104445. * Mode that determines what animations will start.
  104446. */
  104447. var GLTFLoaderAnimationStartMode;
  104448. (function (GLTFLoaderAnimationStartMode) {
  104449. /**
  104450. * No animation will start.
  104451. */
  104452. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  104453. /**
  104454. * The first animation will start.
  104455. */
  104456. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  104457. /**
  104458. * All animations will start.
  104459. */
  104460. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  104461. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  104462. /**
  104463. * Loader state.
  104464. */
  104465. var GLTFLoaderState;
  104466. (function (GLTFLoaderState) {
  104467. /**
  104468. * The asset is loading.
  104469. */
  104470. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  104471. /**
  104472. * The asset is ready for rendering.
  104473. */
  104474. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  104475. /**
  104476. * The asset is completely loaded.
  104477. */
  104478. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  104479. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  104480. /**
  104481. * File loader for loading glTF files into a scene.
  104482. */
  104483. var GLTFFileLoader = /** @class */ (function () {
  104484. function GLTFFileLoader() {
  104485. // #region Common options
  104486. /**
  104487. * Raised when the asset has been parsed
  104488. */
  104489. this.onParsedObservable = new BABYLON.Observable();
  104490. // #endregion
  104491. // #region V2 options
  104492. /**
  104493. * The coordinate system mode. Defaults to AUTO.
  104494. */
  104495. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  104496. /**
  104497. * The animation start mode. Defaults to FIRST.
  104498. */
  104499. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  104500. /**
  104501. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  104502. */
  104503. this.compileMaterials = false;
  104504. /**
  104505. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  104506. */
  104507. this.useClipPlane = false;
  104508. /**
  104509. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  104510. */
  104511. this.compileShadowGenerators = false;
  104512. /**
  104513. * Defines if the Alpha blended materials are only applied as coverage.
  104514. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  104515. * If true, no extra effects are applied to transparent pixels.
  104516. */
  104517. this.transparencyAsCoverage = false;
  104518. /** @hidden */
  104519. this._normalizeAnimationGroupsToBeginAtZero = true;
  104520. /**
  104521. * Function called before loading a url referenced by the asset.
  104522. */
  104523. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104524. /**
  104525. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104526. */
  104527. this.onMeshLoadedObservable = new BABYLON.Observable();
  104528. /**
  104529. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104530. */
  104531. this.onTextureLoadedObservable = new BABYLON.Observable();
  104532. /**
  104533. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  104534. */
  104535. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104536. /**
  104537. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  104538. */
  104539. this.onCameraLoadedObservable = new BABYLON.Observable();
  104540. /**
  104541. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  104542. * For assets with LODs, raised when all of the LODs are complete.
  104543. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  104544. */
  104545. this.onCompleteObservable = new BABYLON.Observable();
  104546. /**
  104547. * Observable raised after the loader is disposed.
  104548. */
  104549. this.onDisposeObservable = new BABYLON.Observable();
  104550. /**
  104551. * Observable raised after a loader extension is created.
  104552. * Set additional options for a loader extension in this event.
  104553. */
  104554. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104555. // #endregion
  104556. this._loader = null;
  104557. /**
  104558. * Name of the loader ("gltf")
  104559. */
  104560. this.name = "gltf";
  104561. /**
  104562. * Supported file extensions of the loader (.gltf, .glb)
  104563. */
  104564. this.extensions = {
  104565. ".gltf": { isBinary: false },
  104566. ".glb": { isBinary: true }
  104567. };
  104568. }
  104569. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  104570. /**
  104571. * Raised when the asset has been parsed
  104572. */
  104573. set: function (callback) {
  104574. if (this._onParsedObserver) {
  104575. this.onParsedObservable.remove(this._onParsedObserver);
  104576. }
  104577. this._onParsedObserver = this.onParsedObservable.add(callback);
  104578. },
  104579. enumerable: true,
  104580. configurable: true
  104581. });
  104582. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  104583. /**
  104584. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104585. */
  104586. set: function (callback) {
  104587. if (this._onMeshLoadedObserver) {
  104588. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  104589. }
  104590. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  104591. },
  104592. enumerable: true,
  104593. configurable: true
  104594. });
  104595. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  104596. /**
  104597. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  104598. */
  104599. set: function (callback) {
  104600. if (this._onTextureLoadedObserver) {
  104601. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  104602. }
  104603. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  104604. },
  104605. enumerable: true,
  104606. configurable: true
  104607. });
  104608. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  104609. /**
  104610. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  104611. */
  104612. set: function (callback) {
  104613. if (this._onMaterialLoadedObserver) {
  104614. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  104615. }
  104616. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  104617. },
  104618. enumerable: true,
  104619. configurable: true
  104620. });
  104621. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  104622. /**
  104623. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  104624. */
  104625. set: function (callback) {
  104626. if (this._onCameraLoadedObserver) {
  104627. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  104628. }
  104629. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  104630. },
  104631. enumerable: true,
  104632. configurable: true
  104633. });
  104634. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  104635. /**
  104636. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  104637. */
  104638. set: function (callback) {
  104639. if (this._onCompleteObserver) {
  104640. this.onCompleteObservable.remove(this._onCompleteObserver);
  104641. }
  104642. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  104643. },
  104644. enumerable: true,
  104645. configurable: true
  104646. });
  104647. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  104648. /**
  104649. * Callback raised after the loader is disposed.
  104650. */
  104651. set: function (callback) {
  104652. if (this._onDisposeObserver) {
  104653. this.onDisposeObservable.remove(this._onDisposeObserver);
  104654. }
  104655. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104656. },
  104657. enumerable: true,
  104658. configurable: true
  104659. });
  104660. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  104661. /**
  104662. * Callback raised after a loader extension is created.
  104663. */
  104664. set: function (callback) {
  104665. if (this._onExtensionLoadedObserver) {
  104666. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  104667. }
  104668. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  104669. },
  104670. enumerable: true,
  104671. configurable: true
  104672. });
  104673. /**
  104674. * Returns a promise that resolves when the asset is completely loaded.
  104675. * @returns a promise that resolves when the asset is completely loaded.
  104676. */
  104677. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  104678. var _this = this;
  104679. return new Promise(function (resolve) {
  104680. _this.onCompleteObservable.addOnce(function () {
  104681. resolve();
  104682. });
  104683. });
  104684. };
  104685. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  104686. /**
  104687. * The loader state or null if the loader is not active.
  104688. */
  104689. get: function () {
  104690. return this._loader ? this._loader.state : null;
  104691. },
  104692. enumerable: true,
  104693. configurable: true
  104694. });
  104695. /**
  104696. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104697. */
  104698. GLTFFileLoader.prototype.dispose = function () {
  104699. if (this._loader) {
  104700. this._loader.dispose();
  104701. this._loader = null;
  104702. }
  104703. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104704. this.onMeshLoadedObservable.clear();
  104705. this.onTextureLoadedObservable.clear();
  104706. this.onMaterialLoadedObservable.clear();
  104707. this.onCameraLoadedObservable.clear();
  104708. this.onCompleteObservable.clear();
  104709. this.onExtensionLoadedObservable.clear();
  104710. this.onDisposeObservable.notifyObservers(this);
  104711. this.onDisposeObservable.clear();
  104712. };
  104713. /**
  104714. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  104715. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104716. * @param scene the scene the meshes should be added to
  104717. * @param data the glTF data to load
  104718. * @param rootUrl root url to load from
  104719. * @param onProgress event that fires when loading progress has occured
  104720. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104721. */
  104722. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104723. var _this = this;
  104724. return Promise.resolve().then(function () {
  104725. var loaderData = _this._parse(data);
  104726. _this._loader = _this._getLoader(loaderData);
  104727. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  104728. });
  104729. };
  104730. /**
  104731. * Imports all objects from the loaded glTF data and adds them to the scene
  104732. * @param scene the scene the objects should be added to
  104733. * @param data the glTF data to load
  104734. * @param rootUrl root url to load from
  104735. * @param onProgress event that fires when loading progress has occured
  104736. * @returns a promise which completes when objects have been loaded to the scene
  104737. */
  104738. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104739. var _this = this;
  104740. return Promise.resolve().then(function () {
  104741. var loaderData = _this._parse(data);
  104742. _this._loader = _this._getLoader(loaderData);
  104743. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  104744. });
  104745. };
  104746. /**
  104747. * Load into an asset container.
  104748. * @param scene The scene to load into
  104749. * @param data The data to import
  104750. * @param rootUrl The root url for scene and resources
  104751. * @param onProgress The callback when the load progresses
  104752. * @returns The loaded asset container
  104753. */
  104754. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  104755. var _this = this;
  104756. return Promise.resolve().then(function () {
  104757. var loaderData = _this._parse(data);
  104758. _this._loader = _this._getLoader(loaderData);
  104759. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  104760. var container = new BABYLON.AssetContainer(scene);
  104761. Array.prototype.push.apply(container.meshes, result.meshes);
  104762. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  104763. Array.prototype.push.apply(container.skeletons, result.skeletons);
  104764. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  104765. container.removeAllFromScene();
  104766. return container;
  104767. });
  104768. });
  104769. };
  104770. /**
  104771. * If the data string can be loaded directly.
  104772. * @param data string contianing the file data
  104773. * @returns if the data can be loaded directly
  104774. */
  104775. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  104776. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  104777. };
  104778. /**
  104779. * Instantiates a glTF file loader plugin.
  104780. * @returns the created plugin
  104781. */
  104782. GLTFFileLoader.prototype.createPlugin = function () {
  104783. return new GLTFFileLoader();
  104784. };
  104785. GLTFFileLoader.prototype._parse = function (data) {
  104786. var parsedData;
  104787. if (data instanceof ArrayBuffer) {
  104788. parsedData = GLTFFileLoader._parseBinary(data);
  104789. }
  104790. else {
  104791. parsedData = {
  104792. json: JSON.parse(data),
  104793. bin: null
  104794. };
  104795. }
  104796. this.onParsedObservable.notifyObservers(parsedData);
  104797. this.onParsedObservable.clear();
  104798. return parsedData;
  104799. };
  104800. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  104801. var _this = this;
  104802. var loaderVersion = { major: 2, minor: 0 };
  104803. var asset = loaderData.json.asset || {};
  104804. var version = GLTFFileLoader._parseVersion(asset.version);
  104805. if (!version) {
  104806. throw new Error("Invalid version: " + asset.version);
  104807. }
  104808. if (asset.minVersion !== undefined) {
  104809. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  104810. if (!minVersion) {
  104811. throw new Error("Invalid minimum version: " + asset.minVersion);
  104812. }
  104813. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  104814. throw new Error("Incompatible minimum version: " + asset.minVersion);
  104815. }
  104816. }
  104817. var createLoaders = {
  104818. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  104819. 2: GLTFFileLoader._CreateGLTFLoaderV2
  104820. };
  104821. var createLoader = createLoaders[version.major];
  104822. if (!createLoader) {
  104823. throw new Error("Unsupported version: " + asset.version);
  104824. }
  104825. var loader = createLoader();
  104826. loader.coordinateSystemMode = this.coordinateSystemMode;
  104827. loader.animationStartMode = this.animationStartMode;
  104828. loader.compileMaterials = this.compileMaterials;
  104829. loader.useClipPlane = this.useClipPlane;
  104830. loader.compileShadowGenerators = this.compileShadowGenerators;
  104831. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  104832. loader._normalizeAnimationGroupsToBeginAtZero = this._normalizeAnimationGroupsToBeginAtZero;
  104833. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  104834. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  104835. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  104836. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  104837. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  104838. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  104839. loader.onCompleteObservable.add(function () {
  104840. _this.onMeshLoadedObservable.clear();
  104841. _this.onTextureLoadedObservable.clear();
  104842. _this.onMaterialLoadedObservable.clear();
  104843. _this.onCameraLoadedObservable.clear();
  104844. _this.onExtensionLoadedObservable.clear();
  104845. _this.onCompleteObservable.notifyObservers(_this);
  104846. _this.onCompleteObservable.clear();
  104847. });
  104848. return loader;
  104849. };
  104850. GLTFFileLoader._parseBinary = function (data) {
  104851. var Binary = {
  104852. Magic: 0x46546C67
  104853. };
  104854. var binaryReader = new BinaryReader(data);
  104855. var magic = binaryReader.readUint32();
  104856. if (magic !== Binary.Magic) {
  104857. throw new Error("Unexpected magic: " + magic);
  104858. }
  104859. var version = binaryReader.readUint32();
  104860. switch (version) {
  104861. case 1: return GLTFFileLoader._parseV1(binaryReader);
  104862. case 2: return GLTFFileLoader._parseV2(binaryReader);
  104863. }
  104864. throw new Error("Unsupported version: " + version);
  104865. };
  104866. GLTFFileLoader._parseV1 = function (binaryReader) {
  104867. var ContentFormat = {
  104868. JSON: 0
  104869. };
  104870. var length = binaryReader.readUint32();
  104871. if (length != binaryReader.getLength()) {
  104872. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104873. }
  104874. var contentLength = binaryReader.readUint32();
  104875. var contentFormat = binaryReader.readUint32();
  104876. var content;
  104877. switch (contentFormat) {
  104878. case ContentFormat.JSON: {
  104879. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  104880. break;
  104881. }
  104882. default: {
  104883. throw new Error("Unexpected content format: " + contentFormat);
  104884. }
  104885. }
  104886. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  104887. var body = binaryReader.readUint8Array(bytesRemaining);
  104888. return {
  104889. json: content,
  104890. bin: body
  104891. };
  104892. };
  104893. GLTFFileLoader._parseV2 = function (binaryReader) {
  104894. var ChunkFormat = {
  104895. JSON: 0x4E4F534A,
  104896. BIN: 0x004E4942
  104897. };
  104898. var length = binaryReader.readUint32();
  104899. if (length !== binaryReader.getLength()) {
  104900. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  104901. }
  104902. // JSON chunk
  104903. var chunkLength = binaryReader.readUint32();
  104904. var chunkFormat = binaryReader.readUint32();
  104905. if (chunkFormat !== ChunkFormat.JSON) {
  104906. throw new Error("First chunk format is not JSON");
  104907. }
  104908. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  104909. // Look for BIN chunk
  104910. var bin = null;
  104911. while (binaryReader.getPosition() < binaryReader.getLength()) {
  104912. var chunkLength_1 = binaryReader.readUint32();
  104913. var chunkFormat_1 = binaryReader.readUint32();
  104914. switch (chunkFormat_1) {
  104915. case ChunkFormat.JSON: {
  104916. throw new Error("Unexpected JSON chunk");
  104917. }
  104918. case ChunkFormat.BIN: {
  104919. bin = binaryReader.readUint8Array(chunkLength_1);
  104920. break;
  104921. }
  104922. default: {
  104923. // ignore unrecognized chunkFormat
  104924. binaryReader.skipBytes(chunkLength_1);
  104925. break;
  104926. }
  104927. }
  104928. }
  104929. return {
  104930. json: json,
  104931. bin: bin
  104932. };
  104933. };
  104934. GLTFFileLoader._parseVersion = function (version) {
  104935. if (version === "1.0" || version === "1.0.1") {
  104936. return {
  104937. major: 1,
  104938. minor: 0
  104939. };
  104940. }
  104941. var match = (version + "").match(/^(\d+)\.(\d+)/);
  104942. if (!match) {
  104943. return null;
  104944. }
  104945. return {
  104946. major: parseInt(match[1]),
  104947. minor: parseInt(match[2])
  104948. };
  104949. };
  104950. GLTFFileLoader._compareVersion = function (a, b) {
  104951. if (a.major > b.major)
  104952. return 1;
  104953. if (a.major < b.major)
  104954. return -1;
  104955. if (a.minor > b.minor)
  104956. return 1;
  104957. if (a.minor < b.minor)
  104958. return -1;
  104959. return 0;
  104960. };
  104961. GLTFFileLoader._decodeBufferToText = function (buffer) {
  104962. var result = "";
  104963. var length = buffer.byteLength;
  104964. for (var i = 0; i < length; i++) {
  104965. result += String.fromCharCode(buffer[i]);
  104966. }
  104967. return result;
  104968. };
  104969. // #endregion
  104970. // #region V1 options
  104971. /**
  104972. * 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.
  104973. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  104974. * Defaults to true.
  104975. * @hidden
  104976. */
  104977. GLTFFileLoader.IncrementalLoading = true;
  104978. /**
  104979. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  104980. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  104981. * @hidden
  104982. */
  104983. GLTFFileLoader.HomogeneousCoordinates = false;
  104984. return GLTFFileLoader;
  104985. }());
  104986. BABYLON.GLTFFileLoader = GLTFFileLoader;
  104987. var BinaryReader = /** @class */ (function () {
  104988. function BinaryReader(arrayBuffer) {
  104989. this._arrayBuffer = arrayBuffer;
  104990. this._dataView = new DataView(arrayBuffer);
  104991. this._byteOffset = 0;
  104992. }
  104993. BinaryReader.prototype.getPosition = function () {
  104994. return this._byteOffset;
  104995. };
  104996. BinaryReader.prototype.getLength = function () {
  104997. return this._arrayBuffer.byteLength;
  104998. };
  104999. BinaryReader.prototype.readUint32 = function () {
  105000. var value = this._dataView.getUint32(this._byteOffset, true);
  105001. this._byteOffset += 4;
  105002. return value;
  105003. };
  105004. BinaryReader.prototype.readUint8Array = function (length) {
  105005. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  105006. this._byteOffset += length;
  105007. return value;
  105008. };
  105009. BinaryReader.prototype.skipBytes = function (length) {
  105010. this._byteOffset += length;
  105011. };
  105012. return BinaryReader;
  105013. }());
  105014. if (BABYLON.SceneLoader) {
  105015. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  105016. }
  105017. })(BABYLON || (BABYLON = {}));
  105018. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  105019. var BABYLON;
  105020. (function (BABYLON) {
  105021. var GLTF1;
  105022. (function (GLTF1) {
  105023. /**
  105024. * Enums
  105025. */
  105026. var EComponentType;
  105027. (function (EComponentType) {
  105028. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  105029. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  105030. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  105031. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  105032. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  105033. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  105034. var EShaderType;
  105035. (function (EShaderType) {
  105036. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  105037. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  105038. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  105039. var EParameterType;
  105040. (function (EParameterType) {
  105041. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  105042. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  105043. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  105044. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  105045. EParameterType[EParameterType["INT"] = 5124] = "INT";
  105046. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  105047. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  105048. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  105049. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  105050. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  105051. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  105052. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  105053. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  105054. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  105055. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  105056. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  105057. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  105058. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  105059. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  105060. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  105061. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  105062. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  105063. var ETextureWrapMode;
  105064. (function (ETextureWrapMode) {
  105065. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  105066. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  105067. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  105068. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  105069. var ETextureFilterType;
  105070. (function (ETextureFilterType) {
  105071. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  105072. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  105073. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  105074. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  105075. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  105076. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  105077. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  105078. var ETextureFormat;
  105079. (function (ETextureFormat) {
  105080. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  105081. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  105082. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  105083. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  105084. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  105085. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  105086. var ECullingType;
  105087. (function (ECullingType) {
  105088. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  105089. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  105090. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  105091. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  105092. var EBlendingFunction;
  105093. (function (EBlendingFunction) {
  105094. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  105095. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  105096. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  105097. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  105098. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  105099. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  105100. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  105101. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  105102. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  105103. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  105104. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  105105. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  105106. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  105107. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  105108. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  105109. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  105110. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105111. })(BABYLON || (BABYLON = {}));
  105112. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  105113. var BABYLON;
  105114. (function (BABYLON) {
  105115. var GLTF1;
  105116. (function (GLTF1) {
  105117. /**
  105118. * Tokenizer. Used for shaders compatibility
  105119. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  105120. */
  105121. var ETokenType;
  105122. (function (ETokenType) {
  105123. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  105124. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  105125. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  105126. })(ETokenType || (ETokenType = {}));
  105127. var Tokenizer = /** @class */ (function () {
  105128. function Tokenizer(toParse) {
  105129. this._pos = 0;
  105130. this.currentToken = ETokenType.UNKNOWN;
  105131. this.currentIdentifier = "";
  105132. this.currentString = "";
  105133. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  105134. this._toParse = toParse;
  105135. this._maxPos = toParse.length;
  105136. }
  105137. Tokenizer.prototype.getNextToken = function () {
  105138. if (this.isEnd())
  105139. return ETokenType.END_OF_INPUT;
  105140. this.currentString = this.read();
  105141. this.currentToken = ETokenType.UNKNOWN;
  105142. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  105143. this.currentToken = ETokenType.IDENTIFIER;
  105144. this.currentIdentifier = this.currentString;
  105145. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  105146. this.currentIdentifier += this.currentString;
  105147. this.forward();
  105148. }
  105149. }
  105150. return this.currentToken;
  105151. };
  105152. Tokenizer.prototype.peek = function () {
  105153. return this._toParse[this._pos];
  105154. };
  105155. Tokenizer.prototype.read = function () {
  105156. return this._toParse[this._pos++];
  105157. };
  105158. Tokenizer.prototype.forward = function () {
  105159. this._pos++;
  105160. };
  105161. Tokenizer.prototype.isEnd = function () {
  105162. return this._pos >= this._maxPos;
  105163. };
  105164. return Tokenizer;
  105165. }());
  105166. /**
  105167. * Values
  105168. */
  105169. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  105170. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  105171. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  105172. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  105173. /**
  105174. * Parse
  105175. */
  105176. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  105177. for (var buf in parsedBuffers) {
  105178. var parsedBuffer = parsedBuffers[buf];
  105179. gltfRuntime.buffers[buf] = parsedBuffer;
  105180. gltfRuntime.buffersCount++;
  105181. }
  105182. };
  105183. var parseShaders = function (parsedShaders, gltfRuntime) {
  105184. for (var sha in parsedShaders) {
  105185. var parsedShader = parsedShaders[sha];
  105186. gltfRuntime.shaders[sha] = parsedShader;
  105187. gltfRuntime.shaderscount++;
  105188. }
  105189. };
  105190. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  105191. for (var object in parsedObjects) {
  105192. var parsedObject = parsedObjects[object];
  105193. gltfRuntime[runtimeProperty][object] = parsedObject;
  105194. }
  105195. };
  105196. /**
  105197. * Utils
  105198. */
  105199. var normalizeUVs = function (buffer) {
  105200. if (!buffer) {
  105201. return;
  105202. }
  105203. for (var i = 0; i < buffer.length / 2; i++) {
  105204. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  105205. }
  105206. };
  105207. var getAttribute = function (attributeParameter) {
  105208. if (attributeParameter.semantic === "NORMAL") {
  105209. return "normal";
  105210. }
  105211. else if (attributeParameter.semantic === "POSITION") {
  105212. return "position";
  105213. }
  105214. else if (attributeParameter.semantic === "JOINT") {
  105215. return "matricesIndices";
  105216. }
  105217. else if (attributeParameter.semantic === "WEIGHT") {
  105218. return "matricesWeights";
  105219. }
  105220. else if (attributeParameter.semantic === "COLOR") {
  105221. return "color";
  105222. }
  105223. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  105224. var channel = Number(attributeParameter.semantic.split("_")[1]);
  105225. return "uv" + (channel === 0 ? "" : channel + 1);
  105226. }
  105227. return null;
  105228. };
  105229. /**
  105230. * Loads and creates animations
  105231. */
  105232. var loadAnimations = function (gltfRuntime) {
  105233. for (var anim in gltfRuntime.animations) {
  105234. var animation = gltfRuntime.animations[anim];
  105235. if (!animation.channels || !animation.samplers) {
  105236. continue;
  105237. }
  105238. var lastAnimation = null;
  105239. for (var i = 0; i < animation.channels.length; i++) {
  105240. // Get parameters and load buffers
  105241. var channel = animation.channels[i];
  105242. var sampler = animation.samplers[channel.sampler];
  105243. if (!sampler) {
  105244. continue;
  105245. }
  105246. var inputData = null;
  105247. var outputData = null;
  105248. if (animation.parameters) {
  105249. inputData = animation.parameters[sampler.input];
  105250. outputData = animation.parameters[sampler.output];
  105251. }
  105252. else {
  105253. inputData = sampler.input;
  105254. outputData = sampler.output;
  105255. }
  105256. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  105257. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  105258. var targetID = channel.target.id;
  105259. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  105260. if (targetNode === null) {
  105261. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  105262. }
  105263. if (targetNode === null) {
  105264. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  105265. continue;
  105266. }
  105267. var isBone = targetNode instanceof BABYLON.Bone;
  105268. // Get target path (position, rotation or scaling)
  105269. var targetPath = channel.target.path;
  105270. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  105271. if (targetPathIndex !== -1) {
  105272. targetPath = babylonAnimationPaths[targetPathIndex];
  105273. }
  105274. // Determine animation type
  105275. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  105276. if (!isBone) {
  105277. if (targetPath === "rotationQuaternion") {
  105278. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105279. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  105280. }
  105281. else {
  105282. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105283. }
  105284. }
  105285. // Create animation and key frames
  105286. var babylonAnimation = null;
  105287. var keys = [];
  105288. var arrayOffset = 0;
  105289. var modifyKey = false;
  105290. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  105291. babylonAnimation = lastAnimation;
  105292. modifyKey = true;
  105293. }
  105294. if (!modifyKey) {
  105295. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105296. }
  105297. // For each frame
  105298. for (var j = 0; j < bufferInput.length; j++) {
  105299. var value = null;
  105300. if (targetPath === "rotationQuaternion") { // VEC4
  105301. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  105302. arrayOffset += 4;
  105303. }
  105304. else { // Position and scaling are VEC3
  105305. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  105306. arrayOffset += 3;
  105307. }
  105308. if (isBone) {
  105309. var bone = targetNode;
  105310. var translation = BABYLON.Vector3.Zero();
  105311. var rotationQuaternion = new BABYLON.Quaternion();
  105312. var scaling = BABYLON.Vector3.Zero();
  105313. // Warning on decompose
  105314. var mat = bone.getBaseMatrix();
  105315. if (modifyKey && lastAnimation) {
  105316. mat = lastAnimation.getKeys()[j].value;
  105317. }
  105318. mat.decompose(scaling, rotationQuaternion, translation);
  105319. if (targetPath === "position") {
  105320. translation = value;
  105321. }
  105322. else if (targetPath === "rotationQuaternion") {
  105323. rotationQuaternion = value;
  105324. }
  105325. else {
  105326. scaling = value;
  105327. }
  105328. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  105329. }
  105330. if (!modifyKey) {
  105331. keys.push({
  105332. frame: bufferInput[j],
  105333. value: value
  105334. });
  105335. }
  105336. else if (lastAnimation) {
  105337. lastAnimation.getKeys()[j].value = value;
  105338. }
  105339. }
  105340. // Finish
  105341. if (!modifyKey && babylonAnimation) {
  105342. babylonAnimation.setKeys(keys);
  105343. targetNode.animations.push(babylonAnimation);
  105344. }
  105345. lastAnimation = babylonAnimation;
  105346. gltfRuntime.scene.stopAnimation(targetNode);
  105347. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  105348. }
  105349. }
  105350. };
  105351. /**
  105352. * Returns the bones transformation matrix
  105353. */
  105354. var configureBoneTransformation = function (node) {
  105355. var mat = null;
  105356. if (node.translation || node.rotation || node.scale) {
  105357. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  105358. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  105359. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  105360. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  105361. }
  105362. else {
  105363. mat = BABYLON.Matrix.FromArray(node.matrix);
  105364. }
  105365. return mat;
  105366. };
  105367. /**
  105368. * Returns the parent bone
  105369. */
  105370. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  105371. // Try to find
  105372. for (var i = 0; i < newSkeleton.bones.length; i++) {
  105373. if (newSkeleton.bones[i].name === jointName) {
  105374. return newSkeleton.bones[i];
  105375. }
  105376. }
  105377. // Not found, search in gltf nodes
  105378. var nodes = gltfRuntime.nodes;
  105379. for (var nde in nodes) {
  105380. var node = nodes[nde];
  105381. if (!node.jointName) {
  105382. continue;
  105383. }
  105384. var children = node.children;
  105385. for (var i = 0; i < children.length; i++) {
  105386. var child = gltfRuntime.nodes[children[i]];
  105387. if (!child.jointName) {
  105388. continue;
  105389. }
  105390. if (child.jointName === jointName) {
  105391. var mat = configureBoneTransformation(node);
  105392. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  105393. bone.id = nde;
  105394. return bone;
  105395. }
  105396. }
  105397. }
  105398. return null;
  105399. };
  105400. /**
  105401. * Returns the appropriate root node
  105402. */
  105403. var getNodeToRoot = function (nodesToRoot, id) {
  105404. for (var i = 0; i < nodesToRoot.length; i++) {
  105405. var nodeToRoot = nodesToRoot[i];
  105406. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  105407. var child = nodeToRoot.node.children[j];
  105408. if (child === id) {
  105409. return nodeToRoot.bone;
  105410. }
  105411. }
  105412. }
  105413. return null;
  105414. };
  105415. /**
  105416. * Returns the node with the joint name
  105417. */
  105418. var getJointNode = function (gltfRuntime, jointName) {
  105419. var nodes = gltfRuntime.nodes;
  105420. var node = nodes[jointName];
  105421. if (node) {
  105422. return {
  105423. node: node,
  105424. id: jointName
  105425. };
  105426. }
  105427. for (var nde in nodes) {
  105428. node = nodes[nde];
  105429. if (node.jointName === jointName) {
  105430. return {
  105431. node: node,
  105432. id: nde
  105433. };
  105434. }
  105435. }
  105436. return null;
  105437. };
  105438. /**
  105439. * Checks if a nodes is in joints
  105440. */
  105441. var nodeIsInJoints = function (skins, id) {
  105442. for (var i = 0; i < skins.jointNames.length; i++) {
  105443. if (skins.jointNames[i] === id) {
  105444. return true;
  105445. }
  105446. }
  105447. return false;
  105448. };
  105449. /**
  105450. * Fills the nodes to root for bones and builds hierarchy
  105451. */
  105452. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  105453. // Creates nodes for root
  105454. for (var nde in gltfRuntime.nodes) {
  105455. var node = gltfRuntime.nodes[nde];
  105456. var id = nde;
  105457. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  105458. continue;
  105459. }
  105460. // Create node to root bone
  105461. var mat = configureBoneTransformation(node);
  105462. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  105463. bone.id = id;
  105464. nodesToRoot.push({ bone: bone, node: node, id: id });
  105465. }
  105466. // Parenting
  105467. for (var i = 0; i < nodesToRoot.length; i++) {
  105468. var nodeToRoot = nodesToRoot[i];
  105469. var children = nodeToRoot.node.children;
  105470. for (var j = 0; j < children.length; j++) {
  105471. var child = null;
  105472. for (var k = 0; k < nodesToRoot.length; k++) {
  105473. if (nodesToRoot[k].id === children[j]) {
  105474. child = nodesToRoot[k];
  105475. break;
  105476. }
  105477. }
  105478. if (child) {
  105479. child.bone._parent = nodeToRoot.bone;
  105480. nodeToRoot.bone.children.push(child.bone);
  105481. }
  105482. }
  105483. }
  105484. };
  105485. /**
  105486. * Imports a skeleton
  105487. */
  105488. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  105489. if (!newSkeleton) {
  105490. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  105491. }
  105492. if (!skins.babylonSkeleton) {
  105493. return newSkeleton;
  105494. }
  105495. // Find the root bones
  105496. var nodesToRoot = [];
  105497. var nodesToRootToAdd = [];
  105498. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  105499. newSkeleton.bones = [];
  105500. // Joints
  105501. for (var i = 0; i < skins.jointNames.length; i++) {
  105502. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105503. if (!jointNode) {
  105504. continue;
  105505. }
  105506. var node = jointNode.node;
  105507. if (!node) {
  105508. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  105509. continue;
  105510. }
  105511. var id = jointNode.id;
  105512. // Optimize, if the bone already exists...
  105513. var existingBone = gltfRuntime.scene.getBoneByID(id);
  105514. if (existingBone) {
  105515. newSkeleton.bones.push(existingBone);
  105516. continue;
  105517. }
  105518. // Search for parent bone
  105519. var foundBone = false;
  105520. var parentBone = null;
  105521. for (var j = 0; j < i; j++) {
  105522. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  105523. if (!jointNode_1) {
  105524. continue;
  105525. }
  105526. var joint = jointNode_1.node;
  105527. if (!joint) {
  105528. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  105529. continue;
  105530. }
  105531. var children = joint.children;
  105532. if (!children) {
  105533. continue;
  105534. }
  105535. foundBone = false;
  105536. for (var k = 0; k < children.length; k++) {
  105537. if (children[k] === id) {
  105538. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  105539. foundBone = true;
  105540. break;
  105541. }
  105542. }
  105543. if (foundBone) {
  105544. break;
  105545. }
  105546. }
  105547. // Create bone
  105548. var mat = configureBoneTransformation(node);
  105549. if (!parentBone && nodesToRoot.length > 0) {
  105550. parentBone = getNodeToRoot(nodesToRoot, id);
  105551. if (parentBone) {
  105552. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  105553. nodesToRootToAdd.push(parentBone);
  105554. }
  105555. }
  105556. }
  105557. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  105558. bone.id = id;
  105559. }
  105560. // Polish
  105561. var bones = newSkeleton.bones;
  105562. newSkeleton.bones = [];
  105563. for (var i = 0; i < skins.jointNames.length; i++) {
  105564. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105565. if (!jointNode) {
  105566. continue;
  105567. }
  105568. for (var j = 0; j < bones.length; j++) {
  105569. if (bones[j].id === jointNode.id) {
  105570. newSkeleton.bones.push(bones[j]);
  105571. break;
  105572. }
  105573. }
  105574. }
  105575. newSkeleton.prepare();
  105576. // Finish
  105577. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  105578. newSkeleton.bones.push(nodesToRootToAdd[i]);
  105579. }
  105580. return newSkeleton;
  105581. };
  105582. /**
  105583. * Imports a mesh and its geometries
  105584. */
  105585. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  105586. if (!newMesh) {
  105587. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105588. newMesh.id = id;
  105589. }
  105590. if (!node.babylonNode) {
  105591. return newMesh;
  105592. }
  105593. var subMaterials = [];
  105594. var vertexData = null;
  105595. var verticesStarts = new Array();
  105596. var verticesCounts = new Array();
  105597. var indexStarts = new Array();
  105598. var indexCounts = new Array();
  105599. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105600. var meshID = meshes[meshIndex];
  105601. var mesh = gltfRuntime.meshes[meshID];
  105602. if (!mesh) {
  105603. continue;
  105604. }
  105605. // Positions, normals and UVs
  105606. for (var i = 0; i < mesh.primitives.length; i++) {
  105607. // Temporary vertex data
  105608. var tempVertexData = new BABYLON.VertexData();
  105609. var primitive = mesh.primitives[i];
  105610. if (primitive.mode !== 4) {
  105611. // continue;
  105612. }
  105613. var attributes = primitive.attributes;
  105614. var accessor = null;
  105615. var buffer = null;
  105616. // Set positions, normal and uvs
  105617. for (var semantic in attributes) {
  105618. // Link accessor and buffer view
  105619. accessor = gltfRuntime.accessors[attributes[semantic]];
  105620. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105621. if (semantic === "NORMAL") {
  105622. tempVertexData.normals = new Float32Array(buffer.length);
  105623. tempVertexData.normals.set(buffer);
  105624. }
  105625. else if (semantic === "POSITION") {
  105626. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  105627. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  105628. for (var j = 0; j < buffer.length; j += 4) {
  105629. tempVertexData.positions[j] = buffer[j];
  105630. tempVertexData.positions[j + 1] = buffer[j + 1];
  105631. tempVertexData.positions[j + 2] = buffer[j + 2];
  105632. }
  105633. }
  105634. else {
  105635. tempVertexData.positions = new Float32Array(buffer.length);
  105636. tempVertexData.positions.set(buffer);
  105637. }
  105638. verticesCounts.push(tempVertexData.positions.length);
  105639. }
  105640. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  105641. var channel = Number(semantic.split("_")[1]);
  105642. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  105643. var uvs = new Float32Array(buffer.length);
  105644. uvs.set(buffer);
  105645. normalizeUVs(uvs);
  105646. tempVertexData.set(uvs, uvKind);
  105647. }
  105648. else if (semantic === "JOINT") {
  105649. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  105650. tempVertexData.matricesIndices.set(buffer);
  105651. }
  105652. else if (semantic === "WEIGHT") {
  105653. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  105654. tempVertexData.matricesWeights.set(buffer);
  105655. }
  105656. else if (semantic === "COLOR") {
  105657. tempVertexData.colors = new Float32Array(buffer.length);
  105658. tempVertexData.colors.set(buffer);
  105659. }
  105660. }
  105661. // Indices
  105662. accessor = gltfRuntime.accessors[primitive.indices];
  105663. if (accessor) {
  105664. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105665. tempVertexData.indices = new Int32Array(buffer.length);
  105666. tempVertexData.indices.set(buffer);
  105667. indexCounts.push(tempVertexData.indices.length);
  105668. }
  105669. else {
  105670. // Set indices on the fly
  105671. var indices = [];
  105672. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  105673. indices.push(j);
  105674. }
  105675. tempVertexData.indices = new Int32Array(indices);
  105676. indexCounts.push(tempVertexData.indices.length);
  105677. }
  105678. if (!vertexData) {
  105679. vertexData = tempVertexData;
  105680. }
  105681. else {
  105682. vertexData.merge(tempVertexData);
  105683. }
  105684. // Sub material
  105685. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  105686. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  105687. // Update vertices start and index start
  105688. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  105689. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  105690. }
  105691. }
  105692. var material;
  105693. if (subMaterials.length > 1) {
  105694. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  105695. material.subMaterials = subMaterials;
  105696. }
  105697. else {
  105698. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  105699. }
  105700. if (subMaterials.length === 1) {
  105701. material = subMaterials[0];
  105702. }
  105703. if (!newMesh.material) {
  105704. newMesh.material = material;
  105705. }
  105706. // Apply geometry
  105707. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  105708. newMesh.computeWorldMatrix(true);
  105709. // Apply submeshes
  105710. newMesh.subMeshes = [];
  105711. var index = 0;
  105712. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105713. var meshID = meshes[meshIndex];
  105714. var mesh = gltfRuntime.meshes[meshID];
  105715. if (!mesh) {
  105716. continue;
  105717. }
  105718. for (var i = 0; i < mesh.primitives.length; i++) {
  105719. if (mesh.primitives[i].mode !== 4) {
  105720. //continue;
  105721. }
  105722. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  105723. index++;
  105724. }
  105725. }
  105726. // Finish
  105727. return newMesh;
  105728. };
  105729. /**
  105730. * Configure node transformation from position, rotation and scaling
  105731. */
  105732. var configureNode = function (newNode, position, rotation, scaling) {
  105733. if (newNode.position) {
  105734. newNode.position = position;
  105735. }
  105736. if (newNode.rotationQuaternion || newNode.rotation) {
  105737. newNode.rotationQuaternion = rotation;
  105738. }
  105739. if (newNode.scaling) {
  105740. newNode.scaling = scaling;
  105741. }
  105742. };
  105743. /**
  105744. * Configures node from transformation matrix
  105745. */
  105746. var configureNodeFromMatrix = function (newNode, node, parent) {
  105747. if (node.matrix) {
  105748. var position = new BABYLON.Vector3(0, 0, 0);
  105749. var rotation = new BABYLON.Quaternion();
  105750. var scaling = new BABYLON.Vector3(0, 0, 0);
  105751. var mat = BABYLON.Matrix.FromArray(node.matrix);
  105752. mat.decompose(scaling, rotation, position);
  105753. configureNode(newNode, position, rotation, scaling);
  105754. }
  105755. else if (node.translation && node.rotation && node.scale) {
  105756. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  105757. }
  105758. newNode.computeWorldMatrix(true);
  105759. };
  105760. /**
  105761. * Imports a node
  105762. */
  105763. var importNode = function (gltfRuntime, node, id, parent) {
  105764. var lastNode = null;
  105765. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  105766. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  105767. return null;
  105768. }
  105769. }
  105770. // Meshes
  105771. if (node.skin) {
  105772. if (node.meshes) {
  105773. var skin = gltfRuntime.skins[node.skin];
  105774. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  105775. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  105776. if (newMesh.skeleton === null) {
  105777. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  105778. if (!skin.babylonSkeleton) {
  105779. skin.babylonSkeleton = newMesh.skeleton;
  105780. }
  105781. }
  105782. lastNode = newMesh;
  105783. }
  105784. }
  105785. else if (node.meshes) {
  105786. /**
  105787. * Improve meshes property
  105788. */
  105789. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  105790. lastNode = newMesh;
  105791. }
  105792. // Lights
  105793. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105794. var light = gltfRuntime.lights[node.light];
  105795. if (light) {
  105796. if (light.type === "ambient") {
  105797. var ambienLight = light[light.type];
  105798. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105799. hemiLight.name = node.name || "";
  105800. if (ambienLight.color) {
  105801. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  105802. }
  105803. lastNode = hemiLight;
  105804. }
  105805. else if (light.type === "directional") {
  105806. var directionalLight = light[light.type];
  105807. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105808. dirLight.name = node.name || "";
  105809. if (directionalLight.color) {
  105810. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  105811. }
  105812. lastNode = dirLight;
  105813. }
  105814. else if (light.type === "point") {
  105815. var pointLight = light[light.type];
  105816. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  105817. ptLight.name = node.name || "";
  105818. if (pointLight.color) {
  105819. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  105820. }
  105821. lastNode = ptLight;
  105822. }
  105823. else if (light.type === "spot") {
  105824. var spotLight = light[light.type];
  105825. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  105826. spLight.name = node.name || "";
  105827. if (spotLight.color) {
  105828. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  105829. }
  105830. if (spotLight.fallOfAngle) {
  105831. spLight.angle = spotLight.fallOfAngle;
  105832. }
  105833. if (spotLight.fallOffExponent) {
  105834. spLight.exponent = spotLight.fallOffExponent;
  105835. }
  105836. lastNode = spLight;
  105837. }
  105838. }
  105839. }
  105840. // Cameras
  105841. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  105842. var camera = gltfRuntime.cameras[node.camera];
  105843. if (camera) {
  105844. if (camera.type === "orthographic") {
  105845. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  105846. orthoCamera.name = node.name || "";
  105847. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105848. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105849. lastNode = orthoCamera;
  105850. }
  105851. else if (camera.type === "perspective") {
  105852. var perspectiveCamera = camera[camera.type];
  105853. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  105854. persCamera.name = node.name || "";
  105855. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  105856. if (!perspectiveCamera.aspectRatio) {
  105857. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  105858. }
  105859. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  105860. persCamera.maxZ = perspectiveCamera.zfar;
  105861. persCamera.minZ = perspectiveCamera.znear;
  105862. }
  105863. lastNode = persCamera;
  105864. }
  105865. }
  105866. }
  105867. // Empty node
  105868. if (!node.jointName) {
  105869. if (node.babylonNode) {
  105870. return node.babylonNode;
  105871. }
  105872. else if (lastNode === null) {
  105873. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105874. node.babylonNode = dummy;
  105875. lastNode = dummy;
  105876. }
  105877. }
  105878. if (lastNode !== null) {
  105879. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  105880. configureNodeFromMatrix(lastNode, node, parent);
  105881. }
  105882. else {
  105883. var translation = node.translation || [0, 0, 0];
  105884. var rotation = node.rotation || [0, 0, 0, 1];
  105885. var scale = node.scale || [1, 1, 1];
  105886. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  105887. }
  105888. lastNode.updateCache(true);
  105889. node.babylonNode = lastNode;
  105890. }
  105891. return lastNode;
  105892. };
  105893. /**
  105894. * Traverses nodes and creates them
  105895. */
  105896. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  105897. if (meshIncluded === void 0) { meshIncluded = false; }
  105898. var node = gltfRuntime.nodes[id];
  105899. var newNode = null;
  105900. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  105901. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  105902. meshIncluded = true;
  105903. }
  105904. else {
  105905. meshIncluded = false;
  105906. }
  105907. }
  105908. else {
  105909. meshIncluded = true;
  105910. }
  105911. if (!node.jointName && meshIncluded) {
  105912. newNode = importNode(gltfRuntime, node, id, parent);
  105913. if (newNode !== null) {
  105914. newNode.id = id;
  105915. newNode.parent = parent;
  105916. }
  105917. }
  105918. if (node.children) {
  105919. for (var i = 0; i < node.children.length; i++) {
  105920. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  105921. }
  105922. }
  105923. };
  105924. /**
  105925. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  105926. */
  105927. var postLoad = function (gltfRuntime) {
  105928. // Nodes
  105929. var currentScene = gltfRuntime.currentScene;
  105930. if (currentScene) {
  105931. for (var i = 0; i < currentScene.nodes.length; i++) {
  105932. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105933. }
  105934. }
  105935. else {
  105936. for (var thing in gltfRuntime.scenes) {
  105937. currentScene = gltfRuntime.scenes[thing];
  105938. for (var i = 0; i < currentScene.nodes.length; i++) {
  105939. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105940. }
  105941. }
  105942. }
  105943. // Set animations
  105944. loadAnimations(gltfRuntime);
  105945. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  105946. var skeleton = gltfRuntime.scene.skeletons[i];
  105947. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  105948. }
  105949. };
  105950. /**
  105951. * onBind shaderrs callback to set uniforms and matrices
  105952. */
  105953. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  105954. var materialValues = material.values || technique.parameters;
  105955. for (var unif in unTreatedUniforms) {
  105956. var uniform = unTreatedUniforms[unif];
  105957. var type = uniform.type;
  105958. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  105959. if (uniform.semantic && !uniform.source && !uniform.node) {
  105960. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  105961. }
  105962. else if (uniform.semantic && (uniform.source || uniform.node)) {
  105963. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  105964. if (source === null) {
  105965. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  105966. }
  105967. if (source === null) {
  105968. continue;
  105969. }
  105970. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  105971. }
  105972. }
  105973. else {
  105974. var value = materialValues[technique.uniforms[unif]];
  105975. if (!value) {
  105976. continue;
  105977. }
  105978. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  105979. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  105980. if (texture === null || texture === undefined) {
  105981. continue;
  105982. }
  105983. shaderMaterial.getEffect().setTexture(unif, texture);
  105984. }
  105985. else {
  105986. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  105987. }
  105988. }
  105989. }
  105990. onSuccess(shaderMaterial);
  105991. };
  105992. /**
  105993. * Prepare uniforms to send the only one time
  105994. * Loads the appropriate textures
  105995. */
  105996. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  105997. var materialValues = material.values || technique.parameters;
  105998. var techniqueUniforms = technique.uniforms;
  105999. /**
  106000. * Prepare values here (not matrices)
  106001. */
  106002. for (var unif in unTreatedUniforms) {
  106003. var uniform = unTreatedUniforms[unif];
  106004. var type = uniform.type;
  106005. var value = materialValues[techniqueUniforms[unif]];
  106006. if (value === undefined) {
  106007. // In case the value is the same for all materials
  106008. value = uniform.value;
  106009. }
  106010. if (!value) {
  106011. continue;
  106012. }
  106013. var onLoadTexture = function (uniformName) {
  106014. return function (texture) {
  106015. if (uniform.value && uniformName) {
  106016. // Static uniform
  106017. shaderMaterial.setTexture(uniformName, texture);
  106018. delete unTreatedUniforms[uniformName];
  106019. }
  106020. };
  106021. };
  106022. // Texture (sampler2D)
  106023. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106024. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  106025. }
  106026. // Others
  106027. else {
  106028. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  106029. // Static uniform
  106030. delete unTreatedUniforms[unif];
  106031. }
  106032. }
  106033. }
  106034. };
  106035. /**
  106036. * Shader compilation failed
  106037. */
  106038. var onShaderCompileError = function (program, shaderMaterial, onError) {
  106039. return function (effect, error) {
  106040. shaderMaterial.dispose(true);
  106041. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  106042. };
  106043. };
  106044. /**
  106045. * Shader compilation success
  106046. */
  106047. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  106048. return function (_) {
  106049. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  106050. shaderMaterial.onBind = function (mesh) {
  106051. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  106052. };
  106053. };
  106054. };
  106055. /**
  106056. * Returns the appropriate uniform if already handled by babylon
  106057. */
  106058. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  106059. for (var unif in technique.uniforms) {
  106060. var uniform = technique.uniforms[unif];
  106061. var uniformParameter = technique.parameters[uniform];
  106062. if (tokenizer.currentIdentifier === unif) {
  106063. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  106064. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106065. if (transformIndex !== -1) {
  106066. delete unTreatedUniforms[unif];
  106067. return babylonTransforms[transformIndex];
  106068. }
  106069. }
  106070. }
  106071. }
  106072. return tokenizer.currentIdentifier;
  106073. };
  106074. /**
  106075. * All shaders loaded. Create materials one by one
  106076. */
  106077. var importMaterials = function (gltfRuntime) {
  106078. // Create materials
  106079. for (var mat in gltfRuntime.materials) {
  106080. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  106081. }
  106082. };
  106083. /**
  106084. * Implementation of the base glTF spec
  106085. */
  106086. var GLTFLoaderBase = /** @class */ (function () {
  106087. function GLTFLoaderBase() {
  106088. }
  106089. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  106090. var gltfRuntime = {
  106091. extensions: {},
  106092. accessors: {},
  106093. buffers: {},
  106094. bufferViews: {},
  106095. meshes: {},
  106096. lights: {},
  106097. cameras: {},
  106098. nodes: {},
  106099. images: {},
  106100. textures: {},
  106101. shaders: {},
  106102. programs: {},
  106103. samplers: {},
  106104. techniques: {},
  106105. materials: {},
  106106. animations: {},
  106107. skins: {},
  106108. extensionsUsed: [],
  106109. scenes: {},
  106110. buffersCount: 0,
  106111. shaderscount: 0,
  106112. scene: scene,
  106113. rootUrl: rootUrl,
  106114. loadedBufferCount: 0,
  106115. loadedBufferViews: {},
  106116. loadedShaderCount: 0,
  106117. importOnlyMeshes: false,
  106118. dummyNodes: []
  106119. };
  106120. // Parse
  106121. if (parsedData.extensions) {
  106122. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  106123. }
  106124. if (parsedData.extensionsUsed) {
  106125. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  106126. }
  106127. if (parsedData.buffers) {
  106128. parseBuffers(parsedData.buffers, gltfRuntime);
  106129. }
  106130. if (parsedData.bufferViews) {
  106131. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  106132. }
  106133. if (parsedData.accessors) {
  106134. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  106135. }
  106136. if (parsedData.meshes) {
  106137. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  106138. }
  106139. if (parsedData.lights) {
  106140. parseObject(parsedData.lights, "lights", gltfRuntime);
  106141. }
  106142. if (parsedData.cameras) {
  106143. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  106144. }
  106145. if (parsedData.nodes) {
  106146. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  106147. }
  106148. if (parsedData.images) {
  106149. parseObject(parsedData.images, "images", gltfRuntime);
  106150. }
  106151. if (parsedData.textures) {
  106152. parseObject(parsedData.textures, "textures", gltfRuntime);
  106153. }
  106154. if (parsedData.shaders) {
  106155. parseShaders(parsedData.shaders, gltfRuntime);
  106156. }
  106157. if (parsedData.programs) {
  106158. parseObject(parsedData.programs, "programs", gltfRuntime);
  106159. }
  106160. if (parsedData.samplers) {
  106161. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  106162. }
  106163. if (parsedData.techniques) {
  106164. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  106165. }
  106166. if (parsedData.materials) {
  106167. parseObject(parsedData.materials, "materials", gltfRuntime);
  106168. }
  106169. if (parsedData.animations) {
  106170. parseObject(parsedData.animations, "animations", gltfRuntime);
  106171. }
  106172. if (parsedData.skins) {
  106173. parseObject(parsedData.skins, "skins", gltfRuntime);
  106174. }
  106175. if (parsedData.scenes) {
  106176. gltfRuntime.scenes = parsedData.scenes;
  106177. }
  106178. if (parsedData.scene && parsedData.scenes) {
  106179. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  106180. }
  106181. return gltfRuntime;
  106182. };
  106183. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106184. var buffer = gltfRuntime.buffers[id];
  106185. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  106186. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  106187. }
  106188. else {
  106189. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  106190. if (request) {
  106191. onError(request.status + " " + request.statusText);
  106192. }
  106193. });
  106194. }
  106195. };
  106196. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106197. var texture = gltfRuntime.textures[id];
  106198. if (!texture || !texture.source) {
  106199. onError("");
  106200. return;
  106201. }
  106202. if (texture.babylonTexture) {
  106203. onSuccess(null);
  106204. return;
  106205. }
  106206. var source = gltfRuntime.images[texture.source];
  106207. if (BABYLON.Tools.IsBase64(source.uri)) {
  106208. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  106209. }
  106210. else {
  106211. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  106212. if (request) {
  106213. onError(request.status + " " + request.statusText);
  106214. }
  106215. });
  106216. }
  106217. };
  106218. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106219. var texture = gltfRuntime.textures[id];
  106220. if (texture.babylonTexture) {
  106221. onSuccess(texture.babylonTexture);
  106222. return;
  106223. }
  106224. var sampler = gltfRuntime.samplers[texture.sampler];
  106225. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  106226. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  106227. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  106228. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  106229. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106230. var blob = new Blob([buffer]);
  106231. var blobURL = URL.createObjectURL(blob);
  106232. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  106233. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  106234. if (sampler.wrapS !== undefined) {
  106235. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  106236. }
  106237. if (sampler.wrapT !== undefined) {
  106238. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  106239. }
  106240. newTexture.name = id;
  106241. texture.babylonTexture = newTexture;
  106242. onSuccess(newTexture);
  106243. };
  106244. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106245. var shader = gltfRuntime.shaders[id];
  106246. if (BABYLON.Tools.IsBase64(shader.uri)) {
  106247. var shaderString = atob(shader.uri.split(",")[1]);
  106248. if (onSuccess) {
  106249. onSuccess(shaderString);
  106250. }
  106251. }
  106252. else {
  106253. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  106254. if (request && onError) {
  106255. onError(request.status + " " + request.statusText);
  106256. }
  106257. });
  106258. }
  106259. };
  106260. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106261. var material = gltfRuntime.materials[id];
  106262. if (!material.technique) {
  106263. if (onError) {
  106264. onError("No technique found.");
  106265. }
  106266. return;
  106267. }
  106268. var technique = gltfRuntime.techniques[material.technique];
  106269. if (!technique) {
  106270. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  106271. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  106272. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106273. onSuccess(defaultMaterial);
  106274. return;
  106275. }
  106276. var program = gltfRuntime.programs[technique.program];
  106277. var states = technique.states;
  106278. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  106279. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  106280. var newVertexShader = "";
  106281. var newPixelShader = "";
  106282. var vertexTokenizer = new Tokenizer(vertexShader);
  106283. var pixelTokenizer = new Tokenizer(pixelShader);
  106284. var unTreatedUniforms = {};
  106285. var uniforms = [];
  106286. var attributes = [];
  106287. var samplers = [];
  106288. // Fill uniform, sampler2D and attributes
  106289. for (var unif in technique.uniforms) {
  106290. var uniform = technique.uniforms[unif];
  106291. var uniformParameter = technique.parameters[uniform];
  106292. unTreatedUniforms[unif] = uniformParameter;
  106293. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  106294. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106295. if (transformIndex !== -1) {
  106296. uniforms.push(babylonTransforms[transformIndex]);
  106297. delete unTreatedUniforms[unif];
  106298. }
  106299. else {
  106300. uniforms.push(unif);
  106301. }
  106302. }
  106303. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  106304. samplers.push(unif);
  106305. }
  106306. else {
  106307. uniforms.push(unif);
  106308. }
  106309. }
  106310. for (var attr in technique.attributes) {
  106311. var attribute = technique.attributes[attr];
  106312. var attributeParameter = technique.parameters[attribute];
  106313. if (attributeParameter.semantic) {
  106314. attributes.push(getAttribute(attributeParameter));
  106315. }
  106316. }
  106317. // Configure vertex shader
  106318. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  106319. var tokenType = vertexTokenizer.currentToken;
  106320. if (tokenType !== ETokenType.IDENTIFIER) {
  106321. newVertexShader += vertexTokenizer.currentString;
  106322. continue;
  106323. }
  106324. var foundAttribute = false;
  106325. for (var attr in technique.attributes) {
  106326. var attribute = technique.attributes[attr];
  106327. var attributeParameter = technique.parameters[attribute];
  106328. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  106329. newVertexShader += getAttribute(attributeParameter);
  106330. foundAttribute = true;
  106331. break;
  106332. }
  106333. }
  106334. if (foundAttribute) {
  106335. continue;
  106336. }
  106337. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  106338. }
  106339. // Configure pixel shader
  106340. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  106341. var tokenType = pixelTokenizer.currentToken;
  106342. if (tokenType !== ETokenType.IDENTIFIER) {
  106343. newPixelShader += pixelTokenizer.currentString;
  106344. continue;
  106345. }
  106346. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  106347. }
  106348. // Create shader material
  106349. var shaderPath = {
  106350. vertex: program.vertexShader + id,
  106351. fragment: program.fragmentShader + id
  106352. };
  106353. var options = {
  106354. attributes: attributes,
  106355. uniforms: uniforms,
  106356. samplers: samplers,
  106357. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  106358. };
  106359. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  106360. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  106361. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  106362. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  106363. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  106364. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106365. if (states && states.functions) {
  106366. var functions = states.functions;
  106367. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  106368. shaderMaterial.backFaceCulling = false;
  106369. }
  106370. var blendFunc = functions.blendFuncSeparate;
  106371. if (blendFunc) {
  106372. 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) {
  106373. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  106374. }
  106375. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106376. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  106377. }
  106378. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106379. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  106380. }
  106381. 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) {
  106382. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  106383. }
  106384. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106385. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  106386. }
  106387. 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) {
  106388. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  106389. }
  106390. }
  106391. }
  106392. };
  106393. return GLTFLoaderBase;
  106394. }());
  106395. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  106396. /**
  106397. * glTF V1 Loader
  106398. */
  106399. var GLTFLoader = /** @class */ (function () {
  106400. function GLTFLoader() {
  106401. // #region Stubs for IGLTFLoader interface
  106402. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  106403. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  106404. this.compileMaterials = false;
  106405. this.useClipPlane = false;
  106406. this.compileShadowGenerators = false;
  106407. this.transparencyAsCoverage = false;
  106408. this._normalizeAnimationGroupsToBeginAtZero = true;
  106409. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106410. this.onMeshLoadedObservable = new BABYLON.Observable();
  106411. this.onTextureLoadedObservable = new BABYLON.Observable();
  106412. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106413. this.onCameraLoadedObservable = new BABYLON.Observable();
  106414. this.onCompleteObservable = new BABYLON.Observable();
  106415. this.onDisposeObservable = new BABYLON.Observable();
  106416. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106417. this.state = null;
  106418. }
  106419. GLTFLoader.RegisterExtension = function (extension) {
  106420. if (GLTFLoader.Extensions[extension.name]) {
  106421. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  106422. return;
  106423. }
  106424. GLTFLoader.Extensions[extension.name] = extension;
  106425. };
  106426. GLTFLoader.prototype.dispose = function () { };
  106427. // #endregion
  106428. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  106429. var _this = this;
  106430. scene.useRightHandedSystem = true;
  106431. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106432. gltfRuntime.importOnlyMeshes = true;
  106433. if (meshesNames === "") {
  106434. gltfRuntime.importMeshesNames = [];
  106435. }
  106436. else if (typeof meshesNames === "string") {
  106437. gltfRuntime.importMeshesNames = [meshesNames];
  106438. }
  106439. else if (meshesNames && !(meshesNames instanceof Array)) {
  106440. gltfRuntime.importMeshesNames = [meshesNames];
  106441. }
  106442. else {
  106443. gltfRuntime.importMeshesNames = [];
  106444. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  106445. }
  106446. // Create nodes
  106447. _this._createNodes(gltfRuntime);
  106448. var meshes = new Array();
  106449. var skeletons = new Array();
  106450. // Fill arrays of meshes and skeletons
  106451. for (var nde in gltfRuntime.nodes) {
  106452. var node = gltfRuntime.nodes[nde];
  106453. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  106454. meshes.push(node.babylonNode);
  106455. }
  106456. }
  106457. for (var skl in gltfRuntime.skins) {
  106458. var skin = gltfRuntime.skins[skl];
  106459. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  106460. skeletons.push(skin.babylonSkeleton);
  106461. }
  106462. }
  106463. // Load buffers, shaders, materials, etc.
  106464. _this._loadBuffersAsync(gltfRuntime, function () {
  106465. _this._loadShadersAsync(gltfRuntime, function () {
  106466. importMaterials(gltfRuntime);
  106467. postLoad(gltfRuntime);
  106468. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106469. onSuccess(meshes, skeletons);
  106470. }
  106471. });
  106472. }, onProgress);
  106473. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106474. onSuccess(meshes, skeletons);
  106475. }
  106476. }, onError);
  106477. return true;
  106478. };
  106479. /**
  106480. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  106481. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  106482. * @param scene the scene the meshes should be added to
  106483. * @param data gltf data containing information of the meshes in a loaded file
  106484. * @param rootUrl root url to load from
  106485. * @param onProgress event that fires when loading progress has occured
  106486. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  106487. */
  106488. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106489. var _this = this;
  106490. return new Promise(function (resolve, reject) {
  106491. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  106492. resolve({
  106493. meshes: meshes,
  106494. particleSystems: [],
  106495. skeletons: skeletons,
  106496. animationGroups: []
  106497. });
  106498. }, onProgress, function (message) {
  106499. reject(new Error(message));
  106500. });
  106501. });
  106502. };
  106503. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  106504. var _this = this;
  106505. scene.useRightHandedSystem = true;
  106506. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106507. // Load runtime extensios
  106508. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  106509. // Create nodes
  106510. _this._createNodes(gltfRuntime);
  106511. // Load buffers, shaders, materials, etc.
  106512. _this._loadBuffersAsync(gltfRuntime, function () {
  106513. _this._loadShadersAsync(gltfRuntime, function () {
  106514. importMaterials(gltfRuntime);
  106515. postLoad(gltfRuntime);
  106516. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  106517. onSuccess();
  106518. }
  106519. });
  106520. });
  106521. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  106522. onSuccess();
  106523. }
  106524. }, onError);
  106525. }, onError);
  106526. };
  106527. /**
  106528. * Imports all objects from a loaded gltf file and adds them to the scene
  106529. * @param scene the scene the objects should be added to
  106530. * @param data gltf data containing information of the meshes in a loaded file
  106531. * @param rootUrl root url to load from
  106532. * @param onProgress event that fires when loading progress has occured
  106533. * @returns a promise which completes when objects have been loaded to the scene
  106534. */
  106535. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106536. var _this = this;
  106537. return new Promise(function (resolve, reject) {
  106538. _this._loadAsync(scene, data, rootUrl, function () {
  106539. resolve();
  106540. }, onProgress, function (message) {
  106541. reject(new Error(message));
  106542. });
  106543. });
  106544. };
  106545. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  106546. var hasShaders = false;
  106547. var processShader = function (sha, shader) {
  106548. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  106549. if (shaderString instanceof ArrayBuffer) {
  106550. return;
  106551. }
  106552. gltfRuntime.loadedShaderCount++;
  106553. if (shaderString) {
  106554. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  106555. }
  106556. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  106557. onload();
  106558. }
  106559. }, function () {
  106560. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  106561. });
  106562. };
  106563. for (var sha in gltfRuntime.shaders) {
  106564. hasShaders = true;
  106565. var shader = gltfRuntime.shaders[sha];
  106566. if (shader) {
  106567. processShader.bind(this, sha, shader)();
  106568. }
  106569. else {
  106570. BABYLON.Tools.Error("No shader named: " + sha);
  106571. }
  106572. }
  106573. if (!hasShaders) {
  106574. onload();
  106575. }
  106576. };
  106577. ;
  106578. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  106579. var hasBuffers = false;
  106580. var processBuffer = function (buf, buffer) {
  106581. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  106582. gltfRuntime.loadedBufferCount++;
  106583. if (bufferView) {
  106584. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  106585. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  106586. }
  106587. gltfRuntime.loadedBufferViews[buf] = bufferView;
  106588. }
  106589. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  106590. onLoad();
  106591. }
  106592. }, function () {
  106593. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  106594. });
  106595. };
  106596. for (var buf in gltfRuntime.buffers) {
  106597. hasBuffers = true;
  106598. var buffer = gltfRuntime.buffers[buf];
  106599. if (buffer) {
  106600. processBuffer.bind(this, buf, buffer)();
  106601. }
  106602. else {
  106603. BABYLON.Tools.Error("No buffer named: " + buf);
  106604. }
  106605. }
  106606. if (!hasBuffers) {
  106607. onLoad();
  106608. }
  106609. };
  106610. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  106611. var currentScene = gltfRuntime.currentScene;
  106612. if (currentScene) {
  106613. // Only one scene even if multiple scenes are defined
  106614. for (var i = 0; i < currentScene.nodes.length; i++) {
  106615. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106616. }
  106617. }
  106618. else {
  106619. // Load all scenes
  106620. for (var thing in gltfRuntime.scenes) {
  106621. currentScene = gltfRuntime.scenes[thing];
  106622. for (var i = 0; i < currentScene.nodes.length; i++) {
  106623. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106624. }
  106625. }
  106626. }
  106627. };
  106628. GLTFLoader.Extensions = {};
  106629. return GLTFLoader;
  106630. }());
  106631. GLTF1.GLTFLoader = GLTFLoader;
  106632. ;
  106633. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  106634. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106635. })(BABYLON || (BABYLON = {}));
  106636. //# sourceMappingURL=babylon.glTFLoader.js.map
  106637. var BABYLON;
  106638. (function (BABYLON) {
  106639. var GLTF1;
  106640. (function (GLTF1) {
  106641. /**
  106642. * Utils functions for GLTF
  106643. */
  106644. var GLTFUtils = /** @class */ (function () {
  106645. function GLTFUtils() {
  106646. }
  106647. /**
  106648. * Sets the given "parameter" matrix
  106649. * @param scene: the {BABYLON.Scene} object
  106650. * @param source: the source node where to pick the matrix
  106651. * @param parameter: the GLTF technique parameter
  106652. * @param uniformName: the name of the shader's uniform
  106653. * @param shaderMaterial: the shader material
  106654. */
  106655. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  106656. var mat = null;
  106657. if (parameter.semantic === "MODEL") {
  106658. mat = source.getWorldMatrix();
  106659. }
  106660. else if (parameter.semantic === "PROJECTION") {
  106661. mat = scene.getProjectionMatrix();
  106662. }
  106663. else if (parameter.semantic === "VIEW") {
  106664. mat = scene.getViewMatrix();
  106665. }
  106666. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  106667. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  106668. }
  106669. else if (parameter.semantic === "MODELVIEW") {
  106670. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  106671. }
  106672. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  106673. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  106674. }
  106675. else if (parameter.semantic === "MODELINVERSE") {
  106676. mat = source.getWorldMatrix().invert();
  106677. }
  106678. else if (parameter.semantic === "VIEWINVERSE") {
  106679. mat = scene.getViewMatrix().invert();
  106680. }
  106681. else if (parameter.semantic === "PROJECTIONINVERSE") {
  106682. mat = scene.getProjectionMatrix().invert();
  106683. }
  106684. else if (parameter.semantic === "MODELVIEWINVERSE") {
  106685. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  106686. }
  106687. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  106688. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  106689. }
  106690. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  106691. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  106692. }
  106693. else {
  106694. debugger;
  106695. }
  106696. if (mat) {
  106697. switch (parameter.type) {
  106698. case GLTF1.EParameterType.FLOAT_MAT2:
  106699. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  106700. break;
  106701. case GLTF1.EParameterType.FLOAT_MAT3:
  106702. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  106703. break;
  106704. case GLTF1.EParameterType.FLOAT_MAT4:
  106705. shaderMaterial.setMatrix(uniformName, mat);
  106706. break;
  106707. default: break;
  106708. }
  106709. }
  106710. };
  106711. /**
  106712. * Sets the given "parameter" matrix
  106713. * @param shaderMaterial: the shader material
  106714. * @param uniform: the name of the shader's uniform
  106715. * @param value: the value of the uniform
  106716. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  106717. */
  106718. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  106719. switch (type) {
  106720. case GLTF1.EParameterType.FLOAT:
  106721. shaderMaterial.setFloat(uniform, value);
  106722. return true;
  106723. case GLTF1.EParameterType.FLOAT_VEC2:
  106724. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  106725. return true;
  106726. case GLTF1.EParameterType.FLOAT_VEC3:
  106727. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  106728. return true;
  106729. case GLTF1.EParameterType.FLOAT_VEC4:
  106730. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  106731. return true;
  106732. default: return false;
  106733. }
  106734. };
  106735. /**
  106736. * Returns the wrap mode of the texture
  106737. * @param mode: the mode value
  106738. */
  106739. GLTFUtils.GetWrapMode = function (mode) {
  106740. switch (mode) {
  106741. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  106742. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  106743. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106744. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106745. }
  106746. };
  106747. /**
  106748. * Returns the byte stride giving an accessor
  106749. * @param accessor: the GLTF accessor objet
  106750. */
  106751. GLTFUtils.GetByteStrideFromType = function (accessor) {
  106752. // Needs this function since "byteStride" isn't requiered in glTF format
  106753. var type = accessor.type;
  106754. switch (type) {
  106755. case "VEC2": return 2;
  106756. case "VEC3": return 3;
  106757. case "VEC4": return 4;
  106758. case "MAT2": return 4;
  106759. case "MAT3": return 9;
  106760. case "MAT4": return 16;
  106761. default: return 1;
  106762. }
  106763. };
  106764. /**
  106765. * Returns the texture filter mode giving a mode value
  106766. * @param mode: the filter mode value
  106767. */
  106768. GLTFUtils.GetTextureFilterMode = function (mode) {
  106769. switch (mode) {
  106770. case GLTF1.ETextureFilterType.LINEAR:
  106771. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  106772. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106773. case GLTF1.ETextureFilterType.NEAREST:
  106774. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  106775. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106776. }
  106777. };
  106778. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  106779. var byteOffset = bufferView.byteOffset + byteOffset;
  106780. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  106781. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  106782. throw new Error("Buffer access is out of range");
  106783. }
  106784. var buffer = loadedBufferView.buffer;
  106785. byteOffset += loadedBufferView.byteOffset;
  106786. switch (componentType) {
  106787. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  106788. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  106789. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  106790. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  106791. default: return new Float32Array(buffer, byteOffset, byteLength);
  106792. }
  106793. };
  106794. /**
  106795. * Returns a buffer from its accessor
  106796. * @param gltfRuntime: the GLTF runtime
  106797. * @param accessor: the GLTF accessor
  106798. */
  106799. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  106800. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  106801. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  106802. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  106803. };
  106804. /**
  106805. * Decodes a buffer view into a string
  106806. * @param view: the buffer view
  106807. */
  106808. GLTFUtils.DecodeBufferToText = function (view) {
  106809. var result = "";
  106810. var length = view.byteLength;
  106811. for (var i = 0; i < length; ++i) {
  106812. result += String.fromCharCode(view[i]);
  106813. }
  106814. return result;
  106815. };
  106816. /**
  106817. * Returns the default material of gltf. Related to
  106818. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  106819. * @param scene: the Babylon.js scene
  106820. */
  106821. GLTFUtils.GetDefaultMaterial = function (scene) {
  106822. if (!GLTFUtils._DefaultMaterial) {
  106823. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  106824. "precision highp float;",
  106825. "",
  106826. "uniform mat4 worldView;",
  106827. "uniform mat4 projection;",
  106828. "",
  106829. "attribute vec3 position;",
  106830. "",
  106831. "void main(void)",
  106832. "{",
  106833. " gl_Position = projection * worldView * vec4(position, 1.0);",
  106834. "}"
  106835. ].join("\n");
  106836. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  106837. "precision highp float;",
  106838. "",
  106839. "uniform vec4 u_emission;",
  106840. "",
  106841. "void main(void)",
  106842. "{",
  106843. " gl_FragColor = u_emission;",
  106844. "}"
  106845. ].join("\n");
  106846. var shaderPath = {
  106847. vertex: "GLTFDefaultMaterial",
  106848. fragment: "GLTFDefaultMaterial"
  106849. };
  106850. var options = {
  106851. attributes: ["position"],
  106852. uniforms: ["worldView", "projection", "u_emission"],
  106853. samplers: new Array(),
  106854. needAlphaBlending: false
  106855. };
  106856. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  106857. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  106858. }
  106859. return GLTFUtils._DefaultMaterial;
  106860. };
  106861. // The GLTF default material
  106862. GLTFUtils._DefaultMaterial = null;
  106863. return GLTFUtils;
  106864. }());
  106865. GLTF1.GLTFUtils = GLTFUtils;
  106866. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106867. })(BABYLON || (BABYLON = {}));
  106868. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  106869. var BABYLON;
  106870. (function (BABYLON) {
  106871. var GLTF1;
  106872. (function (GLTF1) {
  106873. var GLTFLoaderExtension = /** @class */ (function () {
  106874. function GLTFLoaderExtension(name) {
  106875. this._name = name;
  106876. }
  106877. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  106878. get: function () {
  106879. return this._name;
  106880. },
  106881. enumerable: true,
  106882. configurable: true
  106883. });
  106884. /**
  106885. * Defines an override for loading the runtime
  106886. * Return true to stop further extensions from loading the runtime
  106887. */
  106888. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106889. return false;
  106890. };
  106891. /**
  106892. * Defines an onverride for creating gltf runtime
  106893. * Return true to stop further extensions from creating the runtime
  106894. */
  106895. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106896. return false;
  106897. };
  106898. /**
  106899. * Defines an override for loading buffers
  106900. * Return true to stop further extensions from loading this buffer
  106901. */
  106902. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106903. return false;
  106904. };
  106905. /**
  106906. * Defines an override for loading texture buffers
  106907. * Return true to stop further extensions from loading this texture data
  106908. */
  106909. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106910. return false;
  106911. };
  106912. /**
  106913. * Defines an override for creating textures
  106914. * Return true to stop further extensions from loading this texture
  106915. */
  106916. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106917. return false;
  106918. };
  106919. /**
  106920. * Defines an override for loading shader strings
  106921. * Return true to stop further extensions from loading this shader data
  106922. */
  106923. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106924. return false;
  106925. };
  106926. /**
  106927. * Defines an override for loading materials
  106928. * Return true to stop further extensions from loading this material
  106929. */
  106930. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106931. return false;
  106932. };
  106933. // ---------
  106934. // Utilities
  106935. // ---------
  106936. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  106937. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106938. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  106939. }, function () {
  106940. setTimeout(function () {
  106941. if (!onSuccess) {
  106942. return;
  106943. }
  106944. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  106945. });
  106946. });
  106947. };
  106948. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  106949. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106950. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  106951. }, function () {
  106952. setTimeout(function () {
  106953. onSuccess();
  106954. });
  106955. });
  106956. };
  106957. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106958. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106959. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  106960. }, function () {
  106961. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  106962. });
  106963. };
  106964. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  106965. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  106966. if (buffer) {
  106967. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106968. }
  106969. }, onError);
  106970. };
  106971. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106972. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106973. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  106974. }, function () {
  106975. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  106976. });
  106977. };
  106978. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106979. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106980. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  106981. }, function () {
  106982. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  106983. });
  106984. };
  106985. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106986. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106987. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  106988. }, function () {
  106989. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  106990. });
  106991. };
  106992. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106993. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  106994. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106995. }, function () {
  106996. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  106997. });
  106998. };
  106999. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  107000. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  107001. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  107002. if (func(loaderExtension)) {
  107003. return;
  107004. }
  107005. }
  107006. defaultFunc();
  107007. };
  107008. return GLTFLoaderExtension;
  107009. }());
  107010. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  107011. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107012. })(BABYLON || (BABYLON = {}));
  107013. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107014. var BABYLON;
  107015. (function (BABYLON) {
  107016. var GLTF1;
  107017. (function (GLTF1) {
  107018. var BinaryExtensionBufferName = "binary_glTF";
  107019. ;
  107020. ;
  107021. var GLTFBinaryExtension = /** @class */ (function (_super) {
  107022. __extends(GLTFBinaryExtension, _super);
  107023. function GLTFBinaryExtension() {
  107024. return _super.call(this, "KHR_binary_glTF") || this;
  107025. }
  107026. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107027. var extensionsUsed = data.json.extensionsUsed;
  107028. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  107029. return false;
  107030. }
  107031. this._bin = data.bin;
  107032. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107033. return true;
  107034. };
  107035. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107036. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  107037. return false;
  107038. }
  107039. if (id !== BinaryExtensionBufferName) {
  107040. return false;
  107041. }
  107042. onSuccess(this._bin);
  107043. return true;
  107044. };
  107045. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107046. var texture = gltfRuntime.textures[id];
  107047. var source = gltfRuntime.images[texture.source];
  107048. if (!source.extensions || !(this.name in source.extensions)) {
  107049. return false;
  107050. }
  107051. var sourceExt = source.extensions[this.name];
  107052. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  107053. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  107054. onSuccess(buffer);
  107055. return true;
  107056. };
  107057. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107058. var shader = gltfRuntime.shaders[id];
  107059. if (!shader.extensions || !(this.name in shader.extensions)) {
  107060. return false;
  107061. }
  107062. var binaryExtensionShader = shader.extensions[this.name];
  107063. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  107064. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  107065. setTimeout(function () {
  107066. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  107067. onSuccess(shaderString);
  107068. });
  107069. return true;
  107070. };
  107071. return GLTFBinaryExtension;
  107072. }(GLTF1.GLTFLoaderExtension));
  107073. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  107074. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  107075. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107076. })(BABYLON || (BABYLON = {}));
  107077. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  107078. var BABYLON;
  107079. (function (BABYLON) {
  107080. var GLTF1;
  107081. (function (GLTF1) {
  107082. ;
  107083. ;
  107084. ;
  107085. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  107086. __extends(GLTFMaterialsCommonExtension, _super);
  107087. function GLTFMaterialsCommonExtension() {
  107088. return _super.call(this, "KHR_materials_common") || this;
  107089. }
  107090. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107091. if (!gltfRuntime.extensions)
  107092. return false;
  107093. var extension = gltfRuntime.extensions[this.name];
  107094. if (!extension)
  107095. return false;
  107096. // Create lights
  107097. var lights = extension.lights;
  107098. if (lights) {
  107099. for (var thing in lights) {
  107100. var light = lights[thing];
  107101. switch (light.type) {
  107102. case "ambient":
  107103. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  107104. var ambient = light.ambient;
  107105. if (ambient) {
  107106. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  107107. }
  107108. break;
  107109. case "point":
  107110. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  107111. var point = light.point;
  107112. if (point) {
  107113. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  107114. }
  107115. break;
  107116. case "directional":
  107117. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  107118. var directional = light.directional;
  107119. if (directional) {
  107120. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  107121. }
  107122. break;
  107123. case "spot":
  107124. var spot = light.spot;
  107125. if (spot) {
  107126. 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);
  107127. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  107128. }
  107129. break;
  107130. default:
  107131. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  107132. break;
  107133. }
  107134. }
  107135. }
  107136. return false;
  107137. };
  107138. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107139. var material = gltfRuntime.materials[id];
  107140. if (!material || !material.extensions)
  107141. return false;
  107142. var extension = material.extensions[this.name];
  107143. if (!extension)
  107144. return false;
  107145. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107146. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107147. if (extension.technique === "CONSTANT") {
  107148. standardMaterial.disableLighting = true;
  107149. }
  107150. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  107151. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  107152. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  107153. // Ambient
  107154. if (typeof extension.values.ambient === "string") {
  107155. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  107156. }
  107157. else {
  107158. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  107159. }
  107160. // Diffuse
  107161. if (typeof extension.values.diffuse === "string") {
  107162. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  107163. }
  107164. else {
  107165. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  107166. }
  107167. // Emission
  107168. if (typeof extension.values.emission === "string") {
  107169. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  107170. }
  107171. else {
  107172. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  107173. }
  107174. // Specular
  107175. if (typeof extension.values.specular === "string") {
  107176. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  107177. }
  107178. else {
  107179. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  107180. }
  107181. return true;
  107182. };
  107183. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  107184. // Create buffer from texture url
  107185. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  107186. // Create texture from buffer
  107187. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  107188. }, onError);
  107189. };
  107190. return GLTFMaterialsCommonExtension;
  107191. }(GLTF1.GLTFLoaderExtension));
  107192. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  107193. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  107194. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107195. })(BABYLON || (BABYLON = {}));
  107196. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  107197. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  107198. /**
  107199. * Defines the module used to import/export glTF 2.0 assets
  107200. */
  107201. var BABYLON;
  107202. (function (BABYLON) {
  107203. var GLTF2;
  107204. (function (GLTF2) {
  107205. var _ArrayItem = /** @class */ (function () {
  107206. function _ArrayItem() {
  107207. }
  107208. _ArrayItem.Assign = function (values) {
  107209. if (values) {
  107210. for (var index = 0; index < values.length; index++) {
  107211. values[index]._index = index;
  107212. }
  107213. }
  107214. };
  107215. return _ArrayItem;
  107216. }());
  107217. /**
  107218. * Loader for loading a glTF 2.0 asset
  107219. */
  107220. var GLTFLoader = /** @class */ (function () {
  107221. function GLTFLoader() {
  107222. /** @hidden */
  107223. this._completePromises = new Array();
  107224. /** @hidden */
  107225. this._onReadyObservable = new BABYLON.Observable();
  107226. this._disposed = false;
  107227. this._state = null;
  107228. this._extensions = {};
  107229. this._defaultSampler = {};
  107230. this._defaultBabylonMaterials = {};
  107231. this._requests = new Array();
  107232. /**
  107233. * Mode that determines the coordinate system to use.
  107234. */
  107235. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107236. /**
  107237. * Mode that determines what animations will start.
  107238. */
  107239. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107240. /**
  107241. * Defines if the loader should compile materials.
  107242. */
  107243. this.compileMaterials = false;
  107244. /**
  107245. * Defines if the loader should also compile materials with clip planes.
  107246. */
  107247. this.useClipPlane = false;
  107248. /**
  107249. * Defines if the loader should compile shadow generators.
  107250. */
  107251. this.compileShadowGenerators = false;
  107252. /**
  107253. * Defines if the Alpha blended materials are only applied as coverage.
  107254. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  107255. * If true, no extra effects are applied to transparent pixels.
  107256. */
  107257. this.transparencyAsCoverage = false;
  107258. /** @hidden */
  107259. this._normalizeAnimationGroupsToBeginAtZero = true;
  107260. /**
  107261. * Function called before loading a url referenced by the asset.
  107262. */
  107263. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  107264. /**
  107265. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  107266. */
  107267. this.onMeshLoadedObservable = new BABYLON.Observable();
  107268. /**
  107269. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  107270. */
  107271. this.onTextureLoadedObservable = new BABYLON.Observable();
  107272. /**
  107273. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  107274. */
  107275. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107276. /**
  107277. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  107278. */
  107279. this.onCameraLoadedObservable = new BABYLON.Observable();
  107280. /**
  107281. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  107282. * For assets with LODs, raised when all of the LODs are complete.
  107283. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  107284. */
  107285. this.onCompleteObservable = new BABYLON.Observable();
  107286. /**
  107287. * Observable raised after the loader is disposed.
  107288. */
  107289. this.onDisposeObservable = new BABYLON.Observable();
  107290. /**
  107291. * Observable raised after a loader extension is created.
  107292. * Set additional options for a loader extension in this event.
  107293. */
  107294. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107295. }
  107296. /** @hidden */
  107297. GLTFLoader._Register = function (name, factory) {
  107298. if (GLTFLoader._ExtensionFactories[name]) {
  107299. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  107300. return;
  107301. }
  107302. GLTFLoader._ExtensionFactories[name] = factory;
  107303. // Keep the order of registration so that extensions registered first are called first.
  107304. GLTFLoader._ExtensionNames.push(name);
  107305. };
  107306. Object.defineProperty(GLTFLoader.prototype, "state", {
  107307. /**
  107308. * Loader state or null if the loader is not active.
  107309. */
  107310. get: function () {
  107311. return this._state;
  107312. },
  107313. enumerable: true,
  107314. configurable: true
  107315. });
  107316. /**
  107317. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  107318. */
  107319. GLTFLoader.prototype.dispose = function () {
  107320. if (this._disposed) {
  107321. return;
  107322. }
  107323. this._disposed = true;
  107324. this.onDisposeObservable.notifyObservers(this);
  107325. this.onDisposeObservable.clear();
  107326. this._clear();
  107327. };
  107328. /**
  107329. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  107330. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  107331. * @param scene the scene the meshes should be added to
  107332. * @param data the glTF data to load
  107333. * @param rootUrl root url to load from
  107334. * @param onProgress event that fires when loading progress has occured
  107335. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  107336. */
  107337. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107338. var _this = this;
  107339. return Promise.resolve().then(function () {
  107340. _this._babylonScene = scene;
  107341. _this._rootUrl = rootUrl;
  107342. _this._progressCallback = onProgress;
  107343. _this._loadData(data);
  107344. var nodes = null;
  107345. if (meshesNames) {
  107346. var nodeMap_1 = {};
  107347. if (_this._gltf.nodes) {
  107348. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  107349. var node = _a[_i];
  107350. if (node.name) {
  107351. nodeMap_1[node.name] = node;
  107352. }
  107353. }
  107354. }
  107355. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  107356. nodes = names.map(function (name) {
  107357. var node = nodeMap_1[name];
  107358. if (!node) {
  107359. throw new Error("Failed to find node '" + name + "'");
  107360. }
  107361. return node;
  107362. });
  107363. }
  107364. return _this._loadAsync(nodes).then(function () {
  107365. return {
  107366. meshes: _this._getMeshes(),
  107367. particleSystems: [],
  107368. skeletons: _this._getSkeletons(),
  107369. animationGroups: _this._getAnimationGroups()
  107370. };
  107371. });
  107372. });
  107373. };
  107374. /**
  107375. * Imports all objects from the loaded glTF data and adds them to the scene
  107376. * @param scene the scene the objects should be added to
  107377. * @param data the glTF data to load
  107378. * @param rootUrl root url to load from
  107379. * @param onProgress event that fires when loading progress has occured
  107380. * @returns a promise which completes when objects have been loaded to the scene
  107381. */
  107382. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107383. var _this = this;
  107384. return Promise.resolve().then(function () {
  107385. _this._babylonScene = scene;
  107386. _this._rootUrl = rootUrl;
  107387. _this._progressCallback = onProgress;
  107388. _this._loadData(data);
  107389. return _this._loadAsync(null);
  107390. });
  107391. };
  107392. GLTFLoader.prototype._loadAsync = function (nodes) {
  107393. var _this = this;
  107394. return Promise.resolve().then(function () {
  107395. _this._state = BABYLON.GLTFLoaderState.LOADING;
  107396. _this._loadExtensions();
  107397. _this._checkExtensions();
  107398. var promises = new Array();
  107399. if (nodes) {
  107400. promises.push(_this._loadNodesAsync(nodes));
  107401. }
  107402. else {
  107403. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  107404. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  107405. }
  107406. if (_this.compileMaterials) {
  107407. promises.push(_this._compileMaterialsAsync());
  107408. }
  107409. if (_this.compileShadowGenerators) {
  107410. promises.push(_this._compileShadowGeneratorsAsync());
  107411. }
  107412. var resultPromise = Promise.all(promises).then(function () {
  107413. _this._state = BABYLON.GLTFLoaderState.READY;
  107414. _this._onReadyObservable.notifyObservers(_this);
  107415. _this._startAnimations();
  107416. });
  107417. resultPromise.then(function () {
  107418. if (_this._rootBabylonMesh) {
  107419. _this._rootBabylonMesh.setEnabled(true);
  107420. }
  107421. BABYLON.Tools.SetImmediate(function () {
  107422. if (!_this._disposed) {
  107423. Promise.all(_this._completePromises).then(function () {
  107424. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  107425. _this.onCompleteObservable.notifyObservers(_this);
  107426. _this.onCompleteObservable.clear();
  107427. _this._clear();
  107428. }).catch(function (error) {
  107429. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107430. _this._clear();
  107431. });
  107432. }
  107433. });
  107434. });
  107435. return resultPromise;
  107436. }).catch(function (error) {
  107437. if (!_this._disposed) {
  107438. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107439. _this._clear();
  107440. throw error;
  107441. }
  107442. });
  107443. };
  107444. GLTFLoader.prototype._loadData = function (data) {
  107445. this._gltf = data.json;
  107446. this._setupData();
  107447. if (data.bin) {
  107448. var buffers = this._gltf.buffers;
  107449. if (buffers && buffers[0] && !buffers[0].uri) {
  107450. var binaryBuffer = buffers[0];
  107451. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  107452. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  107453. }
  107454. binaryBuffer._data = Promise.resolve(data.bin);
  107455. }
  107456. else {
  107457. BABYLON.Tools.Warn("Unexpected BIN chunk");
  107458. }
  107459. }
  107460. };
  107461. GLTFLoader.prototype._setupData = function () {
  107462. _ArrayItem.Assign(this._gltf.accessors);
  107463. _ArrayItem.Assign(this._gltf.animations);
  107464. _ArrayItem.Assign(this._gltf.buffers);
  107465. _ArrayItem.Assign(this._gltf.bufferViews);
  107466. _ArrayItem.Assign(this._gltf.cameras);
  107467. _ArrayItem.Assign(this._gltf.images);
  107468. _ArrayItem.Assign(this._gltf.materials);
  107469. _ArrayItem.Assign(this._gltf.meshes);
  107470. _ArrayItem.Assign(this._gltf.nodes);
  107471. _ArrayItem.Assign(this._gltf.samplers);
  107472. _ArrayItem.Assign(this._gltf.scenes);
  107473. _ArrayItem.Assign(this._gltf.skins);
  107474. _ArrayItem.Assign(this._gltf.textures);
  107475. if (this._gltf.nodes) {
  107476. var nodeParents = {};
  107477. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  107478. var node = _a[_i];
  107479. if (node.children) {
  107480. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  107481. var index = _c[_b];
  107482. nodeParents[index] = node._index;
  107483. }
  107484. }
  107485. }
  107486. var rootNode = this._createRootNode();
  107487. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  107488. var node = _e[_d];
  107489. var parentIndex = nodeParents[node._index];
  107490. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  107491. }
  107492. }
  107493. };
  107494. GLTFLoader.prototype._loadExtensions = function () {
  107495. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  107496. var name_1 = _a[_i];
  107497. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  107498. this._extensions[name_1] = extension;
  107499. this.onExtensionLoadedObservable.notifyObservers(extension);
  107500. }
  107501. this.onExtensionLoadedObservable.clear();
  107502. };
  107503. GLTFLoader.prototype._checkExtensions = function () {
  107504. if (this._gltf.extensionsRequired) {
  107505. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  107506. var name_2 = _a[_i];
  107507. var extension = this._extensions[name_2];
  107508. if (!extension || !extension.enabled) {
  107509. throw new Error("Require extension " + name_2 + " is not available");
  107510. }
  107511. }
  107512. }
  107513. };
  107514. GLTFLoader.prototype._createRootNode = function () {
  107515. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  107516. this._rootBabylonMesh.setEnabled(false);
  107517. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  107518. switch (this.coordinateSystemMode) {
  107519. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  107520. if (!this._babylonScene.useRightHandedSystem) {
  107521. rootNode.rotation = [0, 1, 0, 0];
  107522. rootNode.scale = [1, 1, -1];
  107523. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  107524. }
  107525. break;
  107526. }
  107527. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  107528. this._babylonScene.useRightHandedSystem = true;
  107529. break;
  107530. }
  107531. default: {
  107532. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  107533. }
  107534. }
  107535. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  107536. return rootNode;
  107537. };
  107538. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  107539. var promises = new Array();
  107540. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  107541. var node = nodes_1[_i];
  107542. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107543. }
  107544. promises.push(this._loadAnimationsAsync());
  107545. return Promise.all(promises).then(function () { });
  107546. };
  107547. /** @hidden */
  107548. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  107549. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  107550. if (promise) {
  107551. return promise;
  107552. }
  107553. var promises = new Array();
  107554. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  107555. var index = _a[_i];
  107556. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  107557. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107558. }
  107559. promises.push(this._loadAnimationsAsync());
  107560. return Promise.all(promises).then(function () { });
  107561. };
  107562. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  107563. if (node._primitiveBabylonMeshes) {
  107564. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107565. var babylonMesh = _a[_i];
  107566. callback(babylonMesh);
  107567. }
  107568. }
  107569. else {
  107570. callback(node._babylonMesh);
  107571. }
  107572. };
  107573. GLTFLoader.prototype._getMeshes = function () {
  107574. var meshes = new Array();
  107575. // Root mesh is always first.
  107576. meshes.push(this._rootBabylonMesh);
  107577. var nodes = this._gltf.nodes;
  107578. if (nodes) {
  107579. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  107580. var node = nodes_2[_i];
  107581. if (node._babylonMesh) {
  107582. meshes.push(node._babylonMesh);
  107583. }
  107584. if (node._primitiveBabylonMeshes) {
  107585. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  107586. var babylonMesh = _b[_a];
  107587. meshes.push(babylonMesh);
  107588. }
  107589. }
  107590. }
  107591. }
  107592. return meshes;
  107593. };
  107594. GLTFLoader.prototype._getSkeletons = function () {
  107595. var skeletons = new Array();
  107596. var skins = this._gltf.skins;
  107597. if (skins) {
  107598. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  107599. var skin = skins_1[_i];
  107600. if (skin._babylonSkeleton) {
  107601. skeletons.push(skin._babylonSkeleton);
  107602. }
  107603. }
  107604. }
  107605. return skeletons;
  107606. };
  107607. GLTFLoader.prototype._getAnimationGroups = function () {
  107608. var animationGroups = new Array();
  107609. var animations = this._gltf.animations;
  107610. if (animations) {
  107611. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  107612. var animation = animations_1[_i];
  107613. if (animation._babylonAnimationGroup) {
  107614. animationGroups.push(animation._babylonAnimationGroup);
  107615. }
  107616. }
  107617. }
  107618. return animationGroups;
  107619. };
  107620. GLTFLoader.prototype._startAnimations = function () {
  107621. switch (this.animationStartMode) {
  107622. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  107623. // do nothing
  107624. break;
  107625. }
  107626. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  107627. var babylonAnimationGroups = this._getAnimationGroups();
  107628. if (babylonAnimationGroups.length !== 0) {
  107629. babylonAnimationGroups[0].start(true);
  107630. }
  107631. break;
  107632. }
  107633. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  107634. var babylonAnimationGroups = this._getAnimationGroups();
  107635. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  107636. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  107637. babylonAnimationGroup.start(true);
  107638. }
  107639. break;
  107640. }
  107641. default: {
  107642. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  107643. return;
  107644. }
  107645. }
  107646. };
  107647. /** @hidden */
  107648. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  107649. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  107650. if (promise) {
  107651. return promise;
  107652. }
  107653. if (node._babylonMesh) {
  107654. throw new Error(context + ": Invalid recursive node hierarchy");
  107655. }
  107656. var promises = new Array();
  107657. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  107658. node._babylonMesh = babylonMesh;
  107659. GLTFLoader._LoadTransform(node, babylonMesh);
  107660. if (node.mesh != undefined) {
  107661. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  107662. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  107663. }
  107664. if (node.camera != undefined) {
  107665. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  107666. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  107667. }
  107668. if (node.children) {
  107669. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  107670. var index = _a[_i];
  107671. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  107672. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  107673. }
  107674. }
  107675. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107676. return Promise.all(promises).then(function () { });
  107677. };
  107678. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  107679. var _this = this;
  107680. var promises = new Array();
  107681. var primitives = mesh.primitives;
  107682. if (!primitives || primitives.length === 0) {
  107683. throw new Error(context + ": Primitives are missing");
  107684. }
  107685. _ArrayItem.Assign(primitives);
  107686. if (primitives.length === 1) {
  107687. var primitive = primitives[0];
  107688. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  107689. }
  107690. else {
  107691. node._primitiveBabylonMeshes = [];
  107692. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  107693. var primitive = primitives_1[_i];
  107694. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  107695. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  107696. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  107697. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107698. }
  107699. }
  107700. if (node.skin != undefined) {
  107701. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  107702. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  107703. }
  107704. return Promise.all(promises).then(function () {
  107705. _this._forEachPrimitive(node, function (babylonMesh) {
  107706. babylonMesh._refreshBoundingInfo(true);
  107707. });
  107708. });
  107709. };
  107710. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  107711. var _this = this;
  107712. var promises = new Array();
  107713. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  107714. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  107715. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  107716. babylonGeometry.applyToMesh(babylonMesh);
  107717. });
  107718. }));
  107719. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  107720. if (primitive.material == undefined) {
  107721. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  107722. }
  107723. else {
  107724. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  107725. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  107726. babylonMesh.material = babylonMaterial;
  107727. }));
  107728. }
  107729. return Promise.all(promises).then(function () { });
  107730. };
  107731. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107732. var _this = this;
  107733. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  107734. if (promise) {
  107735. return promise;
  107736. }
  107737. var attributes = primitive.attributes;
  107738. if (!attributes) {
  107739. throw new Error(context + ": Attributes are missing");
  107740. }
  107741. var promises = new Array();
  107742. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  107743. if (primitive.indices == undefined) {
  107744. babylonMesh.isUnIndexed = true;
  107745. }
  107746. else {
  107747. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  107748. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107749. babylonGeometry.setIndices(data);
  107750. }));
  107751. }
  107752. var loadAttribute = function (attribute, kind, callback) {
  107753. if (attributes[attribute] == undefined) {
  107754. return;
  107755. }
  107756. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107757. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107758. babylonMesh._delayInfo.push(kind);
  107759. }
  107760. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107761. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  107762. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  107763. }));
  107764. if (callback) {
  107765. callback(accessor);
  107766. }
  107767. };
  107768. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107769. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  107770. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  107771. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  107772. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  107773. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  107774. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  107775. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  107776. if (accessor.type === "VEC4" /* VEC4 */) {
  107777. babylonMesh.hasVertexAlpha = true;
  107778. }
  107779. });
  107780. return Promise.all(promises).then(function () {
  107781. return babylonGeometry;
  107782. });
  107783. };
  107784. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  107785. if (!primitive.targets) {
  107786. return;
  107787. }
  107788. if (node._numMorphTargets == undefined) {
  107789. node._numMorphTargets = primitive.targets.length;
  107790. }
  107791. else if (primitive.targets.length !== node._numMorphTargets) {
  107792. throw new Error(context + ": Primitives do not have the same number of targets");
  107793. }
  107794. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  107795. for (var index = 0; index < primitive.targets.length; index++) {
  107796. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  107797. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  107798. // TODO: tell the target whether it has positions, normals, tangents
  107799. }
  107800. };
  107801. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  107802. if (!primitive.targets) {
  107803. return Promise.resolve();
  107804. }
  107805. var promises = new Array();
  107806. var morphTargetManager = babylonMesh.morphTargetManager;
  107807. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  107808. var babylonMorphTarget = morphTargetManager.getTarget(index);
  107809. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  107810. }
  107811. return Promise.all(promises).then(function () { });
  107812. };
  107813. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  107814. var _this = this;
  107815. var promises = new Array();
  107816. var loadAttribute = function (attribute, kind, setData) {
  107817. if (attributes[attribute] == undefined) {
  107818. return;
  107819. }
  107820. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  107821. if (!babylonVertexBuffer) {
  107822. return;
  107823. }
  107824. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107825. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107826. setData(babylonVertexBuffer, data);
  107827. }));
  107828. };
  107829. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  107830. babylonVertexBuffer.forEach(data.length, function (value, index) {
  107831. data[index] += value;
  107832. });
  107833. babylonMorphTarget.setPositions(data);
  107834. });
  107835. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  107836. babylonVertexBuffer.forEach(data.length, function (value, index) {
  107837. data[index] += value;
  107838. });
  107839. babylonMorphTarget.setNormals(data);
  107840. });
  107841. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  107842. var dataIndex = 0;
  107843. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  107844. // Tangent data for morph targets is stored as xyz delta.
  107845. // The vertexData.tangent is stored as xyzw.
  107846. // So we need to skip every fourth vertexData.tangent.
  107847. if (((index + 1) % 4) !== 0) {
  107848. data[dataIndex++] += value;
  107849. }
  107850. });
  107851. babylonMorphTarget.setTangents(data);
  107852. });
  107853. return Promise.all(promises).then(function () { });
  107854. };
  107855. GLTFLoader._LoadTransform = function (node, babylonNode) {
  107856. var position = BABYLON.Vector3.Zero();
  107857. var rotation = BABYLON.Quaternion.Identity();
  107858. var scaling = BABYLON.Vector3.One();
  107859. if (node.matrix) {
  107860. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  107861. matrix.decompose(scaling, rotation, position);
  107862. }
  107863. else {
  107864. if (node.translation)
  107865. position = BABYLON.Vector3.FromArray(node.translation);
  107866. if (node.rotation)
  107867. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  107868. if (node.scale)
  107869. scaling = BABYLON.Vector3.FromArray(node.scale);
  107870. }
  107871. babylonNode.position = position;
  107872. babylonNode.rotationQuaternion = rotation;
  107873. babylonNode.scaling = scaling;
  107874. };
  107875. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  107876. var _this = this;
  107877. var assignSkeleton = function (skeleton) {
  107878. _this._forEachPrimitive(node, function (babylonMesh) {
  107879. babylonMesh.skeleton = skeleton;
  107880. });
  107881. // Ignore the TRS of skinned nodes.
  107882. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  107883. node._babylonMesh.parent = _this._rootBabylonMesh;
  107884. node._babylonMesh.position = BABYLON.Vector3.Zero();
  107885. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  107886. node._babylonMesh.scaling = BABYLON.Vector3.One();
  107887. };
  107888. if (skin._loaded) {
  107889. return skin._loaded.then(function () {
  107890. assignSkeleton(skin._babylonSkeleton);
  107891. });
  107892. }
  107893. var skeletonId = "skeleton" + skin._index;
  107894. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  107895. skin._babylonSkeleton = babylonSkeleton;
  107896. this._loadBones(context, skin);
  107897. assignSkeleton(babylonSkeleton);
  107898. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  107899. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  107900. }));
  107901. };
  107902. GLTFLoader.prototype._loadBones = function (context, skin) {
  107903. var babylonBones = {};
  107904. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  107905. var index = _a[_i];
  107906. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  107907. this._loadBone(node, skin, babylonBones);
  107908. }
  107909. };
  107910. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  107911. var babylonBone = babylonBones[node._index];
  107912. if (babylonBone) {
  107913. return babylonBone;
  107914. }
  107915. var babylonParentBone = null;
  107916. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  107917. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  107918. }
  107919. var boneIndex = skin.joints.indexOf(node._index);
  107920. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  107921. babylonBones[node._index] = babylonBone;
  107922. node._babylonBones = node._babylonBones || [];
  107923. node._babylonBones.push(babylonBone);
  107924. return babylonBone;
  107925. };
  107926. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  107927. if (skin.inverseBindMatrices == undefined) {
  107928. return Promise.resolve(null);
  107929. }
  107930. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  107931. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  107932. };
  107933. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  107934. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  107935. var babylonBone = _a[_i];
  107936. var baseMatrix = BABYLON.Matrix.Identity();
  107937. var boneIndex = babylonBone._index;
  107938. if (inverseBindMatricesData && boneIndex !== -1) {
  107939. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  107940. baseMatrix.invertToRef(baseMatrix);
  107941. }
  107942. var babylonParentBone = babylonBone.getParent();
  107943. if (babylonParentBone) {
  107944. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  107945. }
  107946. babylonBone.updateMatrix(baseMatrix, false, false);
  107947. babylonBone._updateDifferenceMatrix(undefined, false);
  107948. }
  107949. };
  107950. GLTFLoader.prototype._getNodeMatrix = function (node) {
  107951. return node.matrix ?
  107952. BABYLON.Matrix.FromArray(node.matrix) :
  107953. 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());
  107954. };
  107955. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  107956. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  107957. babylonCamera.parent = babylonMesh;
  107958. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  107959. switch (camera.type) {
  107960. case "perspective" /* PERSPECTIVE */: {
  107961. var perspective = camera.perspective;
  107962. if (!perspective) {
  107963. throw new Error(context + ": Camera perspective properties are missing");
  107964. }
  107965. babylonCamera.fov = perspective.yfov;
  107966. babylonCamera.minZ = perspective.znear;
  107967. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  107968. break;
  107969. }
  107970. case "orthographic" /* ORTHOGRAPHIC */: {
  107971. if (!camera.orthographic) {
  107972. throw new Error(context + ": Camera orthographic properties are missing");
  107973. }
  107974. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107975. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  107976. babylonCamera.orthoRight = camera.orthographic.xmag;
  107977. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  107978. babylonCamera.orthoTop = camera.orthographic.ymag;
  107979. babylonCamera.minZ = camera.orthographic.znear;
  107980. babylonCamera.maxZ = camera.orthographic.zfar;
  107981. break;
  107982. }
  107983. default: {
  107984. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  107985. }
  107986. }
  107987. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  107988. };
  107989. GLTFLoader.prototype._loadAnimationsAsync = function () {
  107990. var animations = this._gltf.animations;
  107991. if (!animations) {
  107992. return Promise.resolve();
  107993. }
  107994. var promises = new Array();
  107995. for (var index = 0; index < animations.length; index++) {
  107996. var animation = animations[index];
  107997. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  107998. }
  107999. return Promise.all(promises).then(function () { });
  108000. };
  108001. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  108002. var _this = this;
  108003. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  108004. animation._babylonAnimationGroup = babylonAnimationGroup;
  108005. var promises = new Array();
  108006. _ArrayItem.Assign(animation.channels);
  108007. _ArrayItem.Assign(animation.samplers);
  108008. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  108009. var channel = _a[_i];
  108010. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  108011. }
  108012. return Promise.all(promises).then(function () {
  108013. babylonAnimationGroup.normalize(_this._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  108014. });
  108015. };
  108016. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  108017. var _this = this;
  108018. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  108019. // Ignore animations that have no animation targets.
  108020. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  108021. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  108022. return Promise.resolve();
  108023. }
  108024. // Ignore animations targeting TRS of skinned nodes.
  108025. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  108026. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  108027. return Promise.resolve();
  108028. }
  108029. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  108030. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  108031. var targetPath;
  108032. var animationType;
  108033. switch (channel.target.path) {
  108034. case "translation" /* TRANSLATION */: {
  108035. targetPath = "position";
  108036. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108037. break;
  108038. }
  108039. case "rotation" /* ROTATION */: {
  108040. targetPath = "rotationQuaternion";
  108041. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108042. break;
  108043. }
  108044. case "scale" /* SCALE */: {
  108045. targetPath = "scaling";
  108046. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108047. break;
  108048. }
  108049. case "weights" /* WEIGHTS */: {
  108050. targetPath = "influence";
  108051. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  108052. break;
  108053. }
  108054. default: {
  108055. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  108056. }
  108057. }
  108058. var outputBufferOffset = 0;
  108059. var getNextOutputValue;
  108060. switch (targetPath) {
  108061. case "position": {
  108062. getNextOutputValue = function () {
  108063. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108064. outputBufferOffset += 3;
  108065. return value;
  108066. };
  108067. break;
  108068. }
  108069. case "rotationQuaternion": {
  108070. getNextOutputValue = function () {
  108071. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  108072. outputBufferOffset += 4;
  108073. return value;
  108074. };
  108075. break;
  108076. }
  108077. case "scaling": {
  108078. getNextOutputValue = function () {
  108079. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108080. outputBufferOffset += 3;
  108081. return value;
  108082. };
  108083. break;
  108084. }
  108085. case "influence": {
  108086. getNextOutputValue = function () {
  108087. var value = new Array(targetNode._numMorphTargets);
  108088. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  108089. value[i] = data.output[outputBufferOffset++];
  108090. }
  108091. return value;
  108092. };
  108093. break;
  108094. }
  108095. }
  108096. var getNextKey;
  108097. switch (data.interpolation) {
  108098. case "STEP" /* STEP */: {
  108099. getNextKey = function (frameIndex) { return ({
  108100. frame: data.input[frameIndex],
  108101. value: getNextOutputValue(),
  108102. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  108103. }); };
  108104. break;
  108105. }
  108106. case "LINEAR" /* LINEAR */: {
  108107. getNextKey = function (frameIndex) { return ({
  108108. frame: data.input[frameIndex],
  108109. value: getNextOutputValue()
  108110. }); };
  108111. break;
  108112. }
  108113. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108114. getNextKey = function (frameIndex) { return ({
  108115. frame: data.input[frameIndex],
  108116. inTangent: getNextOutputValue(),
  108117. value: getNextOutputValue(),
  108118. outTangent: getNextOutputValue()
  108119. }); };
  108120. break;
  108121. }
  108122. }
  108123. var keys = new Array(data.input.length);
  108124. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  108125. keys[frameIndex] = getNextKey(frameIndex);
  108126. }
  108127. if (targetPath === "influence") {
  108128. var _loop_1 = function (targetIndex) {
  108129. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  108130. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  108131. babylonAnimation.setKeys(keys.map(function (key) { return ({
  108132. frame: key.frame,
  108133. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  108134. value: key.value[targetIndex],
  108135. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  108136. }); }));
  108137. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  108138. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  108139. var babylonAnimationClone = babylonAnimation.clone();
  108140. morphTarget.animations.push(babylonAnimationClone);
  108141. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  108142. });
  108143. };
  108144. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  108145. _loop_1(targetIndex);
  108146. }
  108147. }
  108148. else {
  108149. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  108150. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  108151. babylonAnimation.setKeys(keys);
  108152. if (targetNode._babylonBones) {
  108153. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  108154. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  108155. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  108156. babylonAnimationTarget.animations.push(babylonAnimation);
  108157. }
  108158. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  108159. }
  108160. else {
  108161. targetNode._babylonMesh.animations.push(babylonAnimation);
  108162. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  108163. }
  108164. }
  108165. });
  108166. };
  108167. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  108168. if (sampler._data) {
  108169. return sampler._data;
  108170. }
  108171. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  108172. switch (interpolation) {
  108173. case "STEP" /* STEP */:
  108174. case "LINEAR" /* LINEAR */:
  108175. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108176. break;
  108177. }
  108178. default: {
  108179. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  108180. }
  108181. }
  108182. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  108183. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  108184. sampler._data = Promise.all([
  108185. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  108186. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  108187. ]).then(function (_a) {
  108188. var inputData = _a[0], outputData = _a[1];
  108189. return {
  108190. input: inputData,
  108191. interpolation: interpolation,
  108192. output: outputData,
  108193. };
  108194. });
  108195. return sampler._data;
  108196. };
  108197. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  108198. if (buffer._data) {
  108199. return buffer._data;
  108200. }
  108201. if (!buffer.uri) {
  108202. throw new Error(context + ": Uri is missing");
  108203. }
  108204. buffer._data = this._loadUriAsync(context, buffer.uri);
  108205. return buffer._data;
  108206. };
  108207. /** @hidden */
  108208. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  108209. if (bufferView._data) {
  108210. return bufferView._data;
  108211. }
  108212. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  108213. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  108214. try {
  108215. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  108216. }
  108217. catch (e) {
  108218. throw new Error(context + ": " + e.message);
  108219. }
  108220. });
  108221. return bufferView._data;
  108222. };
  108223. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  108224. if (accessor.type !== "SCALAR" /* SCALAR */) {
  108225. throw new Error(context + ": Invalid type " + accessor.type);
  108226. }
  108227. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  108228. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  108229. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  108230. throw new Error(context + ": Invalid component type " + accessor.componentType);
  108231. }
  108232. if (accessor._data) {
  108233. return accessor._data;
  108234. }
  108235. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108236. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  108237. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  108238. });
  108239. return accessor._data;
  108240. };
  108241. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  108242. // TODO: support normalized and stride
  108243. var _this = this;
  108244. if (accessor.componentType !== 5126 /* FLOAT */) {
  108245. throw new Error("Invalid component type " + accessor.componentType);
  108246. }
  108247. if (accessor._data) {
  108248. return accessor._data;
  108249. }
  108250. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  108251. var length = numComponents * accessor.count;
  108252. if (accessor.bufferView == undefined) {
  108253. accessor._data = Promise.resolve(new Float32Array(length));
  108254. }
  108255. else {
  108256. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108257. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  108258. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  108259. });
  108260. }
  108261. if (accessor.sparse) {
  108262. var sparse_1 = accessor.sparse;
  108263. accessor._data = accessor._data.then(function (data) {
  108264. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  108265. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  108266. return Promise.all([
  108267. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  108268. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  108269. ]).then(function (_a) {
  108270. var indicesData = _a[0], valuesData = _a[1];
  108271. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  108272. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  108273. var valuesIndex = 0;
  108274. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  108275. var dataIndex = indices[indicesIndex] * numComponents;
  108276. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  108277. data[dataIndex++] = values[valuesIndex++];
  108278. }
  108279. }
  108280. return data;
  108281. });
  108282. });
  108283. }
  108284. return accessor._data;
  108285. };
  108286. /** @hidden */
  108287. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  108288. var _this = this;
  108289. if (bufferView._babylonBuffer) {
  108290. return bufferView._babylonBuffer;
  108291. }
  108292. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  108293. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  108294. });
  108295. return bufferView._babylonBuffer;
  108296. };
  108297. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  108298. var _this = this;
  108299. if (accessor._babylonVertexBuffer) {
  108300. return accessor._babylonVertexBuffer;
  108301. }
  108302. if (accessor.sparse) {
  108303. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  108304. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  108305. });
  108306. }
  108307. else {
  108308. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108309. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  108310. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  108311. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  108312. });
  108313. }
  108314. return accessor._babylonVertexBuffer;
  108315. };
  108316. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  108317. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  108318. if (!babylonMaterial) {
  108319. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  108320. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108321. babylonMaterial.metallic = 1;
  108322. babylonMaterial.roughness = 1;
  108323. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108324. }
  108325. return babylonMaterial;
  108326. };
  108327. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  108328. var promises = new Array();
  108329. // Ensure metallic workflow
  108330. babylonMaterial.metallic = 1;
  108331. babylonMaterial.roughness = 1;
  108332. var properties = material.pbrMetallicRoughness;
  108333. if (properties) {
  108334. if (properties.baseColorFactor) {
  108335. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  108336. babylonMaterial.alpha = properties.baseColorFactor[3];
  108337. }
  108338. else {
  108339. babylonMaterial.albedoColor = BABYLON.Color3.White();
  108340. }
  108341. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  108342. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  108343. if (properties.baseColorTexture) {
  108344. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  108345. babylonMaterial.albedoTexture = texture;
  108346. }));
  108347. }
  108348. if (properties.metallicRoughnessTexture) {
  108349. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  108350. babylonMaterial.metallicTexture = texture;
  108351. }));
  108352. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  108353. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  108354. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  108355. }
  108356. }
  108357. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  108358. return Promise.all(promises).then(function () { });
  108359. };
  108360. /** @hidden */
  108361. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108362. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  108363. if (promise) {
  108364. return promise;
  108365. }
  108366. material._babylonData = material._babylonData || {};
  108367. var babylonData = material._babylonData[babylonDrawMode];
  108368. if (!babylonData) {
  108369. var promises = new Array();
  108370. var name_3 = material.name || "material_" + material._index;
  108371. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  108372. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  108373. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  108374. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108375. babylonData = {
  108376. material: babylonMaterial,
  108377. meshes: [],
  108378. loaded: Promise.all(promises).then(function () { })
  108379. };
  108380. material._babylonData[babylonDrawMode] = babylonData;
  108381. }
  108382. babylonData.meshes.push(babylonMesh);
  108383. assign(babylonData.material);
  108384. return babylonData.loaded;
  108385. };
  108386. /** @hidden */
  108387. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  108388. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  108389. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  108390. babylonMaterial.fillMode = drawMode;
  108391. babylonMaterial.enableSpecularAntiAliasing = true;
  108392. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  108393. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  108394. return babylonMaterial;
  108395. };
  108396. /** @hidden */
  108397. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  108398. var promises = new Array();
  108399. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  108400. if (material.doubleSided) {
  108401. babylonMaterial.backFaceCulling = false;
  108402. babylonMaterial.twoSidedLighting = true;
  108403. }
  108404. if (material.normalTexture) {
  108405. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  108406. babylonMaterial.bumpTexture = texture;
  108407. }));
  108408. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  108409. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  108410. if (material.normalTexture.scale != undefined) {
  108411. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  108412. }
  108413. }
  108414. if (material.occlusionTexture) {
  108415. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  108416. babylonMaterial.ambientTexture = texture;
  108417. }));
  108418. babylonMaterial.useAmbientInGrayScale = true;
  108419. if (material.occlusionTexture.strength != undefined) {
  108420. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  108421. }
  108422. }
  108423. if (material.emissiveTexture) {
  108424. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  108425. babylonMaterial.emissiveTexture = texture;
  108426. }));
  108427. }
  108428. return Promise.all(promises).then(function () { });
  108429. };
  108430. /** @hidden */
  108431. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  108432. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  108433. switch (alphaMode) {
  108434. case "OPAQUE" /* OPAQUE */: {
  108435. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108436. break;
  108437. }
  108438. case "MASK" /* MASK */: {
  108439. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  108440. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  108441. if (babylonMaterial.albedoTexture) {
  108442. babylonMaterial.albedoTexture.hasAlpha = true;
  108443. }
  108444. break;
  108445. }
  108446. case "BLEND" /* BLEND */: {
  108447. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  108448. if (babylonMaterial.albedoTexture) {
  108449. babylonMaterial.albedoTexture.hasAlpha = true;
  108450. babylonMaterial.useAlphaFromAlbedoTexture = true;
  108451. }
  108452. break;
  108453. }
  108454. default: {
  108455. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  108456. }
  108457. }
  108458. };
  108459. /** @hidden */
  108460. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  108461. var _this = this;
  108462. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  108463. if (promise) {
  108464. return promise;
  108465. }
  108466. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  108467. context = "#/textures/" + textureInfo.index;
  108468. var promises = new Array();
  108469. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  108470. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  108471. var deferred = new BABYLON.Deferred();
  108472. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  108473. if (!_this._disposed) {
  108474. deferred.resolve();
  108475. }
  108476. }, function (message, exception) {
  108477. if (!_this._disposed) {
  108478. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  108479. }
  108480. });
  108481. promises.push(deferred.promise);
  108482. babylonTexture.name = texture.name || "texture" + texture._index;
  108483. babylonTexture.wrapU = samplerData.wrapU;
  108484. babylonTexture.wrapV = samplerData.wrapV;
  108485. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  108486. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  108487. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  108488. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  108489. babylonTexture.updateURL(dataUrl, blob);
  108490. }));
  108491. assign(babylonTexture);
  108492. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  108493. return Promise.all(promises).then(function () { });
  108494. };
  108495. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  108496. if (!sampler._data) {
  108497. sampler._data = {
  108498. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  108499. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  108500. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  108501. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  108502. };
  108503. }
  108504. ;
  108505. return sampler._data;
  108506. };
  108507. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  108508. if (image._blob) {
  108509. return image._blob;
  108510. }
  108511. var promise;
  108512. if (image.uri) {
  108513. promise = this._loadUriAsync(context, image.uri);
  108514. }
  108515. else {
  108516. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  108517. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  108518. }
  108519. image._blob = promise.then(function (data) {
  108520. return new Blob([data], { type: image.mimeType });
  108521. });
  108522. return image._blob;
  108523. };
  108524. /** @hidden */
  108525. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  108526. var _this = this;
  108527. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  108528. if (promise) {
  108529. return promise;
  108530. }
  108531. if (!GLTFLoader._ValidateUri(uri)) {
  108532. throw new Error(context + ": Uri '" + uri + "' is invalid");
  108533. }
  108534. if (BABYLON.Tools.IsBase64(uri)) {
  108535. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  108536. }
  108537. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  108538. return new Promise(function (resolve, reject) {
  108539. if (!_this._disposed) {
  108540. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  108541. if (!_this._disposed) {
  108542. resolve(new Uint8Array(data));
  108543. }
  108544. }, function (event) {
  108545. if (!_this._disposed) {
  108546. try {
  108547. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  108548. request_1._lengthComputable = event.lengthComputable;
  108549. request_1._loaded = event.loaded;
  108550. request_1._total = event.total;
  108551. _this._onProgress();
  108552. }
  108553. }
  108554. catch (e) {
  108555. reject(e);
  108556. }
  108557. }
  108558. }, _this._babylonScene.database, true, function (request, exception) {
  108559. if (!_this._disposed) {
  108560. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  108561. }
  108562. });
  108563. _this._requests.push(request_1);
  108564. }
  108565. });
  108566. });
  108567. };
  108568. GLTFLoader.prototype._onProgress = function () {
  108569. if (!this._progressCallback) {
  108570. return;
  108571. }
  108572. var lengthComputable = true;
  108573. var loaded = 0;
  108574. var total = 0;
  108575. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108576. var request = _a[_i];
  108577. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  108578. return;
  108579. }
  108580. lengthComputable = lengthComputable && request._lengthComputable;
  108581. loaded += request._loaded;
  108582. total += request._total;
  108583. }
  108584. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  108585. };
  108586. /** @hidden */
  108587. GLTFLoader._GetProperty = function (context, array, index) {
  108588. if (!array || index == undefined || !array[index]) {
  108589. throw new Error(context + ": Failed to find index (" + index + ")");
  108590. }
  108591. return array[index];
  108592. };
  108593. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  108594. // Set defaults if undefined
  108595. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  108596. switch (mode) {
  108597. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108598. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108599. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108600. default:
  108601. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  108602. return BABYLON.Texture.WRAP_ADDRESSMODE;
  108603. }
  108604. };
  108605. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  108606. // Set defaults if undefined
  108607. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  108608. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  108609. if (magFilter === 9729 /* LINEAR */) {
  108610. switch (minFilter) {
  108611. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  108612. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  108613. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  108614. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  108615. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  108616. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108617. default:
  108618. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  108619. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108620. }
  108621. }
  108622. else {
  108623. if (magFilter !== 9728 /* NEAREST */) {
  108624. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  108625. }
  108626. switch (minFilter) {
  108627. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  108628. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  108629. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108630. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  108631. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  108632. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  108633. default:
  108634. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  108635. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108636. }
  108637. }
  108638. };
  108639. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  108640. var buffer = bufferView.buffer;
  108641. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  108642. try {
  108643. switch (componentType) {
  108644. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  108645. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  108646. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  108647. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  108648. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  108649. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  108650. default: throw new Error("Invalid component type " + componentType);
  108651. }
  108652. }
  108653. catch (e) {
  108654. throw new Error(context + ": " + e);
  108655. }
  108656. };
  108657. GLTFLoader._GetNumComponents = function (context, type) {
  108658. switch (type) {
  108659. case "SCALAR": return 1;
  108660. case "VEC2": return 2;
  108661. case "VEC3": return 3;
  108662. case "VEC4": return 4;
  108663. case "MAT2": return 4;
  108664. case "MAT3": return 9;
  108665. case "MAT4": return 16;
  108666. }
  108667. throw new Error(context + ": Invalid type (" + type + ")");
  108668. };
  108669. GLTFLoader._ValidateUri = function (uri) {
  108670. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  108671. };
  108672. GLTFLoader._GetDrawMode = function (context, mode) {
  108673. if (mode == undefined) {
  108674. mode = 4 /* TRIANGLES */;
  108675. }
  108676. switch (mode) {
  108677. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  108678. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  108679. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  108680. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  108681. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  108682. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  108683. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  108684. }
  108685. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  108686. };
  108687. GLTFLoader.prototype._compileMaterialsAsync = function () {
  108688. var promises = new Array();
  108689. if (this._gltf.materials) {
  108690. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  108691. var material = _a[_i];
  108692. if (material._babylonData) {
  108693. for (var babylonDrawMode in material._babylonData) {
  108694. var babylonData = material._babylonData[babylonDrawMode];
  108695. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  108696. var babylonMesh = _c[_b];
  108697. // Ensure nonUniformScaling is set if necessary.
  108698. babylonMesh.computeWorldMatrix(true);
  108699. var babylonMaterial = babylonData.material;
  108700. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  108701. if (this.useClipPlane) {
  108702. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  108703. }
  108704. }
  108705. }
  108706. }
  108707. }
  108708. }
  108709. return Promise.all(promises).then(function () { });
  108710. };
  108711. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  108712. var promises = new Array();
  108713. var lights = this._babylonScene.lights;
  108714. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  108715. var light = lights_1[_i];
  108716. var generator = light.getShadowGenerator();
  108717. if (generator) {
  108718. promises.push(generator.forceCompilationAsync());
  108719. }
  108720. }
  108721. return Promise.all(promises).then(function () { });
  108722. };
  108723. GLTFLoader.prototype._clear = function () {
  108724. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108725. var request = _a[_i];
  108726. request.abort();
  108727. }
  108728. this._requests.length = 0;
  108729. delete this._gltf;
  108730. delete this._babylonScene;
  108731. this._completePromises.length = 0;
  108732. this._onReadyObservable.clear();
  108733. for (var name_4 in this._extensions) {
  108734. this._extensions[name_4].dispose();
  108735. }
  108736. this._extensions = {};
  108737. delete this._rootBabylonMesh;
  108738. delete this._progressCallback;
  108739. this.onMeshLoadedObservable.clear();
  108740. this.onTextureLoadedObservable.clear();
  108741. this.onMaterialLoadedObservable.clear();
  108742. this.onCameraLoadedObservable.clear();
  108743. };
  108744. /** @hidden */
  108745. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  108746. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  108747. var name_5 = _a[_i];
  108748. var extension = this._extensions[name_5];
  108749. if (extension.enabled) {
  108750. var promise = actionAsync(extension);
  108751. if (promise) {
  108752. return promise;
  108753. }
  108754. }
  108755. }
  108756. return null;
  108757. };
  108758. GLTFLoader._ExtensionNames = new Array();
  108759. GLTFLoader._ExtensionFactories = {};
  108760. return GLTFLoader;
  108761. }());
  108762. GLTF2.GLTFLoader = GLTFLoader;
  108763. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  108764. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108765. })(BABYLON || (BABYLON = {}));
  108766. //# sourceMappingURL=babylon.glTFLoader.js.map
  108767. var BABYLON;
  108768. (function (BABYLON) {
  108769. var GLTF2;
  108770. (function (GLTF2) {
  108771. /**
  108772. * Abstract class that can be implemented to extend existing glTF loader behavior.
  108773. */
  108774. var GLTFLoaderExtension = /** @class */ (function () {
  108775. /**
  108776. * Creates new GLTFLoaderExtension
  108777. * @param loader defines the GLTFLoader to use
  108778. */
  108779. function GLTFLoaderExtension(loader) {
  108780. /**
  108781. * Gets or sets a boolean indicating if the extension is enabled
  108782. */
  108783. this.enabled = true;
  108784. this._loader = loader;
  108785. }
  108786. /**
  108787. * Release all resources
  108788. */
  108789. GLTFLoaderExtension.prototype.dispose = function () {
  108790. delete this._loader;
  108791. };
  108792. // #region Overridable Methods
  108793. /**
  108794. * Override this method to modify the default behavior for loading scenes.
  108795. * @hidden
  108796. */
  108797. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  108798. /**
  108799. * Override this method to modify the default behavior for loading nodes.
  108800. * @hidden
  108801. */
  108802. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  108803. /**
  108804. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  108805. * @hidden
  108806. */
  108807. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  108808. /**
  108809. * Override this method to modify the default behavior for loading materials.
  108810. * @hidden
  108811. */
  108812. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  108813. /**
  108814. * Override this method to modify the default behavior for loading textures.
  108815. * @hidden
  108816. */
  108817. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  108818. /**
  108819. * Override this method to modify the default behavior for loading uris.
  108820. * @hidden
  108821. */
  108822. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  108823. // #endregion
  108824. /**
  108825. * Helper method called by a loader extension to load an glTF extension.
  108826. * @hidden
  108827. */
  108828. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  108829. if (!property.extensions) {
  108830. return null;
  108831. }
  108832. var extensions = property.extensions;
  108833. var extension = extensions[this.name];
  108834. if (!extension) {
  108835. return null;
  108836. }
  108837. // Clear out the extension before executing the action to avoid infinite recursion.
  108838. delete extensions[this.name];
  108839. try {
  108840. return actionAsync(context + "/extensions/" + this.name, extension);
  108841. }
  108842. finally {
  108843. // Restore the extension after executing the action.
  108844. extensions[this.name] = extension;
  108845. }
  108846. };
  108847. /**
  108848. * Helper method called by the loader to allow extensions to override loading scenes.
  108849. * @hidden
  108850. */
  108851. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  108852. if (!property.extras) {
  108853. return null;
  108854. }
  108855. var extras = property.extras;
  108856. var value = extras[this.name];
  108857. if (value === undefined) {
  108858. return null;
  108859. }
  108860. // Clear out the extras value before executing the action to avoid infinite recursion.
  108861. delete extras[this.name];
  108862. try {
  108863. return actionAsync(context + "/extras/" + this.name, value);
  108864. }
  108865. finally {
  108866. // Restore the extras value after executing the action.
  108867. extras[this.name] = value;
  108868. }
  108869. };
  108870. /**
  108871. * Helper method called by the loader to allow extensions to override loading scenes.
  108872. * @hidden
  108873. */
  108874. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  108875. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  108876. };
  108877. /**
  108878. * Helper method called by the loader to allow extensions to override loading nodes.
  108879. * @hidden
  108880. */
  108881. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  108882. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  108883. };
  108884. /**
  108885. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  108886. * @hidden
  108887. */
  108888. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  108889. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  108890. };
  108891. /**
  108892. * Helper method called by the loader to allow extensions to override loading materials.
  108893. * @hidden
  108894. */
  108895. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108896. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  108897. };
  108898. /**
  108899. * Helper method called by the loader to allow extensions to override loading textures.
  108900. * @hidden
  108901. */
  108902. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  108903. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  108904. };
  108905. /**
  108906. * Helper method called by the loader to allow extensions to override loading uris.
  108907. * @hidden
  108908. */
  108909. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  108910. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  108911. };
  108912. return GLTFLoaderExtension;
  108913. }());
  108914. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  108915. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108916. })(BABYLON || (BABYLON = {}));
  108917. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108918. var BABYLON;
  108919. (function (BABYLON) {
  108920. var GLTF2;
  108921. (function (GLTF2) {
  108922. var Extensions;
  108923. (function (Extensions) {
  108924. var NAME = "MSFT_lod";
  108925. /**
  108926. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  108927. */
  108928. var MSFT_lod = /** @class */ (function (_super) {
  108929. __extends(MSFT_lod, _super);
  108930. function MSFT_lod(loader) {
  108931. var _this = _super.call(this, loader) || this;
  108932. _this.name = NAME;
  108933. /**
  108934. * Maximum number of LODs to load, starting from the lowest LOD.
  108935. */
  108936. _this.maxLODsToLoad = Number.MAX_VALUE;
  108937. /**
  108938. * Observable raised when all node LODs of one level are loaded.
  108939. * The event data is the index of the loaded LOD starting from zero.
  108940. * Dispose the loader to cancel the loading of the next level of LODs.
  108941. */
  108942. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  108943. /**
  108944. * Observable raised when all material LODs of one level are loaded.
  108945. * The event data is the index of the loaded LOD starting from zero.
  108946. * Dispose the loader to cancel the loading of the next level of LODs.
  108947. */
  108948. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  108949. _this._loadingNodeLOD = null;
  108950. _this._loadNodeSignals = {};
  108951. _this._loadNodePromises = new Array();
  108952. _this._loadingMaterialLOD = null;
  108953. _this._loadMaterialSignals = {};
  108954. _this._loadMaterialPromises = new Array();
  108955. _this._loader._onReadyObservable.addOnce(function () {
  108956. var _loop_1 = function (indexLOD) {
  108957. Promise.all(_this._loadNodePromises[indexLOD]).then(function () {
  108958. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  108959. });
  108960. };
  108961. for (var indexLOD = 0; indexLOD < _this._loadNodePromises.length; indexLOD++) {
  108962. _loop_1(indexLOD);
  108963. }
  108964. var _loop_2 = function (indexLOD) {
  108965. Promise.all(_this._loadMaterialPromises[indexLOD]).then(function () {
  108966. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  108967. });
  108968. };
  108969. for (var indexLOD = 0; indexLOD < _this._loadMaterialPromises.length; indexLOD++) {
  108970. _loop_2(indexLOD);
  108971. }
  108972. });
  108973. return _this;
  108974. }
  108975. MSFT_lod.prototype.dispose = function () {
  108976. _super.prototype.dispose.call(this);
  108977. this._loadingNodeLOD = null;
  108978. this._loadNodeSignals = {};
  108979. this._loadingMaterialLOD = null;
  108980. this._loadMaterialSignals = {};
  108981. this.onMaterialLODsLoadedObservable.clear();
  108982. this.onNodeLODsLoadedObservable.clear();
  108983. };
  108984. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  108985. var _this = this;
  108986. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  108987. var firstPromise;
  108988. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  108989. var _loop_3 = function (indexLOD) {
  108990. var nodeLOD = nodeLODs[indexLOD];
  108991. if (indexLOD !== 0) {
  108992. _this._loadingNodeLOD = nodeLOD;
  108993. if (!_this._loadNodeSignals[nodeLOD._index]) {
  108994. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  108995. }
  108996. }
  108997. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  108998. if (indexLOD !== 0) {
  108999. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109000. if (previousNodeLOD._babylonMesh) {
  109001. previousNodeLOD._babylonMesh.dispose(false, true);
  109002. delete previousNodeLOD._babylonMesh;
  109003. }
  109004. }
  109005. if (indexLOD !== nodeLODs.length - 1) {
  109006. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  109007. if (_this._loadNodeSignals[nodeIndex]) {
  109008. _this._loadNodeSignals[nodeIndex].resolve();
  109009. delete _this._loadNodeSignals[nodeIndex];
  109010. }
  109011. }
  109012. });
  109013. if (indexLOD === 0) {
  109014. firstPromise = promise;
  109015. }
  109016. else {
  109017. _this._loader._completePromises.push(promise);
  109018. _this._loadingNodeLOD = null;
  109019. }
  109020. _this._loadNodePromises[indexLOD] = _this._loadNodePromises[indexLOD] || [];
  109021. _this._loadNodePromises[indexLOD].push(promise);
  109022. };
  109023. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109024. _loop_3(indexLOD);
  109025. }
  109026. return firstPromise;
  109027. });
  109028. };
  109029. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109030. var _this = this;
  109031. // Don't load material LODs if already loading a node LOD.
  109032. if (this._loadingNodeLOD) {
  109033. return null;
  109034. }
  109035. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  109036. var firstPromise;
  109037. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  109038. var _loop_4 = function (indexLOD) {
  109039. var materialLOD = materialLODs[indexLOD];
  109040. if (indexLOD !== 0) {
  109041. _this._loadingMaterialLOD = materialLOD;
  109042. if (!_this._loadMaterialSignals[materialLOD._index]) {
  109043. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  109044. }
  109045. }
  109046. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  109047. if (indexLOD !== 0) {
  109048. var babylonDataLOD = materialLOD._babylonData;
  109049. assign(babylonDataLOD[babylonDrawMode].material);
  109050. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  109051. if (previousBabylonDataLOD[babylonDrawMode]) {
  109052. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  109053. delete previousBabylonDataLOD[babylonDrawMode];
  109054. }
  109055. }
  109056. if (indexLOD !== materialLODs.length - 1) {
  109057. var materialIndex = materialLODs[indexLOD + 1]._index;
  109058. if (_this._loadMaterialSignals[materialIndex]) {
  109059. _this._loadMaterialSignals[materialIndex].resolve();
  109060. delete _this._loadMaterialSignals[materialIndex];
  109061. }
  109062. }
  109063. });
  109064. if (indexLOD === 0) {
  109065. firstPromise = promise;
  109066. }
  109067. else {
  109068. _this._loader._completePromises.push(promise);
  109069. _this._loadingMaterialLOD = null;
  109070. }
  109071. _this._loadMaterialPromises[indexLOD] = _this._loadMaterialPromises[indexLOD] || [];
  109072. _this._loadMaterialPromises[indexLOD].push(promise);
  109073. };
  109074. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109075. _loop_4(indexLOD);
  109076. }
  109077. return firstPromise;
  109078. });
  109079. };
  109080. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  109081. var _this = this;
  109082. // Defer the loading of uris if loading a material or node LOD.
  109083. if (this._loadingMaterialLOD) {
  109084. var index = this._loadingMaterialLOD._index;
  109085. return this._loadMaterialSignals[index].promise.then(function () {
  109086. return _this._loader._loadUriAsync(context, uri);
  109087. });
  109088. }
  109089. else if (this._loadingNodeLOD) {
  109090. var index = this._loadingNodeLOD._index;
  109091. return this._loadNodeSignals[index].promise.then(function () {
  109092. return _this._loader._loadUriAsync(context, uri);
  109093. });
  109094. }
  109095. return null;
  109096. };
  109097. /**
  109098. * Gets an array of LOD properties from lowest to highest.
  109099. */
  109100. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  109101. if (this.maxLODsToLoad <= 0) {
  109102. throw new Error("maxLODsToLoad must be greater than zero");
  109103. }
  109104. var properties = new Array();
  109105. for (var i = ids.length - 1; i >= 0; i--) {
  109106. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  109107. if (properties.length === this.maxLODsToLoad) {
  109108. return properties;
  109109. }
  109110. }
  109111. properties.push(property);
  109112. return properties;
  109113. };
  109114. return MSFT_lod;
  109115. }(GLTF2.GLTFLoaderExtension));
  109116. Extensions.MSFT_lod = MSFT_lod;
  109117. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  109118. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109119. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109120. })(BABYLON || (BABYLON = {}));
  109121. //# sourceMappingURL=MSFT_lod.js.map
  109122. var BABYLON;
  109123. (function (BABYLON) {
  109124. var GLTF2;
  109125. (function (GLTF2) {
  109126. var Extensions;
  109127. (function (Extensions) {
  109128. var NAME = "MSFT_minecraftMesh";
  109129. /** @hidden */
  109130. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  109131. __extends(MSFT_minecraftMesh, _super);
  109132. function MSFT_minecraftMesh() {
  109133. var _this = _super !== null && _super.apply(this, arguments) || this;
  109134. _this.name = NAME;
  109135. return _this;
  109136. }
  109137. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109138. var _this = this;
  109139. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  109140. if (value) {
  109141. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109142. if (babylonMaterial.needAlphaBlending()) {
  109143. babylonMaterial.forceDepthWrite = true;
  109144. babylonMaterial.separateCullingPass = true;
  109145. }
  109146. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  109147. babylonMaterial.twoSidedLighting = true;
  109148. assign(babylonMaterial);
  109149. });
  109150. }
  109151. return null;
  109152. });
  109153. };
  109154. return MSFT_minecraftMesh;
  109155. }(GLTF2.GLTFLoaderExtension));
  109156. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  109157. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  109158. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109159. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109160. })(BABYLON || (BABYLON = {}));
  109161. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  109162. var BABYLON;
  109163. (function (BABYLON) {
  109164. var GLTF2;
  109165. (function (GLTF2) {
  109166. var Extensions;
  109167. (function (Extensions) {
  109168. var NAME = "MSFT_sRGBFactors";
  109169. /** @hidden */
  109170. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  109171. __extends(MSFT_sRGBFactors, _super);
  109172. function MSFT_sRGBFactors() {
  109173. var _this = _super !== null && _super.apply(this, arguments) || this;
  109174. _this.name = NAME;
  109175. return _this;
  109176. }
  109177. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109178. var _this = this;
  109179. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  109180. if (value) {
  109181. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109182. if (!babylonMaterial.albedoTexture) {
  109183. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  109184. }
  109185. if (!babylonMaterial.reflectivityTexture) {
  109186. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  109187. }
  109188. assign(babylonMaterial);
  109189. });
  109190. }
  109191. return null;
  109192. });
  109193. };
  109194. return MSFT_sRGBFactors;
  109195. }(GLTF2.GLTFLoaderExtension));
  109196. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  109197. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  109198. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109199. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109200. })(BABYLON || (BABYLON = {}));
  109201. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  109202. var BABYLON;
  109203. (function (BABYLON) {
  109204. var GLTF2;
  109205. (function (GLTF2) {
  109206. var Extensions;
  109207. (function (Extensions) {
  109208. var NAME = "KHR_draco_mesh_compression";
  109209. /**
  109210. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  109211. */
  109212. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  109213. __extends(KHR_draco_mesh_compression, _super);
  109214. function KHR_draco_mesh_compression(loader) {
  109215. var _this = _super.call(this, loader) || this;
  109216. _this.name = NAME;
  109217. _this._dracoCompression = null;
  109218. // Disable extension if decoder is not available.
  109219. if (!BABYLON.DracoCompression.DecoderAvailable) {
  109220. _this.enabled = false;
  109221. }
  109222. return _this;
  109223. }
  109224. KHR_draco_mesh_compression.prototype.dispose = function () {
  109225. if (this._dracoCompression) {
  109226. this._dracoCompression.dispose();
  109227. }
  109228. _super.prototype.dispose.call(this);
  109229. };
  109230. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109231. var _this = this;
  109232. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  109233. if (primitive.mode != undefined) {
  109234. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  109235. primitive.mode !== 4 /* TRIANGLES */) {
  109236. throw new Error(context + ": Unsupported mode " + primitive.mode);
  109237. }
  109238. // TODO: handle triangle strips
  109239. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  109240. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  109241. }
  109242. }
  109243. var attributes = {};
  109244. var loadAttribute = function (name, kind) {
  109245. var uniqueId = extension.attributes[name];
  109246. if (uniqueId == undefined) {
  109247. return;
  109248. }
  109249. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109250. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109251. babylonMesh._delayInfo.push(kind);
  109252. }
  109253. attributes[kind] = uniqueId;
  109254. };
  109255. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109256. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109257. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109258. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109259. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109260. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109261. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109262. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109263. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  109264. if (!bufferView._dracoBabylonGeometry) {
  109265. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109266. if (!_this._dracoCompression) {
  109267. _this._dracoCompression = new BABYLON.DracoCompression();
  109268. }
  109269. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  109270. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  109271. babylonVertexData.applyToGeometry(babylonGeometry);
  109272. return babylonGeometry;
  109273. }).catch(function (error) {
  109274. throw new Error(context + ": " + error.message);
  109275. });
  109276. });
  109277. }
  109278. return bufferView._dracoBabylonGeometry;
  109279. });
  109280. };
  109281. return KHR_draco_mesh_compression;
  109282. }(GLTF2.GLTFLoaderExtension));
  109283. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  109284. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  109285. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109286. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109287. })(BABYLON || (BABYLON = {}));
  109288. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  109289. var BABYLON;
  109290. (function (BABYLON) {
  109291. var GLTF2;
  109292. (function (GLTF2) {
  109293. var Extensions;
  109294. (function (Extensions) {
  109295. var NAME = "KHR_materials_pbrSpecularGlossiness";
  109296. /**
  109297. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  109298. */
  109299. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  109300. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  109301. function KHR_materials_pbrSpecularGlossiness() {
  109302. var _this = _super !== null && _super.apply(this, arguments) || this;
  109303. _this.name = NAME;
  109304. return _this;
  109305. }
  109306. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109307. var _this = this;
  109308. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  109309. material._babylonData = material._babylonData || {};
  109310. var babylonData = material._babylonData[babylonDrawMode];
  109311. if (!babylonData) {
  109312. var promises = new Array();
  109313. var name_1 = material.name || "materialSG_" + material._index;
  109314. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  109315. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  109316. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  109317. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109318. babylonData = {
  109319. material: babylonMaterial,
  109320. meshes: [],
  109321. loaded: Promise.all(promises).then(function () { })
  109322. };
  109323. material._babylonData[babylonDrawMode] = babylonData;
  109324. }
  109325. babylonData.meshes.push(babylonMesh);
  109326. assign(babylonData.material);
  109327. return babylonData.loaded;
  109328. });
  109329. };
  109330. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  109331. var promises = new Array();
  109332. if (properties.diffuseFactor) {
  109333. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  109334. babylonMaterial.alpha = properties.diffuseFactor[3];
  109335. }
  109336. else {
  109337. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109338. }
  109339. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  109340. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  109341. if (properties.diffuseTexture) {
  109342. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  109343. babylonMaterial.albedoTexture = texture;
  109344. }));
  109345. }
  109346. if (properties.specularGlossinessTexture) {
  109347. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  109348. babylonMaterial.reflectivityTexture = texture;
  109349. }));
  109350. babylonMaterial.reflectivityTexture.hasAlpha = true;
  109351. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  109352. }
  109353. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  109354. return Promise.all(promises).then(function () { });
  109355. };
  109356. return KHR_materials_pbrSpecularGlossiness;
  109357. }(GLTF2.GLTFLoaderExtension));
  109358. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  109359. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  109360. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109361. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109362. })(BABYLON || (BABYLON = {}));
  109363. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  109364. var BABYLON;
  109365. (function (BABYLON) {
  109366. var GLTF2;
  109367. (function (GLTF2) {
  109368. var Extensions;
  109369. (function (Extensions) {
  109370. var NAME = "KHR_materials_unlit";
  109371. /**
  109372. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  109373. */
  109374. var KHR_materials_unlit = /** @class */ (function (_super) {
  109375. __extends(KHR_materials_unlit, _super);
  109376. function KHR_materials_unlit() {
  109377. var _this = _super !== null && _super.apply(this, arguments) || this;
  109378. _this.name = NAME;
  109379. return _this;
  109380. }
  109381. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  109382. var _this = this;
  109383. return this._loadExtensionAsync(context, material, function () {
  109384. material._babylonData = material._babylonData || {};
  109385. var babylonData = material._babylonData[babylonDrawMode];
  109386. if (!babylonData) {
  109387. var name_1 = material.name || "materialUnlit_" + material._index;
  109388. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  109389. babylonMaterial.unlit = true;
  109390. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  109391. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109392. babylonData = {
  109393. material: babylonMaterial,
  109394. meshes: [],
  109395. loaded: promise
  109396. };
  109397. material._babylonData[babylonDrawMode] = babylonData;
  109398. }
  109399. babylonData.meshes.push(babylonMesh);
  109400. assign(babylonData.material);
  109401. return babylonData.loaded;
  109402. });
  109403. };
  109404. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  109405. var promises = new Array();
  109406. // Ensure metallic workflow
  109407. babylonMaterial.metallic = 1;
  109408. babylonMaterial.roughness = 1;
  109409. var properties = material.pbrMetallicRoughness;
  109410. if (properties) {
  109411. if (properties.baseColorFactor) {
  109412. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109413. babylonMaterial.alpha = properties.baseColorFactor[3];
  109414. }
  109415. else {
  109416. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109417. }
  109418. if (properties.baseColorTexture) {
  109419. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109420. babylonMaterial.albedoTexture = texture;
  109421. }));
  109422. }
  109423. }
  109424. if (material.doubleSided) {
  109425. babylonMaterial.backFaceCulling = false;
  109426. babylonMaterial.twoSidedLighting = true;
  109427. }
  109428. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  109429. return Promise.all(promises).then(function () { });
  109430. };
  109431. return KHR_materials_unlit;
  109432. }(GLTF2.GLTFLoaderExtension));
  109433. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  109434. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  109435. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109436. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109437. })(BABYLON || (BABYLON = {}));
  109438. //# sourceMappingURL=KHR_materials_unlit.js.map
  109439. var BABYLON;
  109440. (function (BABYLON) {
  109441. var GLTF2;
  109442. (function (GLTF2) {
  109443. var Extensions;
  109444. (function (Extensions) {
  109445. var NAME = "KHR_lights";
  109446. var LightType;
  109447. (function (LightType) {
  109448. LightType["AMBIENT"] = "ambient";
  109449. LightType["DIRECTIONAL"] = "directional";
  109450. LightType["POINT"] = "point";
  109451. LightType["SPOT"] = "spot";
  109452. })(LightType || (LightType = {}));
  109453. /**
  109454. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  109455. */
  109456. var KHR_lights = /** @class */ (function (_super) {
  109457. __extends(KHR_lights, _super);
  109458. function KHR_lights() {
  109459. var _this = _super !== null && _super.apply(this, arguments) || this;
  109460. _this.name = NAME;
  109461. return _this;
  109462. }
  109463. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  109464. var _this = this;
  109465. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  109466. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  109467. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  109468. if (light.type !== LightType.AMBIENT) {
  109469. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  109470. }
  109471. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  109472. return promise;
  109473. });
  109474. };
  109475. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  109476. var _this = this;
  109477. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  109478. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  109479. var babylonLight;
  109480. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  109481. var name = node._babylonMesh.name;
  109482. switch (light.type) {
  109483. case LightType.AMBIENT: {
  109484. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  109485. }
  109486. case LightType.DIRECTIONAL: {
  109487. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  109488. break;
  109489. }
  109490. case LightType.POINT: {
  109491. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  109492. break;
  109493. }
  109494. case LightType.SPOT: {
  109495. var spotLight = light;
  109496. // TODO: support inner and outer cone angles
  109497. //const innerConeAngle = spotLight.innerConeAngle || 0;
  109498. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  109499. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  109500. break;
  109501. }
  109502. default: {
  109503. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  109504. }
  109505. }
  109506. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  109507. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  109508. babylonLight.parent = node._babylonMesh;
  109509. return promise;
  109510. });
  109511. };
  109512. Object.defineProperty(KHR_lights.prototype, "_lights", {
  109513. get: function () {
  109514. var extensions = this._loader._gltf.extensions;
  109515. if (!extensions || !extensions[this.name]) {
  109516. throw new Error("#/extensions: '" + this.name + "' not found");
  109517. }
  109518. var extension = extensions[this.name];
  109519. return extension.lights;
  109520. },
  109521. enumerable: true,
  109522. configurable: true
  109523. });
  109524. return KHR_lights;
  109525. }(GLTF2.GLTFLoaderExtension));
  109526. Extensions.KHR_lights = KHR_lights;
  109527. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  109528. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109529. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109530. })(BABYLON || (BABYLON = {}));
  109531. var BABYLON;
  109532. (function (BABYLON) {
  109533. var GLTF2;
  109534. (function (GLTF2) {
  109535. var Extensions;
  109536. (function (Extensions) {
  109537. var NAME = "KHR_texture_transform";
  109538. /**
  109539. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  109540. */
  109541. var KHR_texture_transform = /** @class */ (function (_super) {
  109542. __extends(KHR_texture_transform, _super);
  109543. function KHR_texture_transform() {
  109544. var _this = _super !== null && _super.apply(this, arguments) || this;
  109545. _this.name = NAME;
  109546. return _this;
  109547. }
  109548. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109549. var _this = this;
  109550. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  109551. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  109552. if (extension.offset) {
  109553. babylonTexture.uOffset = extension.offset[0];
  109554. babylonTexture.vOffset = extension.offset[1];
  109555. }
  109556. // Always rotate around the origin.
  109557. babylonTexture.uRotationCenter = 0;
  109558. babylonTexture.vRotationCenter = 0;
  109559. if (extension.rotation) {
  109560. babylonTexture.wAng = -extension.rotation;
  109561. }
  109562. if (extension.scale) {
  109563. babylonTexture.uScale = extension.scale[0];
  109564. babylonTexture.vScale = extension.scale[1];
  109565. }
  109566. if (extension.texCoord != undefined) {
  109567. babylonTexture.coordinatesIndex = extension.texCoord;
  109568. }
  109569. assign(babylonTexture);
  109570. });
  109571. });
  109572. };
  109573. return KHR_texture_transform;
  109574. }(GLTF2.GLTFLoaderExtension));
  109575. Extensions.KHR_texture_transform = KHR_texture_transform;
  109576. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  109577. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109578. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109579. })(BABYLON || (BABYLON = {}));
  109580. return BABYLON;
  109581. });
  109582. /***/ }),
  109583. /* 15 */
  109584. /***/ (function(module, exports, __webpack_require__) {
  109585. module.exports = __webpack_require__(16);
  109586. /***/ }),
  109587. /* 16 */
  109588. /***/ (function(module, exports, __webpack_require__) {
  109589. "use strict";
  109590. function __export(m) {
  109591. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  109592. }
  109593. Object.defineProperty(exports, "__esModule", { value: true });
  109594. var mappers_1 = __webpack_require__(3);
  109595. exports.mapperManager = mappers_1.mapperManager;
  109596. var globals_1 = __webpack_require__(4);
  109597. exports.viewerGlobals = globals_1.viewerGlobals;
  109598. var viewerManager_1 = __webpack_require__(7);
  109599. exports.viewerManager = viewerManager_1.viewerManager;
  109600. var defaultViewer_1 = __webpack_require__(8);
  109601. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  109602. var viewer_1 = __webpack_require__(9);
  109603. exports.AbstractViewer = viewer_1.AbstractViewer;
  109604. var telemetryManager_1 = __webpack_require__(6);
  109605. exports.telemetryManager = telemetryManager_1.telemetryManager;
  109606. var modelLoader_1 = __webpack_require__(13);
  109607. exports.ModelLoader = modelLoader_1.ModelLoader;
  109608. var viewerModel_1 = __webpack_require__(5);
  109609. exports.ViewerModel = viewerModel_1.ViewerModel;
  109610. exports.ModelState = viewerModel_1.ModelState;
  109611. /**
  109612. * BabylonJS Viewer
  109613. *
  109614. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  109615. */
  109616. var BABYLON = __webpack_require__(0);
  109617. exports.BABYLON = BABYLON;
  109618. // load needed modules.
  109619. __webpack_require__(14);
  109620. __webpack_require__(64);
  109621. var initializer_1 = __webpack_require__(65);
  109622. exports.InitTags = initializer_1.InitTags;
  109623. // promise polyfill, if needed!
  109624. BABYLON.PromisePolyfill.Apply();
  109625. initializer_1.initListeners();
  109626. //deprectaed, here for backwards compatibility
  109627. var disableInit = globals_1.viewerGlobals.disableInit;
  109628. exports.disableInit = disableInit;
  109629. /**
  109630. * Dispose all viewers currently registered
  109631. */
  109632. function disposeAll() {
  109633. viewerManager_1.viewerManager.dispose();
  109634. mappers_1.mapperManager.dispose();
  109635. telemetryManager_1.telemetryManager.dispose();
  109636. }
  109637. exports.disposeAll = disposeAll;
  109638. var Version = globals_1.viewerGlobals.version;
  109639. exports.Version = Version;
  109640. console.log("Babylon.js viewer (v" + Version + ")");
  109641. // export publicliy all configuration interf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QUVHO0FBQ0g7SUFDSSw2QkFBYSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ3hCLHVCQUFhLENBQUMsT0FBTyxFQUFFLENBQUM7SUFDeEIsbUNBQWdCLENBQUMsT0FBTyxFQUFFLENBQUM7QUFDL0IsQ0FBQztBQU8rSSxnQ0FBVTtBQUwxSixJQUFNLE9BQU8sR0FBRyx1QkFBYSxDQUFDLE9BQU8sQ0FBQztBQUtwQiwwQkFBTztBQUh6QixPQUFPLENBQUMsR0FBRyxDQUFDLHNCQUFzQixHQUFHLE9BQU8sR0FBRyxHQUFHLENBQUMsQ0FBQztBQUlwRCxnREFBZ0Q7QUFDaEQscUNBQWdDIn0=
  109644. /***/ }),
  109645. /* 17 */
  109646. /***/ (function(module, exports) {
  109647. var g;
  109648. // This works in non-strict mode
  109649. g = (function() {
  109650. return this;
  109651. })();
  109652. try {
  109653. // This works if eval is allowed (see CSP)
  109654. g = g || Function("return this")() || (1,eval)("this");
  109655. } catch(e) {
  109656. // This works if the window reference is available
  109657. if(typeof window === "object")
  109658. g = window;
  109659. }
  109660. // g can still be undefined, but nothing to do about it...
  109661. // We return undefined, instead of nothing here, so it's
  109662. // easier to handle this case. if(!global) { ...}
  109663. module.exports = g;
  109664. /***/ }),
  109665. /* 18 */
  109666. /***/ (function(module, exports) {
  109667. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109668. module.exports = CANNON;
  109669. /***/ }),
  109670. /* 19 */
  109671. /***/ (function(module, exports) {
  109672. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109673. module.exports = OIMO;
  109674. /***/ }),
  109675. /* 20 */
  109676. /***/ (function(module, exports) {
  109677. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  109678. module.exports = earcut;
  109679. /***/ }),
  109680. /* 21 */
  109681. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  109682. "use strict";
  109683. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  109684. var isMergeableObject = function isMergeableObject(value) {
  109685. return isNonNullObject(value)
  109686. && !isSpecial(value)
  109687. };
  109688. function isNonNullObject(value) {
  109689. return !!value && typeof value === 'object'
  109690. }
  109691. function isSpecial(value) {
  109692. var stringValue = Object.prototype.toString.call(value);
  109693. return stringValue === '[object RegExp]'
  109694. || stringValue === '[object Date]'
  109695. || isReactElement(value)
  109696. }
  109697. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  109698. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  109699. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  109700. function isReactElement(value) {
  109701. return value.$$typeof === REACT_ELEMENT_TYPE
  109702. }
  109703. function emptyTarget(val) {
  109704. return Array.isArray(val) ? [] : {}
  109705. }
  109706. function cloneUnlessOtherwiseSpecified(value, options) {
  109707. return (options.clone !== false && options.isMergeableObject(value))
  109708. ? deepmerge(emptyTarget(value), value, options)
  109709. : value
  109710. }
  109711. function defaultArrayMerge(target, source, options) {
  109712. return target.concat(source).map(function(element) {
  109713. return cloneUnlessOtherwiseSpecified(element, options)
  109714. })
  109715. }
  109716. function mergeObject(target, source, options) {
  109717. var destination = {};
  109718. if (options.isMergeableObject(target)) {
  109719. Object.keys(target).forEach(function(key) {
  109720. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  109721. });
  109722. }
  109723. Object.keys(source).forEach(function(key) {
  109724. if (!options.isMergeableObject(source[key]) || !target[key]) {
  109725. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  109726. } else {
  109727. destination[key] = deepmerge(target[key], source[key], options);
  109728. }
  109729. });
  109730. return destination
  109731. }
  109732. function deepmerge(target, source, options) {
  109733. options = options || {};
  109734. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  109735. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  109736. var sourceIsArray = Array.isArray(source);
  109737. var targetIsArray = Array.isArray(target);
  109738. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  109739. if (!sourceAndTargetTypesMatch) {
  109740. return cloneUnlessOtherwiseSpecified(source, options)
  109741. } else if (sourceIsArray) {
  109742. return options.arrayMerge(target, source, options)
  109743. } else {
  109744. return mergeObject(target, source, options)
  109745. }
  109746. }
  109747. deepmerge.all = function deepmergeAll(array, options) {
  109748. if (!Array.isArray(array)) {
  109749. throw new Error('first argument should be an array')
  109750. }
  109751. return array.reduce(function(prev, next) {
  109752. return deepmerge(prev, next, options)
  109753. }, {})
  109754. };
  109755. var deepmerge_1 = deepmerge;
  109756. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  109757. /***/ }),
  109758. /* 22 */
  109759. /***/ (function(module, exports, __webpack_require__) {
  109760. "use strict";
  109761. Object.defineProperty(exports, "__esModule", { value: true });
  109762. var babylonjs_1 = __webpack_require__(0);
  109763. var configuration_1 = __webpack_require__(10);
  109764. var viewerModel_1 = __webpack_require__(5);
  109765. var helper_1 = __webpack_require__(1);
  109766. var viewerLabs_1 = __webpack_require__(24);
  109767. var _1 = __webpack_require__(26);
  109768. var SceneManager = /** @class */ (function () {
  109769. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  109770. var _this = this;
  109771. this._engine = _engine;
  109772. this._configurationContainer = _configurationContainer;
  109773. this._observablesManager = _observablesManager;
  109774. this._animationBlendingEnabled = true;
  109775. this._white = babylonjs_1.Color3.White();
  109776. this._forceShadowUpdate = false;
  109777. this._processShadows = true;
  109778. this._groundEnabled = true;
  109779. this._groundMirrorEnabled = true;
  109780. this._defaultRenderingPipelineEnabled = false;
  109781. this._globalConfiguration = {};
  109782. this._defaultRenderingPipelineShouldBuild = true;
  109783. // default from rendering pipeline
  109784. this._bloomEnabled = false;
  109785. // default from rendering pipeline
  109786. this._fxaaEnabled = false;
  109787. this._focusOnModel = function (model) {
  109788. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  109789. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  109790. var halfSizeVec = sizeVec.scale(0.5);
  109791. var center = boundingInfo.min.add(halfSizeVec);
  109792. _this.camera.setTarget(center);
  109793. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  109794. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  109795. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  109796. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  109797. // casting ais safe, due to the constraints tested before
  109798. (<ShadowLight>light).setDirectionToTarget(center);
  109799. });*/
  109800. };
  109801. this._cameraBehaviorMapping = {};
  109802. this.models = [];
  109803. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  109804. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  109805. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  109806. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  109807. this.onSceneInitObservable = new babylonjs_1.Observable();
  109808. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  109809. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  109810. //this._viewer.onEngineInitObservable.add(() => {
  109811. this._handleHardwareLimitations();
  109812. //});
  109813. this.onSceneInitObservable.add(function (scene) {
  109814. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  109815. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  109816. var updateShadows = function () {
  109817. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  109818. var light = _a[_i];
  109819. var generator = light.getShadowGenerator();
  109820. if (generator) {
  109821. // Processing shadows if animates
  109822. var shadowMap = generator.getShadowMap();
  109823. if (shadowMap) {
  109824. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  109825. }
  109826. }
  109827. }
  109828. };
  109829. scene.registerBeforeRender(function () {
  109830. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  109831. // make sure all models are loaded
  109832. updateShadows();
  109833. _this._forceShadowUpdate = false;
  109834. }
  109835. else if (!(_this.models.every(function (model) {
  109836. if (!model.shadowsRenderedAfterLoad) {
  109837. model.shadowsRenderedAfterLoad = true;
  109838. return false;
  109839. }
  109840. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  109841. }))) {
  109842. updateShadows();
  109843. }
  109844. });
  109845. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  109846. });
  109847. if (this._observablesManager) {
  109848. this._observablesManager.onModelLoadedObservable.add(function (model) {
  109849. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  109850. var light = _a[_i];
  109851. var generator = light.getShadowGenerator();
  109852. if (generator) {
  109853. // Processing shadows if animates
  109854. var shadowMap = generator.getShadowMap();
  109855. if (shadowMap) {
  109856. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  109857. }
  109858. }
  109859. }
  109860. _this._focusOnModel(model);
  109861. });
  109862. this._observablesManager.onModelAddedObservable.add(function (model) {
  109863. _this.models.push(model);
  109864. });
  109865. this._observablesManager.onModelRemovedObservable.add(function (model) {
  109866. _this.models.splice(_this.models.indexOf(model), 1);
  109867. });
  109868. }
  109869. }
  109870. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  109871. get: function () {
  109872. return this._defaultRenderingPipeline;
  109873. },
  109874. enumerable: true,
  109875. configurable: true
  109876. });
  109877. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  109878. /**
  109879. * Returns a boolean representing HDR support
  109880. */
  109881. get: function () {
  109882. return this._hdrSupport;
  109883. },
  109884. enumerable: true,
  109885. configurable: true
  109886. });
  109887. Object.defineProperty(SceneManager.prototype, "mainColor", {
  109888. /**
  109889. * Return the main color defined in the configuration.
  109890. */
  109891. get: function () {
  109892. return this._configurationContainer.mainColor;
  109893. },
  109894. enumerable: true,
  109895. configurable: true
  109896. });
  109897. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  109898. get: function () {
  109899. return this._configurationContainer.reflectionColor;
  109900. },
  109901. enumerable: true,
  109902. configurable: true
  109903. });
  109904. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  109905. get: function () {
  109906. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  109907. },
  109908. set: function (value) {
  109909. this.scene.animationPropertiesOverride.enableBlending = value;
  109910. },
  109911. enumerable: true,
  109912. configurable: true
  109913. });
  109914. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  109915. get: function () {
  109916. return this._observablesManager;
  109917. },
  109918. enumerable: true,
  109919. configurable: true
  109920. });
  109921. Object.defineProperty(SceneManager.prototype, "processShadows", {
  109922. /**
  109923. * The flag defining whether shadows are rendered constantly or once.
  109924. */
  109925. get: function () {
  109926. return this._processShadows;
  109927. },
  109928. /**
  109929. * Should shadows be rendered every frame, or only once and stop.
  109930. * This can be used to optimize a scene.
  109931. *
  109932. * Not that the shadows will NOT disapear but will remain in place.
  109933. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  109934. */
  109935. set: function (process) {
  109936. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  109937. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  109938. var light = _a[_i];
  109939. var generator = light.getShadowGenerator();
  109940. if (generator) {
  109941. var shadowMap = generator.getShadowMap();
  109942. if (shadowMap) {
  109943. shadowMap.refreshRate = refreshType;
  109944. }
  109945. }
  109946. }
  109947. this._processShadows = process;
  109948. },
  109949. enumerable: true,
  109950. configurable: true
  109951. });
  109952. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  109953. get: function () {
  109954. return this._groundEnabled;
  109955. },
  109956. set: function (newValue) {
  109957. if (newValue === this._groundEnabled)
  109958. return;
  109959. this._groundEnabled = newValue;
  109960. if (this.environmentHelper && this.environmentHelper.ground) {
  109961. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  109962. }
  109963. },
  109964. enumerable: true,
  109965. configurable: true
  109966. });
  109967. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  109968. /**
  109969. * gets wether the reflection is disabled.
  109970. */
  109971. get: function () {
  109972. return this._groundMirrorEnabled;
  109973. },
  109974. /**
  109975. * sets wether the reflection is disabled.
  109976. */
  109977. set: function (value) {
  109978. if (this._groundMirrorEnabled === value) {
  109979. return;
  109980. }
  109981. this._groundMirrorEnabled = value;
  109982. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  109983. if (!value) {
  109984. this.environmentHelper.groundMaterial.reflectionTexture = null;
  109985. }
  109986. else {
  109987. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  109988. }
  109989. }
  109990. },
  109991. enumerable: true,
  109992. configurable: true
  109993. });
  109994. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  109995. get: function () {
  109996. return this._defaultRenderingPipelineEnabled;
  109997. },
  109998. set: function (value) {
  109999. if (value === this._defaultRenderingPipelineEnabled) {
  110000. return;
  110001. }
  110002. this._defaultRenderingPipelineEnabled = value;
  110003. this._rebuildPostprocesses();
  110004. if (this._defaultRenderingPipeline) {
  110005. this._defaultRenderingPipelineShouldBuild = false;
  110006. this._defaultRenderingPipeline.prepare();
  110007. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  110008. }
  110009. },
  110010. enumerable: true,
  110011. configurable: true
  110012. });
  110013. /**
  110014. * Sets the engine flags to unlock all babylon features.
  110015. * Can also be configured using the scene.flags configuration object
  110016. */
  110017. SceneManager.prototype.unlockBabylonFeatures = function () {
  110018. this.scene.shadowsEnabled = true;
  110019. this.scene.particlesEnabled = true;
  110020. this.scene.postProcessesEnabled = true;
  110021. this.scene.collisionsEnabled = true;
  110022. this.scene.lightsEnabled = true;
  110023. this.scene.texturesEnabled = true;
  110024. this.scene.lensFlaresEnabled = true;
  110025. this.scene.proceduralTexturesEnabled = true;
  110026. this.scene.renderTargetsEnabled = true;
  110027. this.scene.spritesEnabled = true;
  110028. this.scene.skeletonsEnabled = true;
  110029. this.scene.audioEnabled = true;
  110030. };
  110031. /**
  110032. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  110033. */
  110034. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  110035. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  110036. // if the scen exists, dispose it.
  110037. if (this.scene) {
  110038. this.scene.dispose();
  110039. }
  110040. // create a new scene
  110041. this.scene = new babylonjs_1.Scene(this._engine);
  110042. // set a default PBR material
  110043. if (!sceneConfiguration.defaultMaterial) {
  110044. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  110045. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  110046. defaultMaterial.microSurface = 0.6;
  110047. if (this.scene.defaultMaterial) {
  110048. this.scene.defaultMaterial.dispose();
  110049. }
  110050. this.scene.defaultMaterial = defaultMaterial;
  110051. }
  110052. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  110053. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  110054. /*if (sceneConfiguration.glow) {
  110055. let options: Partial<IGlowLayerOptions> = {
  110056. mainTextureFixedSize: 512
  110057. };
  110058. if (typeof sceneConfiguration.glow === 'object') {
  110059. options = sceneConfiguration.glow
  110060. }
  110061. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  110062. }*/
  110063. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  110064. };
  110065. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  110066. if (clearModels === void 0) { clearModels = true; }
  110067. if (clearLights === void 0) { clearLights = false; }
  110068. if (clearModels) {
  110069. this.models.forEach(function (m) { return m.dispose(); });
  110070. this.models.length = 0;
  110071. }
  110072. if (clearLights) {
  110073. this.scene.lights.forEach(function (l) { return l.dispose(); });
  110074. }
  110075. };
  110076. /**
  110077. * This will update the scene's configuration, including camera, lights, environment.
  110078. * @param newConfiguration the delta that should be configured. This includes only the changes
  110079. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  110080. */
  110081. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  110082. var _this = this;
  110083. if (this._configurationContainer) {
  110084. this._globalConfiguration = this._configurationContainer.configuration;
  110085. }
  110086. else {
  110087. this._globalConfiguration = newConfiguration;
  110088. }
  110089. if (newConfiguration.lab) {
  110090. if (newConfiguration.lab.assetsRootURL) {
  110091. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  110092. }
  110093. }
  110094. // update scene configuration
  110095. if (newConfiguration.scene) {
  110096. this._configureScene(newConfiguration.scene);
  110097. }
  110098. // optimizer
  110099. if (newConfiguration.optimizer !== undefined) {
  110100. this._configureOptimizer(newConfiguration.optimizer);
  110101. }
  110102. // configure model
  110103. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  110104. this._configureModel(newConfiguration.model);
  110105. }*/
  110106. // lights
  110107. this._configureLights(newConfiguration.lights);
  110108. // environment
  110109. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  110110. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  110111. }
  110112. // camera
  110113. this._configureCamera(newConfiguration.camera);
  110114. if (newConfiguration.lab) {
  110115. if (newConfiguration.lab.environmentMap) {
  110116. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  110117. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  110118. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  110119. });
  110120. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  110121. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  110122. }
  110123. }
  110124. // rendering piplines
  110125. if (newConfiguration.lab.defaultRenderingPipelines) {
  110126. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  110127. if (typeof pipelineConfig === 'boolean') {
  110128. this.defaultRenderingPipelineEnabled = pipelineConfig;
  110129. }
  110130. else {
  110131. this.defaultRenderingPipelineEnabled = true;
  110132. }
  110133. }
  110134. if (newConfiguration.lab.environmentMainColor) {
  110135. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  110136. this.environmentHelper.setMainColor(mainColor);
  110137. }
  110138. if (newConfiguration.lab.globalLightRotation !== undefined) {
  110139. // rotate all lights that are shadow lights
  110140. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  110141. // casting and '!' are safe, due to the constraints tested before
  110142. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  110143. });
  110144. this._forceShadowUpdate = true;
  110145. }
  110146. }
  110147. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  110148. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  110149. }
  110150. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  110151. this._defaultRenderingPipelineShouldBuild = false;
  110152. this._defaultRenderingPipeline.prepare();
  110153. }
  110154. };
  110155. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  110156. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  110157. if (this._defaultRenderingPipeline) {
  110158. this._defaultRenderingPipeline.dispose();
  110159. this._defaultRenderingPipeline = null;
  110160. this.scene.autoClearDepthAndStencil = true;
  110161. this.scene.autoClear = true;
  110162. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  110163. }
  110164. return;
  110165. }
  110166. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  110167. if (pipelineConfig) {
  110168. if (!this._defaultRenderingPipeline) {
  110169. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  110170. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  110171. }
  110172. this.scene.autoClear = false;
  110173. this.scene.autoClearDepthAndStencil = false;
  110174. this._defaultRenderingPipelineShouldBuild = true;
  110175. var bloomEnabled = this._bloomEnabled;
  110176. if (typeof pipelineConfig !== 'boolean') {
  110177. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  110178. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  110179. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  110180. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  110181. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  110182. }
  110183. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  110184. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  110185. }
  110186. };
  110187. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  110188. get: function () {
  110189. return this._bloomEnabled;
  110190. },
  110191. set: function (value) {
  110192. if (this._bloomEnabled === value) {
  110193. return;
  110194. }
  110195. this._bloomEnabled = value;
  110196. this._rebuildPostprocesses();
  110197. if (this._defaultRenderingPipeline) {
  110198. this._defaultRenderingPipelineShouldBuild = false;
  110199. this._defaultRenderingPipeline.prepare();
  110200. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  110201. }
  110202. },
  110203. enumerable: true,
  110204. configurable: true
  110205. });
  110206. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  110207. get: function () {
  110208. return this._fxaaEnabled;
  110209. },
  110210. set: function (value) {
  110211. if (this._fxaaEnabled === value) {
  110212. return;
  110213. }
  110214. this._fxaaEnabled = value;
  110215. this._rebuildPostprocesses();
  110216. if (this._defaultRenderingPipeline) {
  110217. this._defaultRenderingPipelineShouldBuild = false;
  110218. this._defaultRenderingPipeline.prepare();
  110219. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  110220. }
  110221. },
  110222. enumerable: true,
  110223. configurable: true
  110224. });
  110225. /**
  110226. * internally configure the scene using the provided configuration.
  110227. * The scene will not be recreated, but just updated.
  110228. * @param sceneConfig the (new) scene configuration
  110229. */
  110230. SceneManager.prototype._configureScene = function (sceneConfig) {
  110231. // sanity check!
  110232. if (!this.scene) {
  110233. return;
  110234. }
  110235. var cc = sceneConfig.clearColor;
  110236. var oldcc = this.scene.clearColor;
  110237. if (cc) {
  110238. if (cc.r !== undefined) {
  110239. oldcc.r = cc.r;
  110240. }
  110241. if (cc.g !== undefined) {
  110242. oldcc.g = cc.g;
  110243. }
  110244. if (cc.b !== undefined) {
  110245. oldcc.b = cc.b;
  110246. }
  110247. if (cc.a !== undefined) {
  110248. oldcc.a = cc.a;
  110249. }
  110250. }
  110251. // image processing configuration - optional.
  110252. if (sceneConfig.imageProcessingConfiguration) {
  110253. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  110254. }
  110255. //animation properties override
  110256. if (sceneConfig.animationPropertiesOverride) {
  110257. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  110258. }
  110259. if (sceneConfig.environmentTexture) {
  110260. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  110261. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  110262. this.scene.environmentTexture.dispose();
  110263. }
  110264. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  110265. this.scene.environmentTexture = environmentTexture;
  110266. }
  110267. }
  110268. if (sceneConfig.debug === true) {
  110269. this.scene.debugLayer.show();
  110270. }
  110271. else if (sceneConfig.debug === false) {
  110272. if (this.scene.debugLayer.isVisible()) {
  110273. this.scene.debugLayer.hide();
  110274. }
  110275. }
  110276. if (sceneConfig.disableHdr) {
  110277. this._handleHardwareLimitations(false);
  110278. }
  110279. else {
  110280. this._handleHardwareLimitations(true);
  110281. }
  110282. if (sceneConfig.renderInBackground !== undefined) {
  110283. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  110284. }
  110285. var canvas = this._engine.getRenderingCanvas();
  110286. if (canvas) {
  110287. if (this.camera && sceneConfig.disableCameraControl) {
  110288. this.camera.detachControl(canvas);
  110289. }
  110290. else if (this.camera && sceneConfig.disableCameraControl === false) {
  110291. this.camera.attachControl(canvas);
  110292. }
  110293. }
  110294. // process mainColor changes:
  110295. if (sceneConfig.mainColor) {
  110296. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  110297. var mc = sceneConfig.mainColor;
  110298. if (mc.r !== undefined) {
  110299. this.mainColor.r = mc.r;
  110300. }
  110301. if (mc.g !== undefined) {
  110302. this.mainColor.g = mc.g;
  110303. }
  110304. if (mc.b !== undefined) {
  110305. this.mainColor.b = mc.b;
  110306. }
  110307. this.reflectionColor.copyFrom(this.mainColor);
  110308. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  110309. // reflection color
  110310. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  110311. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  110312. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  110313. this.reflectionColor.copyFrom(tmpColor3);
  110314. //update the environment, if exists
  110315. if (this.environmentHelper) {
  110316. if (this.environmentHelper.groundMaterial) {
  110317. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  110318. }
  110319. if (this.environmentHelper.skyboxMaterial) {
  110320. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  110321. }
  110322. }
  110323. }
  110324. if (sceneConfig.defaultMaterial) {
  110325. var conf = sceneConfig.defaultMaterial;
  110326. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  110327. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  110328. this.scene.defaultMaterial.dispose();
  110329. if (conf.materialType === 'standard') {
  110330. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  110331. }
  110332. else {
  110333. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  110334. }
  110335. }
  110336. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  110337. }
  110338. if (sceneConfig.flags) {
  110339. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  110340. }
  110341. this.onSceneConfiguredObservable.notifyObservers({
  110342. sceneManager: this,
  110343. object: this.scene,
  110344. newConfiguration: sceneConfig
  110345. });
  110346. };
  110347. /**
  110348. * Configure the scene optimizer.
  110349. * The existing scene optimizer will be disposed and a new one will be created.
  110350. * @param optimizerConfig the (new) optimizer configuration
  110351. */
  110352. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  110353. var _this = this;
  110354. if (typeof optimizerConfig === 'boolean') {
  110355. if (this.sceneOptimizer) {
  110356. this.sceneOptimizer.stop();
  110357. this.sceneOptimizer.dispose();
  110358. delete this.sceneOptimizer;
  110359. }
  110360. if (optimizerConfig) {
  110361. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  110362. this.sceneOptimizer.start();
  110363. }
  110364. }
  110365. else {
  110366. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  110367. // check for degradation
  110368. if (optimizerConfig.degradation) {
  110369. switch (optimizerConfig.degradation) {
  110370. case "low":
  110371. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  110372. break;
  110373. case "moderate":
  110374. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  110375. break;
  110376. case "hight":
  110377. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  110378. break;
  110379. }
  110380. }
  110381. if (this.sceneOptimizer) {
  110382. this.sceneOptimizer.stop();
  110383. this.sceneOptimizer.dispose();
  110384. }
  110385. if (optimizerConfig.custom) {
  110386. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  110387. if (customOptimizer_1) {
  110388. optimizerOptions.addCustomOptimization(function () {
  110389. return customOptimizer_1(_this);
  110390. }, function () {
  110391. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  110392. });
  110393. }
  110394. }
  110395. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  110396. this.sceneOptimizer.start();
  110397. }
  110398. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  110399. sceneManager: this,
  110400. object: this.sceneOptimizer,
  110401. newConfiguration: optimizerConfig
  110402. });
  110403. };
  110404. /**
  110405. * configure all models using the configuration.
  110406. * @param modelConfiguration the configuration to use to reconfigure the models
  110407. */
  110408. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  110409. this.models.forEach(model => {
  110410. model.updateConfiguration(modelConfiguration);
  110411. });
  110412. this.onModelsConfiguredObservable.notifyObservers({
  110413. sceneManager: this,
  110414. object: this.models,
  110415. newConfiguration: modelConfiguration
  110416. });
  110417. }*/
  110418. /**
  110419. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  110420. * @param cameraConfig the new camera configuration
  110421. * @param model optionally use the model to configure the camera.
  110422. */
  110423. SceneManager.prototype._configureCamera = function (cameraConfig) {
  110424. var _this = this;
  110425. if (cameraConfig === void 0) { cameraConfig = {}; }
  110426. if (!this.scene.activeCamera) {
  110427. var attachControl = true;
  110428. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  110429. attachControl = false;
  110430. }
  110431. this.scene.createDefaultCamera(true, true, attachControl);
  110432. this.camera = this.scene.activeCamera;
  110433. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  110434. }
  110435. if (cameraConfig.position) {
  110436. var newPosition = this.camera.position.clone();
  110437. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  110438. this.camera.setPosition(newPosition);
  110439. }
  110440. if (cameraConfig.target) {
  110441. var newTarget = this.camera.target.clone();
  110442. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  110443. this.camera.setTarget(newTarget);
  110444. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  110445. this._focusOnModel(this.models[0]);
  110446. }*/
  110447. if (cameraConfig.rotation) {
  110448. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  110449. }
  110450. if (cameraConfig.behaviors) {
  110451. for (var name_1 in cameraConfig.behaviors) {
  110452. if (cameraConfig.behaviors[name_1] !== undefined) {
  110453. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  110454. }
  110455. }
  110456. }
  110457. ;
  110458. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  110459. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  110460. });
  110461. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  110462. var sceneDiagonalLenght = sceneDiagonal.length();
  110463. if (isFinite(sceneDiagonalLenght))
  110464. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  110465. else {
  110466. this.camera.upperRadiusLimit = 10;
  110467. }
  110468. // sanity check!
  110469. if (this.scene.imageProcessingConfiguration) {
  110470. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  110471. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  110472. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  110473. }
  110474. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  110475. this.onCameraConfiguredObservable.notifyObservers({
  110476. sceneManager: this,
  110477. object: this.camera,
  110478. newConfiguration: cameraConfig
  110479. });
  110480. };
  110481. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  110482. var _this = this;
  110483. if (!skyboxConifguration && !groundConfiguration) {
  110484. if (this.environmentHelper) {
  110485. this.environmentHelper.dispose();
  110486. delete this.environmentHelper;
  110487. }
  110488. ;
  110489. }
  110490. else {
  110491. var options = {
  110492. createGround: !!groundConfiguration && this._groundEnabled,
  110493. createSkybox: !!skyboxConifguration,
  110494. setupImageProcessing: false,
  110495. };
  110496. // will that cause problems with model ground configuration?
  110497. /*if (model) {
  110498. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  110499. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  110500. const halfSizeVec = sizeVec.scale(0.5);
  110501. const center = boundingInfo.min.add(halfSizeVec);
  110502. options.groundYBias = -center.y;
  110503. }*/
  110504. if (groundConfiguration) {
  110505. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  110506. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  110507. if (groundSize) {
  110508. options.groundSize = groundSize;
  110509. }
  110510. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  110511. if (groundConfig_1.shadowLevel !== undefined) {
  110512. options.groundShadowLevel = groundConfig_1.shadowLevel;
  110513. }
  110514. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  110515. if (groundConfig_1.texture) {
  110516. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  110517. }
  110518. if (groundConfig_1.color) {
  110519. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  110520. }
  110521. if (groundConfig_1.opacity !== undefined) {
  110522. options.groundOpacity = groundConfig_1.opacity;
  110523. }
  110524. if (groundConfig_1.mirror) {
  110525. options.enableGroundMirror = true;
  110526. // to prevent undefines
  110527. if (typeof groundConfig_1.mirror === "object") {
  110528. if (groundConfig_1.mirror.amount !== undefined)
  110529. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  110530. if (groundConfig_1.mirror.sizeRatio !== undefined)
  110531. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  110532. if (groundConfig_1.mirror.blurKernel !== undefined)
  110533. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  110534. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  110535. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  110536. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  110537. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  110538. if (this._defaultPipelineTextureType !== undefined)
  110539. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  110540. }
  110541. }
  110542. }
  110543. var postInitSkyboxMaterial = false;
  110544. if (skyboxConifguration) {
  110545. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  110546. if (conf.material && conf.material.imageProcessingConfiguration) {
  110547. options.setupImageProcessing = false; // will be configured later manually.
  110548. }
  110549. var skyboxSize = conf.scale;
  110550. if (skyboxSize) {
  110551. options.skyboxSize = skyboxSize;
  110552. }
  110553. options.sizeAuto = !options.skyboxSize;
  110554. if (conf.color) {
  110555. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  110556. }
  110557. if (conf.cubeTexture && conf.cubeTexture.url) {
  110558. if (typeof conf.cubeTexture.url === "string") {
  110559. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  110560. }
  110561. else {
  110562. // init later!
  110563. postInitSkyboxMaterial = true;
  110564. }
  110565. }
  110566. if (conf.material) {
  110567. postInitSkyboxMaterial = true;
  110568. }
  110569. }
  110570. options.setupImageProcessing = false; // TMP
  110571. if (!this.environmentHelper) {
  110572. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  110573. }
  110574. else {
  110575. // unlikely, but there might be a new scene! we need to dispose.
  110576. // get the scene used by the envHelper
  110577. var scene = this.environmentHelper.rootMesh.getScene();
  110578. // is it a different scene? Oh no!
  110579. if (scene !== this.scene) {
  110580. this.environmentHelper.dispose();
  110581. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  110582. }
  110583. else {
  110584. this.environmentHelper.updateOptions(options);
  110585. }
  110586. }
  110587. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  110588. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  110589. }
  110590. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  110591. if (this.environmentHelper.groundMaterial && groundConfig) {
  110592. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  110593. if (groundConfig.material) {
  110594. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  110595. }
  110596. if (this.environmentHelper.groundMirror) {
  110597. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  110598. // TODO user camera exposure value to set the mirror clear color
  110599. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  110600. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  110601. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  110602. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  110603. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  110604. this.environmentHelper.groundMirror.clearColor.a = 1;
  110605. if (!this.groundMirrorEnabled) {
  110606. this.environmentHelper.groundMaterial.reflectionTexture = null;
  110607. }
  110608. }
  110609. }
  110610. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  110611. if (skyboxMaterial) {
  110612. skyboxMaterial._perceptualColor = this.mainColor;
  110613. if (postInitSkyboxMaterial) {
  110614. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  110615. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  110616. }
  110617. }
  110618. }
  110619. }
  110620. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  110621. _this._updateGroundMirrorRenderList(model);
  110622. });
  110623. this.onEnvironmentConfiguredObservable.notifyObservers({
  110624. sceneManager: this,
  110625. object: this.environmentHelper,
  110626. newConfiguration: {
  110627. skybox: skyboxConifguration,
  110628. ground: groundConfiguration
  110629. }
  110630. });
  110631. };
  110632. /**
  110633. * configure the lights.
  110634. *
  110635. * @param lightsConfiguration the (new) light(s) configuration
  110636. * @param model optionally use the model to configure the camera.
  110637. */
  110638. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  110639. var _this = this;
  110640. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  110641. // sanity check!
  110642. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  110643. if (!lightKeys.length) {
  110644. if (!this.scene.lights.length)
  110645. this.scene.createDefaultLight(true);
  110646. }
  110647. else {
  110648. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  110649. // compare to the global (!) configuration object and dispose unneeded:
  110650. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  110651. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  110652. lightsAvailable_1.forEach(function (lName) {
  110653. if (lightsToConfigure_1.indexOf(lName) === -1) {
  110654. _this.scene.getLightByName(lName).dispose();
  110655. }
  110656. });
  110657. }
  110658. lightKeys.forEach(function (name, idx) {
  110659. var lightConfig = { type: 0 };
  110660. if (typeof lightsConfiguration[name] === 'object') {
  110661. lightConfig = lightsConfiguration[name];
  110662. }
  110663. if (typeof lightsConfiguration[name] === 'number') {
  110664. lightConfig.type = lightsConfiguration[name];
  110665. }
  110666. lightConfig.name = name;
  110667. var light;
  110668. // light is not already available
  110669. if (lightsAvailable_1.indexOf(name) === -1) {
  110670. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  110671. if (!constructor)
  110672. return;
  110673. light = constructor();
  110674. }
  110675. else {
  110676. // available? get it from the scene
  110677. light = _this.scene.getLightByName(name);
  110678. if (typeof lightsConfiguration[name] === 'boolean') {
  110679. lightConfig.type = light.getTypeID();
  110680. }
  110681. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  110682. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  110683. light.dispose();
  110684. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  110685. if (!constructor)
  110686. return;
  110687. light = constructor();
  110688. }
  110689. }
  110690. // if config set the light to false, dispose it.
  110691. if (lightsConfiguration[name] === false) {
  110692. light.dispose();
  110693. return;
  110694. }
  110695. //enabled
  110696. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  110697. light.setEnabled(enabled);
  110698. helper_1.extendClassWithConfig(light, lightConfig);
  110699. //position. Some lights don't support shadows
  110700. if (light instanceof babylonjs_1.ShadowLight) {
  110701. // set default values
  110702. light.shadowMinZ = light.shadowMinZ || 0.2;
  110703. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  110704. if (lightConfig.target) {
  110705. if (light.setDirectionToTarget) {
  110706. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  110707. light.setDirectionToTarget(target);
  110708. }
  110709. }
  110710. else if (lightConfig.direction) {
  110711. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  110712. light.direction = direction;
  110713. }
  110714. var isShadowEnabled = false;
  110715. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  110716. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  110717. isShadowEnabled = true;
  110718. }
  110719. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  110720. var spotLight = light;
  110721. if (lightConfig.spotAngle !== undefined) {
  110722. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  110723. }
  110724. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  110725. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  110726. }
  110727. isShadowEnabled = true;
  110728. }
  110729. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  110730. if (lightConfig.shadowFieldOfView) {
  110731. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  110732. }
  110733. isShadowEnabled = true;
  110734. }
  110735. var shadowGenerator_1 = light.getShadowGenerator();
  110736. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  110737. var bufferSize = lightConfig.shadowBufferSize || 256;
  110738. if (!shadowGenerator_1) {
  110739. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  110740. }
  110741. var blurKernel = _this.getBlurKernel(light, bufferSize);
  110742. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  110743. shadowGenerator_1.blurKernel = blurKernel;
  110744. //override defaults
  110745. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  110746. // add the focues meshes to the shadow list
  110747. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  110748. _this._updateShadowRenderList(shadowGenerator_1, model);
  110749. });
  110750. //if (model) {
  110751. _this._updateShadowRenderList(shadowGenerator_1);
  110752. //}
  110753. }
  110754. else if (shadowGenerator_1) {
  110755. shadowGenerator_1.dispose();
  110756. }
  110757. }
  110758. });
  110759. // render priority
  110760. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  110761. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  110762. var configuration = globalLightsConfiguration_1[name];
  110763. var light = _this.scene.getLightByName(name);
  110764. // sanity check
  110765. if (!light)
  110766. return;
  110767. light.renderPriority = -idx;
  110768. });
  110769. }
  110770. this.onLightsConfiguredObservable.notifyObservers({
  110771. sceneManager: this,
  110772. object: this.scene.lights,
  110773. newConfiguration: lightsConfiguration
  110774. });
  110775. };
  110776. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  110777. var focusMeshes = model ? model.meshes : this.scene.meshes;
  110778. // add the focues meshes to the shadow list
  110779. var shadownMap = shadowGenerator.getShadowMap();
  110780. if (!shadownMap)
  110781. return;
  110782. if (resetList && shadownMap.renderList) {
  110783. shadownMap.renderList.length = 0;
  110784. }
  110785. else {
  110786. shadownMap.renderList = shadownMap.renderList || [];
  110787. }
  110788. for (var index = 0; index < focusMeshes.length; index++) {
  110789. var mesh = focusMeshes[index];
  110790. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  110791. shadownMap.renderList.push(mesh);
  110792. }
  110793. }
  110794. if (!this._shadowGroundPlane) {
  110795. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  110796. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  110797. shadowGroundPlane.useVertexColors = false;
  110798. //material isn't ever used in rendering, just used to set back face culling
  110799. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  110800. shadowGroundPlane.material.backFaceCulling = false;
  110801. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  110802. shadowGroundPlane.freezeWorldMatrix();
  110803. this._shadowGroundPlane = shadowGroundPlane;
  110804. this.scene.removeMesh(shadowGroundPlane);
  110805. }
  110806. }
  110807. else {
  110808. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  110809. this._shadowGroundPlane.dispose();
  110810. this._shadowGroundPlane = null;
  110811. }
  110812. }
  110813. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  110814. shadownMap.renderList.push(this._shadowGroundPlane);
  110815. }
  110816. };
  110817. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  110818. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  110819. var focusMeshes = model ? model.meshes : this.scene.meshes;
  110820. var renderList = this.environmentHelper.groundMirror.renderList;
  110821. if (resetList) {
  110822. renderList.length = 0;
  110823. }
  110824. for (var index = 0; index < focusMeshes.length; index++) {
  110825. var mesh = focusMeshes[index];
  110826. if (renderList.indexOf(mesh) === -1) {
  110827. renderList.push(mesh);
  110828. }
  110829. }
  110830. }
  110831. };
  110832. /**
  110833. * Gets the shadow map blur kernel according to the light configuration.
  110834. * @param light The light used to generate the shadows
  110835. * @param bufferSize The size of the shadow map
  110836. * @return the kernel blur size
  110837. */
  110838. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  110839. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  110840. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  110841. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  110842. }
  110843. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  110844. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  110845. }
  110846. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  110847. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  110848. }
  110849. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  110850. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  110851. return blurKernel;
  110852. };
  110853. /**
  110854. * Alters render settings to reduce features based on hardware feature limitations
  110855. * @param enableHDR Allows the viewer to run in HDR mode.
  110856. */
  110857. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  110858. if (enableHDR === void 0) { enableHDR = true; }
  110859. //flip rendering settings switches based on hardware support
  110860. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  110861. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  110862. //shadows are disabled if there's not enough varyings for a single shadow
  110863. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  110864. this._maxShadows = 0;
  110865. }
  110866. else {
  110867. this._maxShadows = 3;
  110868. }
  110869. //can we render to any >= 16-bit targets (required for HDR)
  110870. var caps = this._engine.getCaps();
  110871. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  110872. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  110873. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  110874. if (linearHalfFloatTargets) {
  110875. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  110876. this._shadowGeneratorBias = 0.002;
  110877. }
  110878. else if (linearFloatTargets) {
  110879. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  110880. this._shadowGeneratorBias = 0.001;
  110881. }
  110882. else {
  110883. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  110884. this._shadowGeneratorBias = 0.001;
  110885. }
  110886. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  110887. };
  110888. /**
  110889. * Dispoe the entire viewer including the scene and the engine
  110890. */
  110891. SceneManager.prototype.dispose = function () {
  110892. // this.onCameraConfiguredObservable.clear();
  110893. this.onEnvironmentConfiguredObservable.clear();
  110894. this.onLightsConfiguredObservable.clear();
  110895. this.onModelsConfiguredObservable.clear();
  110896. this.onSceneConfiguredObservable.clear();
  110897. this.onSceneInitObservable.clear();
  110898. this.onSceneOptimizerConfiguredObservable.clear();
  110899. if (this.sceneOptimizer) {
  110900. this.sceneOptimizer.stop();
  110901. this.sceneOptimizer.dispose();
  110902. }
  110903. if (this.environmentHelper) {
  110904. this.environmentHelper.dispose();
  110905. }
  110906. this.models.forEach(function (model) {
  110907. model.dispose();
  110908. });
  110909. if (this._defaultRenderingPipeline) {
  110910. this._defaultRenderingPipeline.dispose();
  110911. }
  110912. this.models.length = 0;
  110913. if (this.scene) {
  110914. this.scene.dispose();
  110915. }
  110916. };
  110917. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  110918. var behavior;
  110919. var type;
  110920. if (typeof behaviorConfig === 'object') {
  110921. type = behaviorConfig.type;
  110922. }
  110923. else if (typeof behaviorConfig === 'number') {
  110924. type = behaviorConfig;
  110925. }
  110926. else {
  110927. type = this._cameraBehaviorMapping[name];
  110928. }
  110929. if (type === undefined)
  110930. return;
  110931. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  110932. var enabled = true;
  110933. if (typeof behaviorConfig === 'boolean') {
  110934. enabled = behaviorConfig;
  110935. }
  110936. // constructing behavior
  110937. switch (type) {
  110938. case 0 /* AUTOROTATION */:
  110939. this.camera.useAutoRotationBehavior = enabled;
  110940. behavior = this.camera.autoRotationBehavior;
  110941. break;
  110942. case 1 /* BOUNCING */:
  110943. this.camera.useBouncingBehavior = enabled;
  110944. behavior = this.camera.bouncingBehavior;
  110945. break;
  110946. case 2 /* FRAMING */:
  110947. this.camera.useFramingBehavior = enabled;
  110948. behavior = this.camera.framingBehavior;
  110949. break;
  110950. default:
  110951. behavior = null;
  110952. break;
  110953. }
  110954. if (behavior) {
  110955. this._cameraBehaviorMapping[name] = type;
  110956. if (typeof behaviorConfig === "object") {
  110957. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  110958. }
  110959. }
  110960. // post attach configuration. Some functionalities require the attached camera.
  110961. switch (type) {
  110962. case 0 /* AUTOROTATION */:
  110963. break;
  110964. case 1 /* BOUNCING */:
  110965. break;
  110966. case 2 /* FRAMING */:
  110967. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  110968. if (config.zoomOnBoundingInfo) {
  110969. behavior.zoomOnMeshHierarchy(model.rootMesh);
  110970. }
  110971. });
  110972. break;
  110973. }
  110974. };
  110975. return SceneManager;
  110976. }());
  110977. exports.SceneManager = SceneManager;
  110978. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUErakI7QUFDL2pCLGtEQUFtUjtBQUNuUixvREFBK0Q7QUFDL0Qsb0NBQWtEO0FBRWxELGlEQUFnRDtBQUNoRCx5Q0FBZ0U7QUFnQmhFO0lBc0ZJLHNCQUFvQixPQUFlLEVBQVUsdUJBQStDLEVBQVUsbUJBQXdDO1FBQTlJLGlCQXlFQztRQXpFbUIsWUFBTyxHQUFQLE9BQU8sQ0FBUTtRQUFVLDRCQUF1QixHQUF2Qix1QkFBdUIsQ0FBd0I7UUFBVSx3QkFBbUIsR0FBbkIsbUJBQW1CLENBQXFCO1FBakN0SSw4QkFBeUIsR0FBWSxJQUFJLENBQUM7UUFpQmpDLFdBQU0sR0FBRyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBRWpDLHVCQUFrQixHQUFZLEtBQUssQ0FBQztRQXVIcEMsb0JBQWUsR0FBWSxJQUFJLENB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ksSUFBSSxDQUFDLG1CQUFtQixDQUFDLHVCQUF1QixDQUFDLEdBQUcsQ0FBQyxVQUFDLEtBQUs7b0JBQ25GLElBQUksTUFBTSxDQUFDLGtCQUFrQixFQUFFO3dCQUNULFFBQVMsQ0FBQyxtQkFBbUIsQ0FBQyxLQUFLLENBQUMsUUFBUSxDQUFDLENBQUM7cUJBQ25FO2dCQUNMLENBQUMsQ0FBQyxDQUFDO2dCQUNILE1BQU07U0FDYjtJQUNMLENBQUM7SUFDTCxtQkFBQztBQUFELENBQUMsQUF4MkNELElBdzJDQztBQXgyQ1ksb0NBQVkifQ==
  110979. /***/ }),
  110980. /* 23 */
  110981. /***/ (function(module, exports, __webpack_require__) {
  110982. "use strict";
  110983. Object.defineProperty(exports, "__esModule", { value: true });
  110984. /**
  110985. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  110986. * native GroupAnimation class.
  110987. */
  110988. var GroupModelAnimation = /** @class */ (function () {
  110989. /**
  110990. * Create a new GroupModelAnimation object using an AnimationGroup object
  110991. * @param _animationGroup The aniamtion group to base the class on
  110992. */
  110993. function GroupModelAnimation(_animationGroup) {
  110994. var _this = this;
  110995. this._animationGroup = _animationGroup;
  110996. this._state = 0 /* INIT */;
  110997. this._playMode = 1 /* LOOP */;
  110998. this._animationGroup.onAnimationEndObservable.add(function () {
  110999. _this.stop();
  111000. _this._state = 4 /* ENDED */;
  111001. });
  111002. }
  111003. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  111004. /**
  111005. * Get the animation's name
  111006. */
  111007. get: function () {
  111008. return this._animationGroup.name;
  111009. },
  111010. enumerable: true,
  111011. configurable: true
  111012. });
  111013. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  111014. /**
  111015. * Get the current animation's state
  111016. */
  111017. get: function () {
  111018. return this._state;
  111019. },
  111020. enumerable: true,
  111021. configurable: true
  111022. });
  111023. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  111024. /**
  111025. * Gets the speed ratio to use for all animations
  111026. */
  111027. get: function () {
  111028. return this._animationGroup.speedRatio;
  111029. },
  111030. /**
  111031. * Sets the speed ratio to use for all animations
  111032. */
  111033. set: function (value) {
  111034. this._animationGroup.speedRatio = value;
  111035. },
  111036. enumerable: true,
  111037. configurable: true
  111038. });
  111039. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  111040. /**
  111041. * Get the max numbers of frame available in the animation group
  111042. *
  111043. * In correlation to an arry, this would be ".length"
  111044. */
  111045. get: function () {
  111046. return this._animationGroup.to - this._animationGroup.from;
  111047. },
  111048. enumerable: true,
  111049. configurable: true
  111050. });
  111051. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  111052. /**
  111053. * Get the current frame playing right now.
  111054. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  111055. *
  111056. * In correlation to an array, this would be the current index
  111057. */
  111058. get: function () {
  111059. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  111060. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  111061. }
  111062. else {
  111063. return 0;
  111064. }
  111065. },
  111066. enumerable: true,
  111067. configurable: true
  111068. });
  111069. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  111070. /**
  111071. * Get the FPS value of this animation
  111072. */
  111073. get: function () {
  111074. // get the first currentFrame found
  111075. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  111076. var animatable = this._animationGroup.animatables[i];
  111077. var animations = animatable.getAnimations();
  111078. if (!animations || !animations.length) {
  111079. continue;
  111080. }
  111081. for (var idx = 0; idx < animations.length; ++idx) {
  111082. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  111083. return animations[idx].animation.framePerSecond;
  111084. }
  111085. }
  111086. }
  111087. return 0;
  111088. },
  111089. enumerable: true,
  111090. configurable: true
  111091. });
  111092. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  111093. /**
  111094. * What is the animation'S play mode (looping or played once)
  111095. */
  111096. get: function () {
  111097. return this._playMode;
  111098. },
  111099. /**
  111100. * Set the play mode.
  111101. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  111102. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  111103. */
  111104. set: function (value) {
  111105. if (value === this._playMode) {
  111106. return;
  111107. }
  111108. this._playMode = value;
  111109. if (this.state === 1 /* PLAYING */) {
  111110. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  111111. }
  111112. else {
  111113. this._animationGroup.reset();
  111114. this._state = 0 /* INIT */;
  111115. }
  111116. },
  111117. enumerable: true,
  111118. configurable: true
  111119. });
  111120. /**
  111121. * Reset the animation group
  111122. */
  111123. GroupModelAnimation.prototype.reset = function () {
  111124. this._animationGroup.reset();
  111125. };
  111126. /**
  111127. * Restart the animation group
  111128. */
  111129. GroupModelAnimation.prototype.restart = function () {
  111130. if (this.state === 2 /* PAUSED */)
  111131. this._animationGroup.restart();
  111132. else
  111133. this.start();
  111134. };
  111135. /**
  111136. *
  111137. * @param frameNumber Go to a specific frame in the animation
  111138. */
  111139. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  111140. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  111141. };
  111142. /**
  111143. * Start playing the animation.
  111144. */
  111145. GroupModelAnimation.prototype.start = function () {
  111146. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  111147. if (this._animationGroup.isStarted) {
  111148. this._state = 1 /* PLAYING */;
  111149. }
  111150. };
  111151. /**
  111152. * Pause the animation
  111153. */
  111154. GroupModelAnimation.prototype.pause = function () {
  111155. this._animationGroup.pause();
  111156. this._state = 2 /* PAUSED */;
  111157. };
  111158. /**
  111159. * Stop the animation.
  111160. * This will fail silently if the animation group is already stopped.
  111161. */
  111162. GroupModelAnimation.prototype.stop = function () {
  111163. this._animationGroup.stop();
  111164. if (!this._animationGroup.isStarted) {
  111165. this._state = 3 /* STOPPED */;
  111166. }
  111167. };
  111168. /**
  111169. * Dispose this animation object.
  111170. */
  111171. GroupModelAnimation.prototype.dispose = function () {
  111172. this._animationGroup.dispose();
  111173. };
  111174. return GroupModelAnimation;
  111175. }());
  111176. exports.GroupModelAnimation = GroupModelAnimation;
  111177. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixDQUFDLEdBQUcsQ0FBQztZQUM5QyxLQUFJLENBQUMsSUFBSSxFQUFFLENBQUM7WUFDWixLQUFJLENBQUMsTUFBTSxnQkFBdUIsQ0FBQztRQUN2QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFLRCxzQkFBVyxxQ0FBSTtRQUhmOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDO1FBQ3JDLENBQUM7OztPQUFBO0lBS0Qsc0JBQVcsc0NBQUs7UUFIaEI7O1dBRUc7YUFDSDtZQUNJLE9BQU8sSUFBSSxDQUFDLE1BQU0sQ0FBQztRQUN2QixDQUFDOzs7T0FBQTtJQUtELHNCQUFXLDJDQUFVO1FBSHJCOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsVUFBVSxDQUFDO1F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FBRSxDQUFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  111178. /***/ }),
  111179. /* 24 */
  111180. /***/ (function(module, exports, __webpack_require__) {
  111181. "use strict";
  111182. Object.defineProperty(exports, "__esModule", { value: true });
  111183. var environmentSerializer_1 = __webpack_require__(25);
  111184. var babylonjs_1 = __webpack_require__(0);
  111185. var texture_1 = __webpack_require__(12);
  111186. /**
  111187. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  111188. * The APIs in all labs-related classes and configuration might change.
  111189. * Once stable, lab features will be moved to the publis API and configuration object.
  111190. */
  111191. var ViewerLabs = /** @class */ (function () {
  111192. function ViewerLabs(_scene) {
  111193. this._scene = _scene;
  111194. this.environment = {
  111195. //irradiance
  111196. irradiancePolynomialCoefficients: {
  111197. x: new babylonjs_1.Vector3(0, 0, 0),
  111198. y: new babylonjs_1.Vector3(0, 0, 0),
  111199. z: new babylonjs_1.Vector3(0, 0, 0),
  111200. xx: new babylonjs_1.Vector3(0, 0, 0),
  111201. yy: new babylonjs_1.Vector3(0, 0, 0),
  111202. zz: new babylonjs_1.Vector3(0, 0, 0),
  111203. yz: new babylonjs_1.Vector3(0, 0, 0),
  111204. zx: new babylonjs_1.Vector3(0, 0, 0),
  111205. xy: new babylonjs_1.Vector3(0, 0, 0)
  111206. },
  111207. textureIntensityScale: 1.0
  111208. };
  111209. }
  111210. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  111211. var _this = this;
  111212. //@! todo: should loadEnvironment cancel any currently loading environments?
  111213. if (data instanceof ArrayBuffer) {
  111214. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  111215. if (onSuccess)
  111216. onSuccess(this.environment);
  111217. }
  111218. else if (typeof data === 'string') {
  111219. var url = this.getAssetUrl(data);
  111220. this._scene._loadFile(url, function (arrayBuffer) {
  111221. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  111222. if (onSuccess)
  111223. onSuccess(_this.environment);
  111224. }, function (progressEvent) { if (onProgress)
  111225. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  111226. if (onError) {
  111227. onError(e);
  111228. }
  111229. });
  111230. }
  111231. else {
  111232. //data assumed to be PBREnvironment object
  111233. this.environment = data;
  111234. if (onSuccess)
  111235. onSuccess(data);
  111236. }
  111237. };
  111238. /**
  111239. * Applies an `EnvironmentMapConfiguration` to the scene
  111240. * @param environmentMapConfiguration Environment map configuration to apply
  111241. */
  111242. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  111243. if (!this.environment)
  111244. return;
  111245. //set orientation
  111246. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  111247. // Add env texture to the scene.
  111248. if (this.environment.specularTexture) {
  111249. // IE crashes when disposing the old texture and setting a new one
  111250. if (!this._scene.environmentTexture) {
  111251. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  111252. }
  111253. if (this._scene.environmentTexture) {
  111254. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  111255. this._scene.environmentTexture.invertZ = true;
  111256. this._scene.environmentTexture.lodLevelInAlpha = true;
  111257. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  111258. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  111259. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  111260. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  111261. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  111262. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  111263. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  111264. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  111265. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  111266. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  111267. this._scene.environmentTexture.sphericalPolynomial = poly;
  111268. //set orientation
  111269. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  111270. }
  111271. }
  111272. };
  111273. /**
  111274. * Get an environment asset url by using the configuration if the path is not absolute.
  111275. * @param url Asset url
  111276. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  111277. */
  111278. ViewerLabs.prototype.getAssetUrl = function (url) {
  111279. var returnUrl = url;
  111280. if (url && url.toLowerCase().indexOf("//") === -1) {
  111281. if (!this.assetsRootURL) {
  111282. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  111283. return url;
  111284. }
  111285. returnUrl = this.assetsRootURL + returnUrl;
  111286. }
  111287. return returnUrl;
  111288. };
  111289. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  111290. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  111291. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  111292. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  111293. axis.normalize();
  111294. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  111295. babylonjs_1.Matrix.TranslationToRef(babylonjs_1.Tmp.Vector3[0].x, babylonjs_1.Tmp.Vector3[0].y, babylonjs_1.Tmp.Vector3[0].z, babylonjs_1.Tmp.Matrix[0]);
  111296. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  111297. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  111298. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  111299. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  111300. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  111301. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  111302. shadowLight.setDirectionToTarget(target);
  111303. };
  111304. return ViewerLabs;
  111305. }());
  111306. exports.ViewerLabs = ViewerLabs;
  111307. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtRQUFiLFdBQU0sR0FBTixNQUFNLENBQU87UUFHMUIsZ0JBQVcsR0FBbUI7WUFDakMsWUFBWTtZQUNaLGdDQUFnQyxFQUFFO2dCQUM5QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO2dCQUN2QixDQUFDLEVBQUUsSUFBSSxtQkFBTyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ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xDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxhQUFhLENBQUMsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFMUQsZUFBRyxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLENBQUMsZUFBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsRUFBRSxlQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxFQUFFLGVBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUUzRSxXQUFXLENBQUMsUUFBUSxDQUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  111308. /***/ }),
  111309. /* 25 */
  111310. /***/ (function(module, exports, __webpack_require__) {
  111311. "use strict";
  111312. Object.defineProperty(exports, "__esModule", { value: true });
  111313. var babylonjs_1 = __webpack_require__(0);
  111314. var texture_1 = __webpack_require__(12);
  111315. /**
  111316. * A static class proving methods to aid parsing Spectre environment files
  111317. */
  111318. var EnvironmentDeserializer = /** @class */ (function () {
  111319. function EnvironmentDeserializer() {
  111320. }
  111321. /**
  111322. * Parses an arraybuffer into a new PBREnvironment object
  111323. * @param arrayBuffer The arraybuffer of the Spectre environment file
  111324. * @return a PBREnvironment object
  111325. */
  111326. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  111327. var environment = {
  111328. //irradiance
  111329. irradiancePolynomialCoefficients: {
  111330. x: new babylonjs_1.Vector3(0, 0, 0),
  111331. y: new babylonjs_1.Vector3(0, 0, 0),
  111332. z: new babylonjs_1.Vector3(0, 0, 0),
  111333. xx: new babylonjs_1.Vector3(0, 0, 0),
  111334. yy: new babylonjs_1.Vector3(0, 0, 0),
  111335. zz: new babylonjs_1.Vector3(0, 0, 0),
  111336. yz: new babylonjs_1.Vector3(0, 0, 0),
  111337. zx: new babylonjs_1.Vector3(0, 0, 0),
  111338. xy: new babylonjs_1.Vector3(0, 0, 0)
  111339. },
  111340. //specular
  111341. textureIntensityScale: 1.0,
  111342. };
  111343. //read .env
  111344. var littleEndian = false;
  111345. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  111346. var dataView = new DataView(arrayBuffer);
  111347. var pos = 0;
  111348. for (var i = 0; i < magicBytes.length; i++) {
  111349. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  111350. babylonjs_1.Tools.Error('Not a Spectre environment map');
  111351. }
  111352. }
  111353. var version = dataView.getUint16(pos, littleEndian);
  111354. pos += 2;
  111355. if (version !== 1) {
  111356. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  111357. }
  111358. //read json descriptor - collect characters up to null terminator
  111359. var descriptorString = '';
  111360. var charCode = 0x00;
  111361. while ((charCode = dataView.getUint8(pos++))) {
  111362. descriptorString += String.fromCharCode(charCode);
  111363. }
  111364. var descriptor = JSON.parse(descriptorString);
  111365. var payloadPos = pos;
  111366. //irradiance
  111367. switch (descriptor.irradiance.type) {
  111368. case 'irradiance_sh_coefficients_9':
  111369. //irradiance
  111370. var harmonics = descriptor.irradiance;
  111371. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  111372. //harmonics now represent radiance
  111373. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  111374. break;
  111375. default:
  111376. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  111377. }
  111378. //specular
  111379. switch (descriptor.specular.type) {
  111380. case 'cubemap_faces':
  111381. var specularDescriptor = descriptor.specular;
  111382. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  111383. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  111384. var mipmaps = specularDescriptor.mipmaps;
  111385. var imageType = specularDescriptor.imageType;
  111386. for (var l = 0; l < mipmaps.length; l++) {
  111387. var faceRanges = mipmaps[l];
  111388. specularTexture.source[l] = [];
  111389. for (var i = 0; i < 6; i++) {
  111390. var range = faceRanges[i];
  111391. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  111392. switch (imageType) {
  111393. case 'png':
  111394. //construct image element from bytes
  111395. var image = new Image();
  111396. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  111397. image.src = src;
  111398. specularTexture.source[l][i] = image;
  111399. break;
  111400. default:
  111401. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  111402. }
  111403. }
  111404. }
  111405. break;
  111406. default:
  111407. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  111408. }
  111409. return environment;
  111410. };
  111411. /**
  111412. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  111413. * L = (1/pi) * E * rho
  111414. *
  111415. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  111416. * @param harmonics Spherical harmonic coefficients (9)
  111417. */
  111418. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  111419. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  111420. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  111421. // (The pixel shader must apply albedo after texture fetches, etc).
  111422. };
  111423. /**
  111424. * Convert spherical harmonics to spherical polynomial coefficients
  111425. * @param harmonics Spherical harmonic coefficients (9)
  111426. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  111427. */
  111428. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  111429. var rPi = 1 / Math.PI;
  111430. //x
  111431. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  111432. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  111433. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  111434. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  111435. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  111436. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  111437. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  111438. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  111439. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  111440. //xx
  111441. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  111442. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  111443. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  111444. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  111445. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  111446. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  111447. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  111448. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  111449. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  111450. //yz
  111451. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  111452. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  111453. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  111454. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  111455. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  111456. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  111457. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  111458. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  111459. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  111460. };
  111461. /**
  111462. * Multiplies harmonic coefficients in place
  111463. * @param harmonics Spherical harmonic coefficients (9)
  111464. * @param scaleFactor Value to multiply by
  111465. */
  111466. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  111467. harmonics.l00[0] *= scaleFactor;
  111468. harmonics.l00[1] *= scaleFactor;
  111469. harmonics.l00[2] *= scaleFactor;
  111470. harmonics.l1_1[0] *= scaleFactor;
  111471. harmonics.l1_1[1] *= scaleFactor;
  111472. harmonics.l1_1[2] *= scaleFactor;
  111473. harmonics.l10[0] *= scaleFactor;
  111474. harmonics.l10[1] *= scaleFactor;
  111475. harmonics.l10[2] *= scaleFactor;
  111476. harmonics.l11[0] *= scaleFactor;
  111477. harmonics.l11[1] *= scaleFactor;
  111478. harmonics.l11[2] *= scaleFactor;
  111479. harmonics.l2_2[0] *= scaleFactor;
  111480. harmonics.l2_2[1] *= scaleFactor;
  111481. harmonics.l2_2[2] *= scaleFactor;
  111482. harmonics.l2_1[0] *= scaleFactor;
  111483. harmonics.l2_1[1] *= scaleFactor;
  111484. harmonics.l2_1[2] *= scaleFactor;
  111485. harmonics.l20[0] *= scaleFactor;
  111486. harmonics.l20[1] *= scaleFactor;
  111487. harmonics.l20[2] *= scaleFactor;
  111488. harmonics.l21[0] *= scaleFactor;
  111489. harmonics.l21[1] *= scaleFactor;
  111490. harmonics.l21[2] *= scaleFactor;
  111491. harmonics.l22[0] *= scaleFactor;
  111492. harmonics.l22[1] *= scaleFactor;
  111493. harmonics.l22[2] *= scaleFactor;
  111494. };
  111495. return EnvironmentDeserializer;
  111496. }());
  111497. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  111498. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTJDO0FBQzNDLHFDQUFnRTtBQW1IaEU7O0dBRUc7QUFDSDtJQUFBO0lBcU5BLENBQUM7SUFuTkc7Ozs7T0FJRztJQUNXLDZCQUFLLEdBQW5CLFVBQW9CLFdBQXdCO1FBQ3hDLElBQUksV0FBVyxHQUFtQjtZQUM5QixZQUFZO1lBQ1osZ0NBQWdDLEVBQUU7Z0JBQzlCLENBQUMsRUFBRSxJQUFJLG1CQUF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ztRQUNqQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  111499. /***/ }),
  111500. /* 26 */
  111501. /***/ (function(module, exports, __webpack_require__) {
  111502. "use strict";
  111503. Object.defineProperty(exports, "__esModule", { value: true });
  111504. var extended_1 = __webpack_require__(27);
  111505. var cache = {};
  111506. /**
  111507. *
  111508. * @param name the name of the custom optimizer configuration
  111509. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  111510. */
  111511. function getCustomOptimizerByName(name, upgrade) {
  111512. if (!cache[name]) {
  111513. switch (name) {
  111514. case 'extended':
  111515. if (upgrade) {
  111516. return extended_1.extendedUpgrade;
  111517. }
  111518. else {
  111519. return extended_1.extendedDegrade;
  111520. }
  111521. }
  111522. }
  111523. return cache[name];
  111524. }
  111525. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  111526. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0=
  111527. /***/ }),
  111528. /* 27 */
  111529. /***/ (function(module, exports, __webpack_require__) {
  111530. "use strict";
  111531. Object.defineProperty(exports, "__esModule", { value: true });
  111532. var babylonjs_1 = __webpack_require__(0);
  111533. /**
  111534. * A custom upgrade-oriented function configuration for the scene optimizer.
  111535. *
  111536. * @param viewer the viewer to optimize
  111537. */
  111538. function extendedUpgrade(sceneManager) {
  111539. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  111540. // if (!this.Scene.BackgroundHelper) {
  111541. // this.Scene.EngineScene.autoClear = false;
  111542. // this.Scene.BackgroundHelper = true;
  111543. // Would require a dedicated clear color;
  111544. // return false;
  111545. // }
  111546. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  111547. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  111548. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111549. return false;
  111550. }
  111551. if (!sceneManager.scene.postProcessesEnabled) {
  111552. sceneManager.scene.postProcessesEnabled = true;
  111553. return false;
  111554. }
  111555. if (!sceneManager.groundEnabled) {
  111556. sceneManager.groundEnabled = true;
  111557. return false;
  111558. }
  111559. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  111560. sceneManager.fxaaEnabled = true;
  111561. return false;
  111562. }
  111563. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  111564. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  111565. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  111566. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111567. return false;
  111568. }
  111569. if (!sceneManager.processShadows) {
  111570. sceneManager.processShadows = true;
  111571. return false;
  111572. }
  111573. if (defaultPipeline && !sceneManager.bloomEnabled) {
  111574. sceneManager.bloomEnabled = true;
  111575. return false;
  111576. }
  111577. if (!sceneManager.groundMirrorEnabled) {
  111578. sceneManager.groundMirrorEnabled = true;
  111579. return false;
  111580. }
  111581. return true;
  111582. }
  111583. exports.extendedUpgrade = extendedUpgrade;
  111584. /**
  111585. * A custom degrade-oriented function configuration for the scene optimizer.
  111586. *
  111587. * @param viewer the viewer to optimize
  111588. */
  111589. function extendedDegrade(sceneManager) {
  111590. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  111591. if (sceneManager.groundMirrorEnabled) {
  111592. sceneManager.groundMirrorEnabled = false;
  111593. return false;
  111594. }
  111595. if (defaultPipeline && sceneManager.bloomEnabled) {
  111596. sceneManager.bloomEnabled = false;
  111597. return false;
  111598. }
  111599. if (sceneManager.processShadows) {
  111600. sceneManager.processShadows = false;
  111601. return false;
  111602. }
  111603. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  111604. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  111605. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111606. return false;
  111607. }
  111608. if (defaultPipeline && sceneManager.fxaaEnabled) {
  111609. sceneManager.fxaaEnabled = false;
  111610. return false;
  111611. }
  111612. if (sceneManager.groundEnabled) {
  111613. sceneManager.groundEnabled = false;
  111614. return false;
  111615. }
  111616. if (sceneManager.scene.postProcessesEnabled) {
  111617. sceneManager.scene.postProcessesEnabled = false;
  111618. return false;
  111619. }
  111620. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  111621. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  111622. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  111623. return false;
  111624. }
  111625. // if (this.Scene.BackgroundHelper) {
  111626. // this.Scene.EngineScene.autoClear = true;
  111627. // this.Scene.BackgroundHelper = false;
  111628. // Would require a dedicated clear color;
  111629. // return false;
  111630. // }
  111631. return true;
  111632. }
  111633. exports.extendedDegrade = extendedDegrade;
  111634. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUFvRTtBQUdwRTs7OztHQUlHO0FBQ0gseUJBQWdDLFlBQTBCO0lBQ3RELElBQUksZUFBZSxHQUE2QixZQUFZLENBQUMsd0JBQXdCLENBQUM7SUFDdEYsc0NBQXNDO0lBQ3RDLDZDQUE2QztJQUM3QyxzQ0FBc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SyxDQUFDLG9CQUFvQixHQUFHLEtBQUssQ0FBQztRQUNoRCxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyx1QkFBdUIsRUFBRSxHQUFHLElBQUksRUFBRTtRQUNqRSxJQUFJLE9BQU8sR0FBRyxrQkFBTSxDQUFDLEtBQUssQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  111635. /***/ }),
  111636. /* 28 */
  111637. /***/ (function(module, exports, __webpack_require__) {
  111638. "use strict";
  111639. Object.defineProperty(exports, "__esModule", { value: true });
  111640. var mappers_1 = __webpack_require__(3);
  111641. var types_1 = __webpack_require__(29);
  111642. var configurationCompatibility_1 = __webpack_require__(53);
  111643. var _1 = __webpack_require__(1);
  111644. var babylonjs_1 = __webpack_require__(0);
  111645. /**
  111646. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  111647. * parse the object and return a conform ViewerConfiguration.
  111648. * It is a private member of the scene.
  111649. */
  111650. var ConfigurationLoader = /** @class */ (function () {
  111651. function ConfigurationLoader(_enableCache) {
  111652. if (_enableCache === void 0) { _enableCache = false; }
  111653. this._enableCache = _enableCache;
  111654. this._configurationCache = {};
  111655. this._loadRequests = [];
  111656. }
  111657. /**
  111658. * load a configuration object that is defined in the initial configuration provided.
  111659. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  111660. *
  111661. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  111662. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  111663. * @returns A promise that delivers the extended viewer configuration, when done.
  111664. */
  111665. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  111666. var _this = this;
  111667. if (initConfig === void 0) { initConfig = {}; }
  111668. var loadedConfig = _1.deepmerge({}, initConfig);
  111669. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  111670. if (loadedConfig.configuration) {
  111671. var mapperType_1 = "json";
  111672. return Promise.resolve().then(function () {
  111673. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  111674. // a file to load
  111675. var url = '';
  111676. if (typeof loadedConfig.configuration === "string") {
  111677. url = loadedConfig.configuration;
  111678. }
  111679. // if configuration is an object
  111680. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  111681. url = loadedConfig.configuration.url;
  111682. var type = loadedConfig.configuration.mapper;
  111683. // empty string?
  111684. if (!type) {
  111685. // load mapper type from filename / url
  111686. type = loadedConfig.configuration.url.split('.').pop();
  111687. }
  111688. mapperType_1 = type || mapperType_1;
  111689. }
  111690. return _this._loadFile(url);
  111691. }
  111692. else {
  111693. if (typeof loadedConfig.configuration === "object") {
  111694. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  111695. return loadedConfig.configuration.payload || {};
  111696. }
  111697. return {};
  111698. }
  111699. }).then(function (data) {
  111700. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  111701. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  111702. var merged = _1.deepmerge(extendedConfiguration, parsed);
  111703. configurationCompatibility_1.processConfigurationCompatibility(merged);
  111704. if (callback)
  111705. callback(merged);
  111706. return merged;
  111707. });
  111708. }
  111709. else {
  111710. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  111711. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  111712. if (callback)
  111713. callback(loadedConfig);
  111714. return Promise.resolve(loadedConfig);
  111715. }
  111716. };
  111717. /**
  111718. * Dispose the configuration loader. This will cancel file requests, if active.
  111719. */
  111720. ConfigurationLoader.prototype.dispose = function () {
  111721. this._loadRequests.forEach(function (request) {
  111722. request.abort();
  111723. });
  111724. this._loadRequests.length = 0;
  111725. };
  111726. ConfigurationLoader.prototype._loadFile = function (url) {
  111727. var _this = this;
  111728. var cacheReference = this._configurationCache;
  111729. if (this._enableCache && cacheReference[url]) {
  111730. return Promise.resolve(cacheReference[url]);
  111731. }
  111732. return new Promise(function (resolve, reject) {
  111733. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  111734. var idx = _this._loadRequests.indexOf(fileRequest);
  111735. if (idx !== -1)
  111736. _this._loadRequests.splice(idx, 1);
  111737. if (_this._enableCache)
  111738. cacheReference[url] = result;
  111739. resolve(result);
  111740. }, undefined, undefined, false, function (request, error) {
  111741. var idx = _this._loadRequests.indexOf(fileRequest);
  111742. if (idx !== -1)
  111743. _this._loadRequests.splice(idx, 1);
  111744. reject(error);
  111745. });
  111746. _this._loadRequests.push(fileRequest);
  111747. });
  111748. };
  111749. return ConfigurationLoader;
  111750. }());
  111751. exports.ConfigurationLoader = ConfigurationLoader;
  111752. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ3VyYXRpb24vbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQTBDO0FBRTFDLGlDQUErQztBQUMvQywyRUFBaUY7QUFFakYsK0JBQXVDO0FBQ3ZDLHVDQUFnRDtBQUVoR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 */
  111755. /***/ (function(module, exports, __webpack_require__) {
  111756. "use strict";
  111757. Object.defineProperty(exports, "__esModule", { value: true });
  111758. var minimal_1 = __webpack_require__(30);
  111759. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  111760. var default_1 = __webpack_require__(49);
  111761. exports.defaultConfiguration = default_1.defaultConfiguration;
  111762. var extended_1 = __webpack_require__(50);
  111763. var shadowLight_1 = __webpack_require__(51);
  111764. var environmentMap_1 = __webpack_require__(52);
  111765. var _1 = __webpack_require__(1);
  111766. /**
  111767. * Get the configuration type you need to use as the base for your viewer.
  111768. * The types can either be a single string, or comma separated types that will extend each other. for example:
  111769. *
  111770. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  111771. *
  111772. * @param types a comma-separated string of the type(s) or configuration to load.
  111773. */
  111774. var getConfigurationType = function (types) {
  111775. var config = {};
  111776. var typesSeparated = types.split(",");
  111777. typesSeparated.forEach(function (type) {
  111778. switch (type.trim()) {
  111779. case 'environmentMap':
  111780. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  111781. break;
  111782. case 'shadowDirectionalLight':
  111783. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  111784. break;
  111785. case 'shadowSpotLight':
  111786. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  111787. break;
  111788. case 'extended':
  111789. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  111790. break;
  111791. case 'minimal':
  111792. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  111793. break;
  111794. case 'none':
  111795. break;
  111796. case 'default':
  111797. default:
  111798. config = _1.deepmerge(config, default_1.defaultConfiguration);
  111799. break;
  111800. }
  111801. if (config.extends) {
  111802. config = _1.deepmerge(config, getConfigurationType(config.extends));
  111803. }
  111804. });
  111805. return config;
  111806. };
  111807. exports.getConfigurationType = getConfigurationType;
  111808. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXgu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tBQUssU0FBUztnQkFDVixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSw4QkFBb0IsQ0FBQyxDQUFDO2dCQUNqRCxNQUFNO1lBQ1YsS0FBSyxNQUFNO2dCQUNQLE1BQU07WUFDVixLQUFLLFNBQVMsQ0FBQztZQUNmO2dCQUNJLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDhCQUFvQixDQUFDLENBQUM7Z0JBQ2pELE1BQU07U0FDYjtRQUVELElBQUksTUFBTSxDQUFDLE9BQU8sRUFBRTtZQUNoQixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxvQkFBb0IsQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztTQUNwRTtJQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTyxNQUFNLENBQUM7QUFFbEIsQ0FBQyxDQUFBO0FBRVEsb0RBQW9CIn0=
  111809. /***/ }),
  111810. /* 30 */
  111811. /***/ (function(module, exports, __webpack_require__) {
  111812. "use strict";
  111813. Object.defineProperty(exports, "__esModule", { value: true });
  111814. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  111815. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  111816. /**
  111817. * The minimal configuration needed to make the viewer work.
  111818. * Some functionalities might not work correctly (like fill-screen)
  111819. */
  111820. exports.minimalConfiguration = {
  111821. version: "0.1",
  111822. templates: {
  111823. main: {
  111824. html: babylonjs_viewer_assets_1.defaultTemplate
  111825. },
  111826. fillContainer: {
  111827. html: babylonjs_viewer_assets_1.fillContainer,
  111828. params: {
  111829. disable: false
  111830. }
  111831. },
  111832. loadingScreen: {
  111833. html: babylonjs_viewer_assets_1.loadingScreen,
  111834. params: {
  111835. backgroundColor: "#000000",
  111836. loadingImage: babylonjs_viewer_assets_2.loading
  111837. }
  111838. },
  111839. viewer: {
  111840. html: babylonjs_viewer_assets_1.defaultViewer,
  111841. },
  111842. overlay: {
  111843. html: babylonjs_viewer_assets_1.overlay,
  111844. params: {
  111845. closeImage: babylonjs_viewer_assets_2.close,
  111846. closeText: 'Close'
  111847. }
  111848. },
  111849. error: {
  111850. html: babylonjs_viewer_assets_1.error
  111851. }
  111852. },
  111853. engine: {
  111854. antialiasing: true
  111855. }
  111856. };
  111857. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  111858. /***/ }),
  111859. /* 31 */
  111860. /***/ (function(module, exports, __webpack_require__) {
  111861. "use strict";
  111862. Object.defineProperty(exports, "__esModule", { value: true });
  111863. exports.babylonFont = __webpack_require__(32);
  111864. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  111865. /***/ }),
  111866. /* 32 */
  111867. /***/ (function(module, exports) {
  111868. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABIgAA8AAAAAH7gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp9rlZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAABxAAAAsqyRvzljdnQgAAAEHAAAACAAAAAqCdkJr2ZwZ20AAAQ8AAAA8AAAAVn8nuaOZ2FzcAAABSwAAAAMAAAADAAIABtnbHlmAAAFOAAABlUAAAh+MHVDHWhlYWQAAAuQAAAAMgAAADb+LvI4aGhlYQAAC8QAAAAVAAAAJBABCAZobXR4AAAL3AAAACYAAAAqErQDvGxvY2EAAAwEAAAAIgAAACIJ6we4bWF4cAAADCgAAAAcAAAAIACJANFuYW1lAAAMRAAABTsAAAvzM/OUeXBvc3QAABGAAAAAEwAAACD/UQB3cHJlcAAAEZQAAACJAAAA03i98g542mNgZk9knMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vwh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ejXajN6P3o3ehnXnGFMJ9ndB7yHVrWyjDH4Ivg0ZdXMXNA3Ei9mIfwCJoYWxAHjaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA="
  111869. /***/ }),
  111870. /* 33 */
  111871. /***/ (function(module, exports, __webpack_require__) {
  111872. "use strict";
  111873. Object.defineProperty(exports, "__esModule", { value: true });
  111874. exports.babylonLogo = __webpack_require__(34);
  111875. exports.close = __webpack_require__(35);
  111876. exports.fullscreen = __webpack_require__(36);
  111877. exports.helpCircle = __webpack_require__(37);
  111878. exports.loading = __webpack_require__(38);
  111879. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  111880. /***/ }),
  111881. /* 34 */
  111882. /***/ (function(module, exports) {
  111883. module.exports = "data:image/png;base64,iVBORw0KGgoAAAAN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zJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  111884. /***/ }),
  111885. /* 35 */
  111886. /***/ (function(module, exports) {
  111887. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  111888. /***/ }),
  111889. /* 36 */
  111890. /***/ (function(module, exports) {
  111891. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  111892. /***/ }),
  111893. /* 37 */
  111894. /***/ (function(module, exports) {
  111895. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAB/ElEQVR42u3Xs4JdQRzH8X9sqYrNNnbqtPELxKgWD7AsI71B7BcI21W9rNa+d27zjSac/5kzZ2J8yqPfGUn++xMwis2UcpsGuilQoJt6blHCJkbKt2I+FbSRpJVy5kos5nAVQxrDJWbFfP4wXYTqYL9kwRiuk9VFRksYJvKEGA+ZEPb3+udrOcNaJjGJtZyhTo8IKIVaOXmOMfKrrnsCo1WU+HFE/fxu9dk9asR+f8fswnU08fmTuDo8nZarat2P/DjobtFPP3dY8bGi6jNUE/MxuM58vNsFVvfHiHNqleqjmwo0a+zdW3zutr26Dk2ZPqW1oZli7/fzuT57dQqaFmUaZDNZ9HoDYIMbUEoWt+xb69EVuwG3CdfNcvtWNbqbbkB9ePVgK4DFDKGrcwO6CNPHJvvGdGpI0uEGGELk2WGfn8or33OxAUc/TulP8cnHVVENI5Vhp+mIa+TT9tm9pKkN7ab6tHEDRVo3LUGjTxuNpClyAzaRSiwGSbPeDRhJC99Ls7rno5zvpUw0zMMQQV1wdFzmezgvSZhJR1Aj+3QyW5Jx8JsD9okfV74p4ELIceNudMAjRodtfh8T4yETg7fvEf3pAqMlCw7QQah29kl2zOIiedLkOc9MicVcymkhSQtlzJVvxUg2UMxNaunCYOiihpsUsZ6R8t8f4DUz8hFGPnrb0AAAAABJRU5ErkJggg=="
  111896. /***/ }),
  111897. /* 38 */
  111898. /***/ (function(module, exports) {
  111899. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s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KR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  111900. /***/ }),
  111901. /* 39 */
  111902. /***/ (function(module, exports, __webpack_require__) {
  111903. "use strict";
  111904. Object.defineProperty(exports, "__esModule", { value: true });
  111905. exports.defaultTemplate = __webpack_require__(40);
  111906. exports.defaultViewer = __webpack_require__(41);
  111907. exports.error = __webpack_require__(42);
  111908. exports.fillContainer = __webpack_require__(43);
  111909. exports.help = __webpack_require__(44);
  111910. exports.loadingScreen = __webpack_require__(45);
  111911. exports.navbar = __webpack_require__(46);
  111912. exports.overlay = __webpack_require__(47);
  111913. exports.share = __webpack_require__(48);
  111914. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  111915. /***/ }),
  111916. /* 40 */
  111917. /***/ (function(module, exports) {
  111918. module.exports = "<style>@font-face{font-family:babylon;src:url({{babylonFont}}) format('woff');font-weight:400;font-style:normal}.icon{font-family:babylon}</style> {{#if fillScreen}} <style>body,html{width:100%;height:100%;margin:0;padding:0}</style> {{/if}} <fill-container></fill-container>";
  111919. /***/ }),
  111920. /* 41 */
  111921. /***/ (function(module, exports) {
  111922. module.exports = "<style>viewer{position:relative;overflow:hidden;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas touch-action=none> </canvas> <nav-bar></nav-bar>";
  111923. /***/ }),
  111924. /* 42 */
  111925. /***/ (function(module, exports) {
  111926. module.exports = "Error loading the model";
  111927. /***/ }),
  111928. /* 43 */
  111929. /***/ (function(module, exports) {
  111930. module.exports = "<style>fill-container{display:flex}fill-container>*{touch-action:none}</style> {{#unless disable}} <style>fill-container{width:100%;height:100%;justify-content:flex-start;align-items:stretch;align-content:stretch}fill-container>*{flex:1 1 auto;flex-direction:row;justify-content:flex-start;align-items:stretch;align-content:stretch}</style> {{/unless}} <viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  111931. /***/ }),
  111932. /* 44 */
  111933. /***/ (function(module, exports) {
  111934. module.exports = "HELP";
  111935. /***/ }),
  111936. /* 45 */
  111937. /***/ (function(module, exports) {
  111938. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  111939. /***/ }),
  111940. /* 46 */
  111941. /***/ (function(module, exports) {
  111942. module.exports = "<style>nav-bar{position:absolute;height:48px;width:100%;bottom:10px;display:flex;justify-content:center}nav-bar .nav-container{display:flex;flex-direction:row;margin:0 10px;height:100%;width:100%;justify-content:center}nav-bar .animation-control{background-color:rgba(91,93,107,.75);display:flex;flex-direction:row;height:100%;width:100%;max-width:1280px;justify-content:center}nav-bar .flex-container{display:flex;flex-direction:row;justify-content:center;height:100%;width:100%}nav-bar button{background:0 0;border:none;color:#fff;margin:0;padding:0;height:100%;min-width:48px;cursor:pointer}nav-bar button:active,nav-bar button:focus,nav-bar button:hover{background:0 0;border:none;outline:0}nav-bar button:hover{background-color:rgba(22,24,26,.2)}nav-bar .control-text{font-family:\"Segoe UI\";font-size:12px;font-weight:400;pointer-events:none}nav-bar .icon,nav-bar img{pointer-events:none}.logo-button{display:flex;align-items:center;flex-direction:row;justify-content:center;background-color:rgba(91,93,107,.75);height:48px;min-width:48px;margin-right:4px}.logo-button img{height:20px;width:20px}.types{display:flex;flex-direction:column;width:48px}.speed .flex-container,.types .flex-container{align-items:center}.menu-options{position:absolute;bottom:48px;width:48px;background-color:rgba(22,24,26,.9)}.animation-label,.help,.logo-button,.speed,.types-icon{display:none}.types-icon:after{font-size:16px;content:\"\\F6BE\"}.up-icon:after{line-height:16px;font-size:12px;content:\"\\E70E\"}.play-icon:after{font-size:16px;content:\"\\E768\"}.pause-icon:after{font-size:16px;content:\"\\E769\"}.fullscreen-icon:after{font-size:16px;content:\"\\E740\"}.help-icon:after{font-size:16px;content:\"\\EF4E\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-circle{width:12px;height:12px;border:2px solid #fff;border-radius:50%;background-color:#5b5d6b;cursor:pointer;position:relative;bottom:10px;pointer-events:none}.default-control{display:flex;flex-direction:row;height:100%;background-color:rgba(91,93,107,.75)}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button:hover{background-color:transparent;color:#fff}.menu-options .animation-number{margin:0 18px 0 6px}.menu-options .speed-text{margin-right:18px}.menu-options{visibility:hidden}.open .menu-options{visibility:visible}.types .menu-options{width:144px}.types .menu-options button{padding:0 8px;justify-content:left}.types .menu-options button>*{display:flex;margin:8px}.types .menu-options button span.animation-number{display:none}.fullscreen{display:none}@media screen and (min-width:540px){.help,.speed,.types-icon{display:inline-block}.logo-button{display:flex}.types{width:84px}.progress-bar-container{margin:0 12px}.speed{width:64px}.speed .menu-options{width:64px}.fullscreen{display:block}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px;text-overflow:ellipsis;overflow:hidden}nav-bar button.animation-buttons{padding:0 8px;justify-content:left}.icon.up-icon{margin-left:8px}nav-bar button.animation-buttons>div{display:flex;pointer-events:none}.animation-number{display:none}.progress-bar-container{margin:0 12px}.types{width:144px}}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;outline:0;margin:0 12px;height:30px;background-color:transparent}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:#fff}.progress-wrapper::-moz-range-progress{background-color:#fff;height:2px}.progress-wrapper::-moz-range-thumb{width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1)}.progress-wrapper::-moz-range-track{background:#fff;height:2px}.progress-wrapper::-ms-track{height:2px;background:0 0;border-color:transparent;border-width:10px 0;color:transparent}.progress-wrapper::-ms-fill-lower{background:#fff;border-radius:5px}.progress-wrapper::-ms-fill-upper{background:#fff;border-radius:5px}.progress-wrapper::-ms-thumb{width:16px;height:16px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:0}span{display:inline-block}</style> {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} <style>nav-bar .nav-container{justify-content:flex-end}</style> {{else}} <style>nav-bar .nav-container{justify-content:space-between}</style> {{/if}} {{/if}} {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=nav-container id=navbar-control> {{#unless hideLogo}} <div class=logo-button title={{logoText}}> {{#if logoLink}} <a href={{logoLink}} target=_blank> <img src={{logoImage}}> </a> {{else}} <img src={{logoImage}}> {{/if}} </div> {{/unless}}{{#unless (or (not animations) hideAnimations)}} <div class=animation-control> <div class=types> <button class=\"flex-container animation-buttons\" id=types-button> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{selectedAnimationName}}</span> <span class=\"control-text animation-number\">{{selectedAnimation}}</span> {{#if (gt (count animations) 1)}} <span class=\"icon up-icon\"></span> {{/if}} </button> <div class=menu-options> {{#each animations}} {{#unless (eq ../selectedAnimation (add @index 1))}} <button class=\"flex-container animation-buttons\" id=label-option-button data-value={{this}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control id=progress-control> <button class=play-pause id=play-pause-button> {{#if paused}} <span class=\"icon play-icon\"></span> {{else}} <span class=\"icon pause-icon\"></span> {{/if}} </button> <input class=progress-wrapper id=progress-wrapper type=range min=0 max=100 step=0.01> </div> <div class=speed> <button class=flex-container id=speed-button> <span class=\"control-text speed-text\">{{selectedSpeed}}</span> <span class=\"icon up-icon\"></span> </button> <div class=menu-options> {{#eachInMap speedList}} {{#unless (eq ../selectedSpeed id)}} <button class=flex-container id=speed-option-button data-value={{value}}> <span class=\"control-text speed-text\">{{id}}</span> </button> {{/unless}} {{/eachInMap}} </div> </div> </div> {{/unless}} <div class=default-control> {{#unless hideHelp}} <button class=help id=help-button title=Help> <span class=\"icon help-icon\"></span> </button> {{/unless}} {{#unless hideFullScreen}} <button class=fullscreen id=fullscreen-button title=Fullscreen> <span class=\"icon fullscreen-icon\"></span> </button> {{/unless}} </div> </div>";
  111943. /***/ }),
  111944. /* 47 */
  111945. /***/ (function(module, exports) {
  111946. 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>";
  111947. /***/ }),
  111948. /* 48 */
  111949. /***/ (function(module, exports) {
  111950. module.exports = "SHARE";
  111951. /***/ }),
  111952. /* 49 */
  111953. /***/ (function(module, exports, __webpack_require__) {
  111954. "use strict";
  111955. Object.defineProperty(exports, "__esModule", { value: true });
  111956. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  111957. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  111958. var images = __webpack_require__(2);
  111959. /**
  111960. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  111961. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  111962. */
  111963. exports.defaultConfiguration = {
  111964. version: "3.2.0-alpha4",
  111965. templates: {
  111966. main: {
  111967. html: babylonjs_viewer_assets_1.defaultTemplate,
  111968. params: {
  111969. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  111970. noEscape: true
  111971. }
  111972. },
  111973. fillContainer: {
  111974. html: babylonjs_viewer_assets_1.fillContainer,
  111975. params: {
  111976. disable: false
  111977. }
  111978. },
  111979. loadingScreen: {
  111980. html: babylonjs_viewer_assets_1.loadingScreen,
  111981. params: {
  111982. backgroundColor: "#000000",
  111983. loadingImage: images.loading
  111984. }
  111985. },
  111986. viewer: {
  111987. html: babylonjs_viewer_assets_1.defaultViewer,
  111988. params: {
  111989. enableDragAndDrop: false
  111990. }
  111991. },
  111992. navBar: {
  111993. html: babylonjs_viewer_assets_1.navbar,
  111994. params: {
  111995. speedList: {
  111996. "0.5x": "0.5",
  111997. "1.0x": "1.0",
  111998. "1.5x": "1.5",
  111999. "2.0x": "2.0",
  112000. },
  112001. logoImage: images.babylonLogo,
  112002. logoText: 'BabylonJS',
  112003. logoLink: 'https://babylonjs.com',
  112004. hideHelp: true,
  112005. disableOnFullscreen: false,
  112006. },
  112007. events: {
  112008. pointerdown: {
  112009. 'navbar-control': true,
  112010. 'help-button': true
  112011. },
  112012. input: {
  112013. 'progress-wrapper': true
  112014. },
  112015. pointerup: {
  112016. 'progress-wrapper': true
  112017. }
  112018. }
  112019. },
  112020. overlay: {
  112021. html: babylonjs_viewer_assets_1.overlay,
  112022. params: {
  112023. closeImage: images.close,
  112024. closeText: 'Close'
  112025. }
  112026. },
  112027. help: {
  112028. html: babylonjs_viewer_assets_1.help
  112029. },
  112030. share: {
  112031. html: babylonjs_viewer_assets_1.share
  112032. },
  112033. error: {
  112034. html: babylonjs_viewer_assets_1.error
  112035. }
  112036. },
  112037. camera: {
  112038. behaviors: {
  112039. autoRotate: {
  112040. type: 0
  112041. },
  112042. framing: {
  112043. type: 2,
  112044. zoomOnBoundingInfo: true,
  112045. zoomStopsAnimation: false
  112046. },
  112047. bouncing: {
  112048. type: 1
  112049. }
  112050. },
  112051. wheelPrecision: 200,
  112052. },
  112053. skybox: {},
  112054. ground: {
  112055. receiveShadows: true
  112056. },
  112057. engine: {
  112058. antialiasing: true
  112059. },
  112060. scene: {}
  112061. };
  112062. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUUseUNBQWU7WUFDckIsTUFBTSxFQUFFO2dCQUNKLFdBQVcsRUFBRSxxQ0FBVztnQkFDeEIsUUFBUSxFQUFFLElBQUk7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0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FBQyxLQUFLO2dCQUN4QixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLDhCQUFJO1NBQ2I7UUFDRCxLQUFLLEVBQUU7WUFDSCxJQUFJLEVBQUUsK0JBQUs7U0FDZDtRQUNELEtBQUssRUFBRTtZQUNILElBQUksRUFBRSwrQkFBSztTQUNkO0tBRUo7SUFDRCxNQUFNLEVBQUU7UUFDSixTQUFTLEVBQUU7WUFDUCxVQUFVLEVBQUU7Z0JBQ1IsSUFBSSxFQUFFLENBQUM7YUFDVjtZQUNELE9BQU8sRUFBRTtnQkFDTCxJQUFJLEVBQUUsQ0FBQztnQkFDUCxrQkFBa0IsRUFBRSxJQUFJO2dCQUN4QixrQkFBa0IsRUFBRSxLQUFLO2FBQzVCO1lBQ0QsUUFBUSxFQUFFO2dCQUNOLElBQUksRUFBRSxDQUFDO2FBQ1Y7U0FDSjtRQUNELGNBQWMsRUFBRSxHQUFHO0tBQ3RCO0lBQ0QsTUFBTSxFQUFFLEVBQ1A7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0lBQ0QsS0FBSyxFQUFFLEVBQ047Q0FDSixDQUFBIn0=
  112063. /***/ }),
  112064. /* 50 */
  112065. /***/ (function(module, exports, __webpack_require__) {
  112066. "use strict";
  112067. Object.defineProperty(exports, "__esModule", { value: true });
  112068. var babylonjs_1 = __webpack_require__(0);
  112069. /**
  112070. * The viewer's "extended" configuration.
  112071. * This configuration defines specific obejcts and parameters that we think make any model look good.
  112072. */
  112073. exports.extendedConfiguration = {
  112074. version: "3.2.0",
  112075. extends: "default",
  112076. camera: {
  112077. exposure: 3.034578,
  112078. fov: 0.7853981633974483,
  112079. contrast: 1.6,
  112080. toneMappingEnabled: true,
  112081. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  112082. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  112083. behaviors: {
  112084. framing: {
  112085. type: 2,
  112086. mode: 0,
  112087. positionScale: 0.5,
  112088. defaultElevation: 0.2617993877991494,
  112089. elevationReturnWaitTime: 3000,
  112090. elevationReturnTime: 2000,
  112091. framingTime: 500,
  112092. zoomStopsAnimation: false,
  112093. radiusScale: 0.866
  112094. },
  112095. autoRotate: {
  112096. type: 0,
  112097. idleRotationWaitTime: 4000,
  112098. idleRotationSpeed: 0.17453292519943295,
  112099. idleRotationSpinupTime: 2500,
  112100. zoomStopsAnimation: false
  112101. },
  112102. bouncing: {
  112103. type: 1,
  112104. lowerRadiusTransitionRange: 0.05,
  112105. upperRadiusTransitionRange: -0.2
  112106. }
  112107. },
  112108. upperRadiusLimit: 5,
  112109. lowerRadiusLimit: 0.5,
  112110. frameOnModelLoad: true,
  112111. framingElevation: 0.2617993877991494,
  112112. framingRotation: 1.5707963267948966,
  112113. radius: 2,
  112114. alpha: 1.5708,
  112115. beta: Math.PI * 0.5 - 0.2618,
  112116. wheelPrecision: 300,
  112117. minZ: 0.1,
  112118. maxZ: 50,
  112119. fovMode: 0,
  112120. pinchPrecision: 1500,
  112121. panningSensibility: 3000
  112122. },
  112123. lights: {
  112124. light0: {
  112125. type: 0,
  112126. frustumEdgeFalloff: 0,
  112127. intensity: 7,
  112128. intensityMode: 0,
  112129. radius: 0.6,
  112130. range: 0.6,
  112131. spotAngle: 60,
  112132. diffuse: {
  112133. r: 1,
  112134. g: 1,
  112135. b: 1
  112136. },
  112137. position: {
  112138. x: -2,
  112139. y: 2.5,
  112140. z: 2
  112141. },
  112142. target: {
  112143. x: 0,
  112144. y: 0,
  112145. z: 0
  112146. },
  112147. enabled: true,
  112148. shadowEnabled: true,
  112149. shadowBufferSize: 512,
  112150. shadowMinZ: 1,
  112151. shadowMaxZ: 10,
  112152. shadowFieldOfView: 60,
  112153. shadowFrustumSize: 2,
  112154. shadowConfig: {
  112155. useBlurCloseExponentialShadowMap: true,
  112156. useKernelBlur: true,
  112157. blurScale: 1.0,
  112158. bias: 0.001,
  112159. depthScale: 50 * (10 - 1),
  112160. frustumEdgeFalloff: 0
  112161. }
  112162. },
  112163. light1: {
  112164. type: 0,
  112165. frustumEdgeFalloff: 0,
  112166. intensity: 7,
  112167. intensityMode: 0,
  112168. radius: 0.4,
  112169. range: 0.4,
  112170. spotAngle: 57,
  112171. diffuse: {
  112172. r: 1,
  112173. g: 1,
  112174. b: 1
  112175. },
  112176. position: {
  112177. x: 4,
  112178. y: 3,
  112179. z: -0.5
  112180. },
  112181. target: {
  112182. x: 0,
  112183. y: 0,
  112184. z: 0
  112185. },
  112186. enabled: true,
  112187. shadowEnabled: false,
  112188. shadowBufferSize: 512,
  112189. shadowMinZ: 0.2,
  112190. shadowMaxZ: 10,
  112191. shadowFieldOfView: 28,
  112192. shadowFrustumSize: 2
  112193. },
  112194. light2: {
  112195. type: 0,
  112196. frustumEdgeFalloff: 0,
  112197. intensity: 1,
  112198. intensityMode: 0,
  112199. radius: 0.5,
  112200. range: 0.5,
  112201. spotAngle: 42.85,
  112202. diffuse: {
  112203. r: 0.8,
  112204. g: 0.8,
  112205. b: 0.8
  112206. },
  112207. position: {
  112208. x: -1,
  112209. y: 3,
  112210. z: -3
  112211. },
  112212. target: {
  112213. x: 0,
  112214. y: 0,
  112215. z: 0
  112216. },
  112217. enabled: true,
  112218. shadowEnabled: false,
  112219. shadowBufferSize: 512,
  112220. shadowMinZ: 0.2,
  112221. shadowMaxZ: 10,
  112222. shadowFieldOfView: 45,
  112223. shadowFrustumSize: 2
  112224. }
  112225. },
  112226. ground: {
  112227. shadowLevel: 0.9,
  112228. texture: "Ground_2.0-1024.png",
  112229. material: {
  112230. primaryColorHighlightLevel: 0.035,
  112231. primaryColorShadowLevel: 0,
  112232. enableNoise: true,
  112233. useRGBColor: false,
  112234. maxSimultaneousLights: 1,
  112235. diffuseTexture: {
  112236. gammaSpace: true
  112237. }
  112238. },
  112239. opacity: 1,
  112240. mirror: false,
  112241. receiveShadows: true,
  112242. size: 5
  112243. },
  112244. skybox: {
  112245. scale: 11,
  112246. cubeTexture: {
  112247. url: "Skybox_2.0-256.dds"
  112248. },
  112249. material: {
  112250. primaryColorHighlightLevel: 0.03,
  112251. primaryColorShadowLevel: 0.03,
  112252. enableNoise: true,
  112253. useRGBColor: false,
  112254. reflectionTexture: {
  112255. gammaSpace: true
  112256. }
  112257. }
  112258. },
  112259. engine: {
  112260. renderInBackground: true
  112261. },
  112262. scene: {
  112263. flags: {
  112264. shadowsEnabled: true,
  112265. particlesEnabled: false,
  112266. collisionsEnabled: false,
  112267. lightsEnabled: true,
  112268. texturesEnabled: true,
  112269. lensFlaresEnabled: false,
  112270. proceduralTexturesEnabled: false,
  112271. renderTargetsEnabled: true,
  112272. spritesEnabled: false,
  112273. skeletonsEnabled: true,
  112274. audioEnabled: false,
  112275. },
  112276. defaultMaterial: {
  112277. materialType: 'pbr',
  112278. reflectivityColor: {
  112279. r: 0.1,
  112280. g: 0.1,
  112281. b: 0.1
  112282. },
  112283. microSurface: 0.6
  112284. },
  112285. clearColor: {
  112286. r: 0.9,
  112287. g: 0.9,
  112288. b: 0.9,
  112289. a: 1.0
  112290. },
  112291. imageProcessingConfiguration: {
  112292. vignetteCentreX: 0,
  112293. vignetteCentreY: 0,
  112294. vignetteColor: {
  112295. r: 0.086,
  112296. g: 0.184,
  112297. b: 0.259,
  112298. a: 1
  112299. },
  112300. vignetteWeight: 0.855,
  112301. vignetteStretch: 0.5,
  112302. vignetteBlendMode: 0,
  112303. vignetteCameraFov: 0.7853981633974483,
  112304. isEnabled: true,
  112305. colorCurves: {
  112306. shadowsHue: 0,
  112307. shadowsDensity: 0,
  112308. shadowsSaturation: 0,
  112309. shadowsExposure: 0,
  112310. midtonesHue: 0,
  112311. midtonesDensity: 0,
  112312. midtonesExposure: 0,
  112313. midtonesSaturation: 0,
  112314. highlightsHue: 0,
  112315. highlightsDensity: 0,
  112316. highlightsExposure: 0,
  112317. highlightsSaturation: 0
  112318. }
  112319. },
  112320. mainColor: {
  112321. r: 0.8823529411764706,
  112322. g: 0.8823529411764706,
  112323. b: 0.8823529411764706
  112324. }
  112325. },
  112326. loaderPlugins: {
  112327. extendedMaterial: true,
  112328. applyMaterialConfig: true,
  112329. msftLod: true,
  112330. telemetry: true
  112331. },
  112332. model: {
  112333. rotationOffsetAxis: {
  112334. x: 0,
  112335. y: -1,
  112336. z: 0
  112337. },
  112338. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  112339. material: {
  112340. directEnabled: true,
  112341. directIntensity: 0.884,
  112342. emissiveIntensity: 1.04,
  112343. environmentIntensity: 0.6
  112344. },
  112345. entryAnimation: {
  112346. scaling: {
  112347. x: 0,
  112348. y: 0,
  112349. z: 0
  112350. },
  112351. time: 0.5,
  112352. easingFunction: 4,
  112353. easingMode: 1
  112354. },
  112355. exitAnimation: {
  112356. scaling: {
  112357. x: 0,
  112358. y: 0,
  112359. z: 0
  112360. },
  112361. time: 0.5,
  112362. easingFunction: 4,
  112363. easingMode: 1
  112364. },
  112365. normalize: true,
  112366. castShadow: true,
  112367. receiveShadows: true
  112368. },
  112369. lab: {
  112370. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  112371. environmentMap: {
  112372. texture: "EnvMap_2.0-256.env",
  112373. rotationY: 3,
  112374. tintLevel: 0.4
  112375. },
  112376. defaultRenderingPipelines: {
  112377. bloomEnabled: true,
  112378. bloomThreshold: 1.0,
  112379. fxaaEnabled: true,
  112380. bloomWeight: 0.05
  112381. }
  112382. }
  112383. };
  112384. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQU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Q0FBQztnQkFDSixDQUFDLEVBQUUsQ0FBQzthQUNQO1lBQ0QsSUFBSSxFQUFFLEdBQUc7WUFDVCxjQUFjLEVBQUUsQ0FBQztZQUNqQixVQUFVLEVBQUUsQ0FBQztTQUNoQjtRQUNELFNBQVMsRUFBRSxJQUFJO1FBQ2YsVUFBVSxFQUFFLElBQUk7UUFDaEIsY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxHQUFHLEVBQUU7UUFDRCxhQUFhLEVBQUUsa0RBQWtEO1FBQ2pFLGNBQWMsRUFBRTtZQUNaLE9BQU8sRUFBRSxvQkFBb0I7WUFDN0IsU0FBUyxFQUFFLENBQUM7WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  112385. /***/ }),
  112386. /* 51 */
  112387. /***/ (function(module, exports, __webpack_require__) {
  112388. "use strict";
  112389. Object.defineProperty(exports, "__esModule", { value: true });
  112390. /**
  112391. * Defines a default directional shadow light for normalized objects (!)
  112392. */
  112393. exports.shadowDirectionalLightConfiguration = {
  112394. model: {
  112395. receiveShadows: true,
  112396. castShadow: true
  112397. },
  112398. ground: {
  112399. receiveShadows: true
  112400. },
  112401. lights: {
  112402. shadowDirectionalLight: {
  112403. type: 1,
  112404. shadowEnabled: true,
  112405. target: { x: 0, y: 0, z: 0.5 },
  112406. position: { x: 1.49, y: 2.39, z: -1.33 },
  112407. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  112408. intensity: 4.887,
  112409. intensityMode: 0,
  112410. shadowBufferSize: 1024,
  112411. shadowFrustumSize: 6.0,
  112412. shadowFieldOfView: 50.977,
  112413. shadowMinZ: 0.1,
  112414. shadowMaxZ: 10.0,
  112415. shadowConfig: {
  112416. blurKernel: 32,
  112417. useBlurCloseExponentialShadowMap: true
  112418. }
  112419. }
  112420. }
  112421. };
  112422. /**
  112423. * Defines a default shadow-enabled spot light for normalized objects.
  112424. */
  112425. exports.shadowSpotlLightConfiguration = {
  112426. model: {
  112427. receiveShadows: true,
  112428. castShadow: true
  112429. },
  112430. ground: {
  112431. receiveShadows: true
  112432. },
  112433. lights: {
  112434. shadowSpotLight: {
  112435. type: 2,
  112436. intensity: 2,
  112437. shadowEnabled: true,
  112438. target: { x: 0, y: 0, z: 0.5 },
  112439. position: { x: 0, y: 3.5, z: 3.7 },
  112440. angle: 1,
  112441. shadowOrthoScale: 0.5,
  112442. shadowBufferSize: 1024,
  112443. shadowMinZ: 0.1,
  112444. shadowMaxZ: 50.0,
  112445. shadowConfig: {
  112446. frustumEdgeFalloff: 0.5,
  112447. blurKernel: 32,
  112448. useBlurExponentialShadowMap: true
  112449. }
  112450. }
  112451. }
  112452. };
  112453. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQU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QUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsR0FBRyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDbEMsS0FBSyxFQUFFLENBQUM7WUFDUixnQkFBZ0IsRUFBRSxHQUFHO1lBQ3JCLGdCQUFnQixFQUFFLElBQUk7WUFDdEIsVUFBVSxFQUFFLEdBQUc7WUFDZixVQUFVLEVBQUUsSUFBSTtZQUNoQixZQUFZLEVBQUU7Z0JBQ1Ysa0JBQWtCLEVBQUUsR0FBRztnQkFDdkIsVUFBVSxFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0=
  112454. /***/ }),
  112455. /* 52 */
  112456. /***/ (function(module, exports, __webpack_require__) {
  112457. "use strict";
  112458. Object.defineProperty(exports, "__esModule", { value: true });
  112459. /**
  112460. * Lab-oriented default .env support
  112461. */
  112462. exports.environmentMapConfiguration = {
  112463. lab: {
  112464. assetsRootURL: '/assets/environment/',
  112465. environmentMap: {
  112466. texture: 'EnvMap_2.0-256.env',
  112467. rotationY: 0,
  112468. tintLevel: 0.4
  112469. }
  112470. }
  112471. };
  112472. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  112473. /***/ }),
  112474. /* 53 */
  112475. /***/ (function(module, exports, __webpack_require__) {
  112476. "use strict";
  112477. Object.defineProperty(exports, "__esModule", { value: true });
  112478. var configuration_1 = __webpack_require__(11);
  112479. /**
  112480. * This function will make sure the configuration file is taking deprecated fields into account
  112481. * and is setting them to the correct keys and values.
  112482. *
  112483. * @param configuration The configuration to process. Mutable!
  112484. */
  112485. function processConfigurationCompatibility(configuration) {
  112486. if (configuration.camera) {
  112487. // camera contrast -> image processing contrast
  112488. if (configuration.camera.contrast !== undefined) {
  112489. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  112490. }
  112491. // camera exposure -> image processing exposure
  112492. if (configuration.camera.exposure !== undefined) {
  112493. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  112494. }
  112495. }
  112496. if (configuration.scene) {
  112497. //glow
  112498. if (configuration.scene.glow) {
  112499. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  112500. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  112501. if (enabledProcessing !== false) {
  112502. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  112503. }
  112504. }
  112505. }
  112506. }
  112507. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  112508. function setKeyInObject(object, keys, value, shouldOverwrite) {
  112509. var keySplit = keys.split(".");
  112510. if (keySplit.length === 0)
  112511. return;
  112512. var lastKey = keySplit.pop();
  112513. if (!lastKey)
  112514. return;
  112515. var curObj = object;
  112516. keySplit.forEach(function (key) {
  112517. curObj[key] = curObj[key] || {};
  112518. curObj = curObj[key];
  112519. });
  112520. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  112521. return;
  112522. curObj[lastKey] = value;
  112523. }
  112524. //# sourceMappingURL=data:application/json;base64,eyJ2Z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xDQUFDLENBQUM7YUFDdkY7U0FDSjtLQUNKO0FBQ0wsQ0FBQztBQTFCRCw4RUEwQkM7QUFFRCx3QkFBd0IsTUFBVyxFQUFFLElBQVksRUFBRSxLQUFVLEVBQUUsZUFBeUI7SUFDcEYsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUMvQixJQUFJLFFBQVEsQ0FBQyxNQUFNLEtBQUssQ0FBQztRQUFFLE9BQU87SUFDbEMsSUFBSSxPQUFPLEdBQUcsUUFBUSxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBQzdCLElBQUksQ0FBQyxPQUFPO1FBQUUsT0FBTztJQUNyQixJQUFJLE1BQU0sR0FBRyxNQUFNLENBQUM7SUFDcEIsUUFBUSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  112525. /***/ }),
  112526. /* 54 */
  112527. /***/ (function(module, exports, __webpack_require__) {
  112528. "use strict";
  112529. Object.defineProperty(exports, "__esModule", { value: true });
  112530. var telemetryLoaderPlugin_1 = __webpack_require__(55);
  112531. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  112532. var msftLodLoaderPlugin_1 = __webpack_require__(56);
  112533. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  112534. var applyMaterialConfig_1 = __webpack_require__(57);
  112535. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  112536. var extendedMaterialLoaderPlugin_1 = __webpack_require__(58);
  112537. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  112538. var babylonjs_1 = __webpack_require__(0);
  112539. var pluginCache = {};
  112540. /**
  112541. * Get a loader plugin according to its name.
  112542. * The plugin will be cached and will be reused if called for again.
  112543. *
  112544. * @param name the name of the plugin
  112545. */
  112546. function getLoaderPluginByName(name) {
  112547. if (!pluginCache[name]) {
  112548. switch (name) {
  112549. case 'telemetry':
  112550. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  112551. break;
  112552. case 'msftLod':
  112553. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  112554. break;
  112555. case 'applyMaterialConfig':
  112556. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  112557. break;
  112558. case 'extendedMaterial':
  112559. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  112560. break;
  112561. }
  112562. }
  112563. return pluginCache[name];
  112564. }
  112565. exports.getLoaderPluginByName = getLoaderPluginByName;
  112566. /**
  112567. *
  112568. */
  112569. function addLoaderPlugin(name, plugin) {
  112570. if (pluginCache[name]) {
  112571. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  112572. }
  112573. pluginCache[name] = plugin;
  112574. }
  112575. exports.addLoaderPlugin = addLoaderPlugin;
  112576. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs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DBDQUEwQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  112577. /***/ }),
  112578. /* 55 */
  112579. /***/ (function(module, exports, __webpack_require__) {
  112580. "use strict";
  112581. Object.defineProperty(exports, "__esModule", { value: true });
  112582. var telemetryManager_1 = __webpack_require__(6);
  112583. var babylonjs_1 = __webpack_require__(0);
  112584. var TelemetryLoaderPlugin = /** @class */ (function () {
  112585. function TelemetryLoaderPlugin() {
  112586. }
  112587. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  112588. this._model = model;
  112589. this._loadStart = babylonjs_1.Tools.Now;
  112590. };
  112591. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  112592. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  112593. model: model,
  112594. loadTime: babylonjs_1.Tools.Now - this._loadStart
  112595. });
  112596. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  112597. };
  112598. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  112599. this._loadEnd = babylonjs_1.Tools.Now;
  112600. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  112601. model: this._model,
  112602. loadTime: this._loadEnd - this._loadStart
  112603. });
  112604. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  112605. };
  112606. TelemetryLoaderPlugin.prototype.onComplete = function () {
  112607. this._loadEnd = babylonjs_1.Tools.Now;
  112608. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  112609. model: this._model,
  112610. loadTime: this._loadEnd - this._loadStart
  112611. });
  112612. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  112613. };
  112614. return TelemetryLoaderPlugin;
  112615.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QUFDLFlBQVksRUFBRSxJQUFJLENBQUMsTUFBTSxDQUFDLFdBQVcsRUFBRSxFQUFFO1lBQ2hFLEtBQUssRUFBRSxJQUFJLENBQUMsTUFBTTtZQUNsQixRQUFRLEVBQUUsSUFBSSxDQUFDLFFBQVEsR0FBRyxJQUFJLENBQUMsVUFBVTtTQUM1QyxDQUFDLENBQUM7UUFFSCxtQ0FBZ0IsQ0FBQyxnQkFBZ0IsQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxTQUFTLEVBQUUsRUFBRSxJQUFJLENBQUMsTUFBTSxDQUFDLFdBQVcsRUFBRSxDQUFDLENBQUM7SUFDbkcsQ0FBQztJQUVNLDBDQUFVLEdBQWpCO1FBQ0ksSUFBSSxDQUFDLFFBQVEsR0FBRyxpQkFBSyxDQUFDLEdBQUcsQ0FBQztRQUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  112618. /***/ }),
  112619. /* 56 */
  112620. /***/ (function(module, exports, __webpack_require__) {
  112621. "use strict";
  112622. Object.defineProperty(exports, "__esModule", { value: true });
  112623. /**
  112624. * A loder plugin to use MSFT_lod extension correctly (glTF)
  112625. */
  112626. var MSFTLodLoaderPlugin = /** @class */ (function () {
  112627. function MSFTLodLoaderPlugin() {
  112628. }
  112629. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  112630. this._model = model;
  112631. };
  112632. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  112633. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  112634. var MSFT_lod = extension;
  112635. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  112636. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  112637. }
  112638. };
  112639. return MSFTLodLoaderPlugin;
  112640. }());
  112641. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  112642. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  112643. /***/ }),
  112644. /* 57 */
  112645. /***/ (function(module, exports, __webpack_require__) {
  112646. "use strict";
  112647. Object.defineProperty(exports, "__esModule", { value: true });
  112648. /**
  112649. * Force-apply material configuration right after a material was loaded.
  112650. */
  112651. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  112652. function ApplyMaterialConfigPlugin() {
  112653. }
  112654. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  112655. this._model = model;
  112656. };
  112657. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  112658. this._model && this._model._applyModelMaterialConfiguration(material);
  112659. };
  112660. return ApplyMaterialConfigPlugin;
  112661. }());
  112662. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  112663. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  112664. /***/ }),
  112665. /* 58 */
  112666. /***/ (function(module, exports, __webpack_require__) {
  112667. "use strict";
  112668. Object.defineProperty(exports, "__esModule", { value: true });
  112669. var babylonjs_1 = __webpack_require__(0);
  112670. /**
  112671. * A (PBR) material will be extended using this function.
  112672. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  112673. */
  112674. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  112675. function ExtendedMaterialLoaderPlugin() {
  112676. }
  112677. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  112678. var material = baseMaterial;
  112679. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  112680. };
  112681. return ExtendedMaterialLoaderPlugin;
  112682. }());
  112683. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  112684. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsdUNBQTRJO0FBRTVJOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  112685. /***/ }),
  112686. /* 59 */
  112687. /***/ (function(module, exports, __webpack_require__) {
  112688. "use strict";
  112689. Object.defineProperty(exports, "__esModule", { value: true });
  112690. var babylonjs_1 = __webpack_require__(0);
  112691. var ObservablesManager = /** @class */ (function () {
  112692. function ObservablesManager() {
  112693. this.onSceneInitObservable = new babylonjs_1.Observable();
  112694. this.onEngineInitObservable = new babylonjs_1.Observable();
  112695. this.onModelLoadedObservable = new babylonjs_1.Observable();
  112696. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  112697. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  112698. this.onModelAddedObservable = new babylonjs_1.Observable();
  112699. this.onModelRemovedObservable = new babylonjs_1.Observable();
  112700. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  112701. this.onLoaderInitObservable = new babylonjs_1.Observable();
  112702. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  112703. }
  112704. ObservablesManager.prototype.dispose = function () {
  112705. this.onSceneInitObservable.clear();
  112706. this.onEngineInitObservable.clear();
  112707. this.onModelLoadedObservable.clear();
  112708. this.onModelLoadProgressObservable.clear();
  112709. this.onModelLoadErrorObservable.clear();
  112710. this.onModelAddedObservable.clear();
  112711. this.onModelRemovedObservable.clear();
  112712. this.onViewerInitDoneObservable.clear();
  112713. this.onLoaderInitObservable.clear();
  112714. this.onFrameRenderedObservable.clear();
  112715. };
  112716. return ObservablesManager;
  112717. }());
  112718. exports.ObservablesManager = ObservablesManager;
  112719. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdC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BQUUsQ0FBQztRQUMzQyxJQUFJLENBQUMsMEJBQTBCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUN0QyxJQUFJLENBQUMsMEJBQTBCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBRUwseUJBQUM7QUFBRCxDQUFDLEFBekVELElBeUVDO0FBekVZLGdEQUFrQiJ9
  112720. /***/ }),
  112721. /* 60 */
  112722. /***/ (function(module, exports, __webpack_require__) {
  112723. "use strict";
  112724. Object.defineProperty(exports, "__esModule", { value: true });
  112725. var babylonjs_1 = __webpack_require__(0);
  112726. var ConfigurationContainer = /** @class */ (function () {
  112727. function ConfigurationContainer() {
  112728. this.mainColor = babylonjs_1.Color3.White();
  112729. this.reflectionColor = babylonjs_1.Color3.White();
  112730. }
  112731. return ConfigurationContainer;
  112732. }());
  112733. exports.ConfigurationContainer = ConfigurationContainer;
  112734. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUNwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBUkQsSUFRQztBQVJZLHdEQUFzQiJ9
  112735. /***/ }),
  112736. /* 61 */
  112737. /***/ (function(module, exports, __webpack_require__) {
  112738. "use strict";
  112739. Object.defineProperty(exports, "__esModule", { value: true });
  112740. var babylonjs_1 = __webpack_require__(0);
  112741. var helper_1 = __webpack_require__(1);
  112742. var Handlebars = __webpack_require__(62);
  112743. var eventManager_1 = __webpack_require__(63);
  112744. var _1 = __webpack_require__(1);
  112745. /**
  112746. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  112747. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  112748. */
  112749. var TemplateManager = /** @class */ (function () {
  112750. function TemplateManager(containerElement) {
  112751. this.containerElement = containerElement;
  112752. this.templates = {};
  112753. this.onTemplateInit = new babylonjs_1.Observable();
  112754. this.onTemplateLoaded = new babylonjs_1.Observable();
  112755. this.onTemplateStateChange = new babylonjs_1.Observable();
  112756. this.onAllLoaded = new babylonjs_1.Observable();
  112757. this.onEventTriggered = new babylonjs_1.Observable();
  112758. this.eventManager = new eventManager_1.EventManager(this);
  112759. }
  112760. /**
  112761. * Initialize the template(s) for the viewer. Called bay the Viewer class
  112762. * @param templates the templates to be used to initialize the main template
  112763. */
  112764. TemplateManager.prototype.initTemplate = function (templates) {
  112765. var _this = this;
  112766. var internalInit = function (dependencyMap, name, parentTemplate) {
  112767. //init template
  112768. var template = _this.templates[name];
  112769. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  112770. return internalInit(dependencyMap[childName], childName, template);
  112771. });
  112772. // register the observers
  112773. //template.onLoaded.add(() => {
  112774. var addToParent = function () {
  112775. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  112776. template.appendTo(containingElement);
  112777. _this._checkLoadedState();
  112778. };
  112779. if (parentTemplate && !parentTemplate.parent) {
  112780. parentTemplate.onAppended.add(function () {
  112781. addToParent();
  112782. });
  112783. }
  112784. else {
  112785. addToParent();
  112786. }
  112787. //});
  112788. return template;
  112789. };
  112790. //build the html tree
  112791. return this._buildHTMLTree(templates).then(function (htmlTree) {
  112792. if (_this.templates['main']) {
  112793. internalInit(htmlTree, 'main');
  112794. }
  112795. else {
  112796. _this._checkLoadedState();
  112797. }
  112798. return;
  112799. });
  112800. };
  112801. /**
  112802. *
  112803. * This function will create a simple map with child-dependencies of the template html tree.
  112804. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  112805. * It is expected that the main template will be called main!
  112806. *
  112807. * @param templates
  112808. */
  112809. TemplateManager.prototype._buildHTMLTree = function (templates) {
  112810. var _this = this;
  112811. var promises = Object.keys(templates).map(function (name) {
  112812. // if the template was overridden
  112813. if (!templates[name])
  112814. return Promise.resolve(false);
  112815. // else - we have a template, let's do our job!
  112816. var template = new Template(name, templates[name]);
  112817. template.onLoaded.add(function () {
  112818. _this.onTemplateLoaded.notifyObservers(template);
  112819. });
  112820. template.onStateChange.add(function () {
  112821. _this.onTemplateStateChange.notifyObservers(template);
  112822. });
  112823. _this.onTemplateInit.notifyObservers(template);
  112824. // make sure the global onEventTriggered is called as well
  112825. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  112826. _this.templates[name] = template;
  112827. return template.initPromise;
  112828. });
  112829. return Promise.all(promises).then(function () {
  112830. var templateStructure = {};
  112831. // now iterate through all templates and check for children:
  112832. var buildTree = function (parentObject, name) {
  112833. _this.templates[name].isInHtmlTree = true;
  112834. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  112835. childNodes.forEach(function (element) {
  112836. parentObject[element] = {};
  112837. buildTree(parentObject[element], element);
  112838. });
  112839. };
  112840. if (_this.templates['main']) {
  112841. buildTree(templateStructure, "main");
  112842. }
  112843. return templateStructure;
  112844. });
  112845. };
  112846. /**
  112847. * Get the canvas in the template tree.
  112848. * There must be one and only one canvas inthe template.
  112849. */
  112850. TemplateManager.prototype.getCanvas = function () {
  112851. return this.containerElement.querySelector('canvas');
  112852. };
  112853. /**
  112854. * Get a specific template from the template tree
  112855. * @param name the name of the template to load
  112856. */
  112857. TemplateManager.prototype.getTemplate = function (name) {
  112858. return this.templates[name];
  112859. };
  112860. TemplateManager.prototype._checkLoadedState = function () {
  112861. var _this = this;
  112862. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  112863. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  112864. });
  112865. if (done) {
  112866. this.onAllLoaded.notifyObservers(this);
  112867. }
  112868. };
  112869. /**
  112870. * Dispose the template manager
  112871. */
  112872. TemplateManager.prototype.dispose = function () {
  112873. var _this = this;
  112874. // dispose all templates
  112875. Object.keys(this.templates).forEach(function (template) {
  112876. _this.templates[template].dispose();
  112877. });
  112878. this.templates = {};
  112879. this.eventManager.dispose();
  112880. this.onTemplateInit.clear();
  112881. this.onAllLoaded.clear();
  112882. this.onEventTriggered.clear();
  112883. this.onTemplateLoaded.clear();
  112884. this.onTemplateStateChange.clear();
  112885. };
  112886. return TemplateManager;
  112887. }());
  112888. exports.TemplateManager = TemplateManager;
  112889. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  112890. Handlebars.registerHelper('eachInMap', function (map, block) {
  112891. var out = '';
  112892. Object.keys(map).map(function (prop) {
  112893. var data = map[prop];
  112894. if (typeof data === 'object') {
  112895. data.id = data.id || prop;
  112896. out += block.fn(data);
  112897. }
  112898. else {
  112899. out += block.fn({ id: prop, value: data });
  112900. }
  112901. });
  112902. return out;
  112903. });
  112904. Handlebars.registerHelper('add', function (a, b) {
  112905. var out = a + b;
  112906. return out;
  112907. });
  112908. Handlebars.registerHelper('eq', function (a, b) {
  112909. var out = (a == b);
  112910. return out;
  112911. });
  112912. Handlebars.registerHelper('or', function (a, b) {
  112913. var out = a || b;
  112914. return out;
  112915. });
  112916. Handlebars.registerHelper('not', function (a) {
  112917. var out = !a;
  112918. return out;
  112919. });
  112920. Handlebars.registerHelper('count', function (map) {
  112921. return map.length;
  112922. });
  112923. Handlebars.registerHelper('gt', function (a, b) {
  112924. var out = a > b;
  112925. return out;
  112926. });
  112927. /**
  112928. * This class represents a single template in the viewer's template tree.
  112929. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  112930. * A template is injected using the template manager in the correct position.
  112931. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  112932. *
  112933. * For further information please refer to the documentation page, https://doc.babylonjs.com
  112934. */
  112935. var Template = /** @class */ (function () {
  112936. function Template(name, _configuration) {
  112937. var _this = this;
  112938. this.name = name;
  112939. this._configuration = _configuration;
  112940. this.onLoaded = new babylonjs_1.Observable();
  112941. this.onAppended = new babylonjs_1.Observable();
  112942. this.onStateChange = new babylonjs_1.Observable();
  112943. this.onEventTriggered = new babylonjs_1.Observable();
  112944. this.loadRequests = [];
  112945. this.isLoaded = false;
  112946. this.isShown = false;
  112947. this.isInHtmlTree = false;
  112948. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  112949. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  112950. if (htmlTemplate) {
  112951. _this._htmlTemplate = htmlTemplate;
  112952. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  112953. var config = _this._configuration.params || {};
  112954. _this._rawHtml = compiledTemplate(config);
  112955. try {
  112956. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  112957. }
  112958. catch (e) {
  112959. var test = document.createElement(_this.name);
  112960. test.innerHTML = _this._rawHtml;
  112961. _this._fragment = test;
  112962. }
  112963. _this.isLoaded = true;
  112964. _this.isShown = true;
  112965. _this.onLoaded.notifyObservers(_this);
  112966. }
  112967. return _this;
  112968. });
  112969. }
  112970. /**
  112971. * Some templates have parameters (like background color for example).
  112972. * The parameters are provided to Handlebars which in turn generates the template.
  112973. * This function will update the template with the new parameters
  112974. *
  112975. * Note that when updating parameters the events will be registered again (after being cleared).
  112976. *
  112977. * @param params the new template parameters
  112978. */
  112979. Template.prototype.updateParams = function (params, append) {
  112980. if (append === void 0) { append = true; }
  112981. if (append) {
  112982. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  112983. }
  112984. else {
  112985. this._configuration.params = params;
  112986. }
  112987. // update the template
  112988. if (this.isLoaded) {
  112989. // this.dispose();
  112990. }
  112991. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  112992. var config = this._configuration.params || {};
  112993. this._rawHtml = compiledTemplate(config);
  112994. try {
  112995. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  112996. }
  112997. catch (e) {
  112998. var test = document.createElement(this.name);
  112999. test.innerHTML = this._rawHtml;
  113000. this._fragment = test;
  113001. }
  113002. if (this.parent) {
  113003. this.appendTo(this.parent, true);
  113004. }
  113005. };
  113006. Object.defineProperty(Template.prototype, "configuration", {
  113007. /**
  113008. * Get the template'S configuration
  113009. */
  113010. get: function () {
  113011. return this._configuration;
  113012. },
  113013. enumerable: true,
  113014. configurable: true
  113015. });
  113016. /**
  113017. * A template can be a parent element for other templates or HTML elements.
  113018. * This function will deliver all child HTML elements of this template.
  113019. */
  113020. Template.prototype.getChildElements = function () {
  113021. var childrenArray = [];
  113022. //Edge and IE don't support frage,ent.children
  113023. var children = this._fragment && this._fragment.children;
  113024. if (!this._fragment) {
  113025. var fragment = this.parent.querySelector(this.name);
  113026. if (fragment) {
  113027. children = fragment.querySelectorAll('*');
  113028. }
  113029. }
  113030. if (!children) {
  113031. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  113032. children = this._fragment.querySelectorAll('*');
  113033. }
  113034. for (var i = 0; i < children.length; ++i) {
  113035. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  113036. }
  113037. return childrenArray;
  113038. };
  113039. /**
  113040. * Appending the template to a parent HTML element.
  113041. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  113042. * @param parent the parent to which the template is added
  113043. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  113044. */
  113045. Template.prototype.appendTo = function (parent, forceRemove) {
  113046. var _this = this;
  113047. if (this.parent) {
  113048. if (forceRemove && this._addedFragment) {
  113049. /*let fragement = this.parent.querySelector(this.name)
  113050. if (fragement)
  113051. this.parent.removeChild(fragement);*/
  113052. this.parent.innerHTML = '';
  113053. }
  113054. else {
  113055. return;
  113056. }
  113057. }
  113058. this.parent = parent;
  113059. if (this._configuration.id) {
  113060. this.parent.id = this._configuration.id;
  113061. }
  113062. if (this._fragment) {
  113063. this.parent.appendChild(this._fragment);
  113064. this._addedFragment = this._fragment;
  113065. }
  113066. else {
  113067. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  113068. }
  113069. // appended only one frame after.
  113070. setTimeout(function () {
  113071. _this._registerEvents();
  113072. _this.onAppended.notifyObservers(_this);
  113073. });
  113074. };
  113075. /**
  113076. * Show the template using the provided visibilityFunction, or natively using display: flex.
  113077. * The provided function returns a promise that should be fullfilled when the element is shown.
  113078. * Since it is a promise async operations are more than possible.
  113079. * See the default viewer for an opacity example.
  113080. * @param visibilityFunction The function to execute to show the template.
  113081. */
  113082. Template.prototype.show = function (visibilityFunction) {
  113083. var _this = this;
  113084. if (this._isHiding)
  113085. return Promise.resolve(this);
  113086. return Promise.resolve().then(function () {
  113087. _this._isShowing = true;
  113088. if (visibilityFunction) {
  113089. return visibilityFunction(_this);
  113090. }
  113091. else {
  113092. // flex? box? should this be configurable easier than the visibilityFunction?
  113093. _this.parent.style.display = 'flex';
  113094. // support old browsers with no flex:
  113095. if (_this.parent.style.display !== 'flex') {
  113096. _this.parent.style.display = '';
  113097. }
  113098. return _this;
  113099. }
  113100. }).then(function () {
  113101. _this.isShown = true;
  113102. _this._isShowing = false;
  113103. _this.onStateChange.notifyObservers(_this);
  113104. return _this;
  113105. });
  113106. };
  113107. /**
  113108. * Hide the template using the provided visibilityFunction, or natively using display: none.
  113109. * The provided function returns a promise that should be fullfilled when the element is hidden.
  113110. * Since it is a promise async operations are more than possible.
  113111. * See the default viewer for an opacity example.
  113112. * @param visibilityFunction The function to execute to show the template.
  113113. */
  113114. Template.prototype.hide = function (visibilityFunction) {
  113115. var _this = this;
  113116. if (this._isShowing)
  113117. return Promise.resolve(this);
  113118. return Promise.resolve().then(function () {
  113119. _this._isHiding = true;
  113120. if (visibilityFunction) {
  113121. return visibilityFunction(_this);
  113122. }
  113123. else {
  113124. // flex? box? should this be configurable easier than the visibilityFunction?
  113125. _this.parent.style.display = 'none';
  113126. return _this;
  113127. }
  113128. }).then(function () {
  113129. _this.isShown = false;
  113130. _this._isHiding = false;
  113131. _this.onStateChange.notifyObservers(_this);
  113132. return _this;
  113133. });
  113134. };
  113135. /**
  113136. * Dispose this template
  113137. */
  113138. Template.prototype.dispose = function () {
  113139. this.onAppended.clear();
  113140. this.onEventTriggered.clear();
  113141. this.onLoaded.clear();
  113142. this.onStateChange.clear();
  113143. this.isLoaded = false;
  113144. // remove from parent
  113145. try {
  113146. this.parent.removeChild(this._fragment);
  113147. }
  113148. catch (e) {
  113149. //noop
  113150. }
  113151. this.loadRequests.forEach(function (request) {
  113152. request.abort();
  113153. });
  113154. if (this._registeredEvents) {
  113155. this._registeredEvents.forEach(function (evt) {
  113156. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  113157. });
  113158. }
  113159. delete this._fragment;
  113160. };
  113161. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  113162. var _this = this;
  113163. if (!templateConfig) {
  113164. return Promise.reject('No templateConfig provided');
  113165. }
  113166. else if (templateConfig.html !== undefined) {
  113167. return Promise.resolve(templateConfig.html);
  113168. }
  113169. else {
  113170. var location_1 = this._getTemplateLocation(templateConfig);
  113171. if (helper_1.isUrl(location_1)) {
  113172. return new Promise(function (resolve, reject) {
  113173. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  113174. resolve(data);
  113175. }, undefined, undefined, false, function (request, error) {
  113176. reject(error);
  113177. });
  113178. _this.loadRequests.push(fileRequest);
  113179. });
  113180. }
  113181. else {
  113182. location_1 = location_1.replace('#', '');
  113183. var element = document.getElementById(location_1);
  113184. if (element) {
  113185. return Promise.resolve(element.innerHTML);
  113186. }
  113187. else {
  113188. return Promise.reject('Template ID not found');
  113189. }
  113190. }
  113191. }
  113192. };
  113193. Template.prototype._registerEvents = function () {
  113194. var _this = this;
  113195. this._registeredEvents = this._registeredEvents || [];
  113196. if (this._registeredEvents.length) {
  113197. // first remove the registered events
  113198. this._registeredEvents.forEach(function (evt) {
  113199. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  113200. });
  113201. }
  113202. if (this._configuration.events) {
  113203. var _loop_1 = function (eventName) {
  113204. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  113205. var functionToFire_1 = function (selector, event) {
  113206. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  113207. };
  113208. // if boolean, set the parent as the event listener
  113209. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  113210. var selector = this_1.parent.id;
  113211. if (selector) {
  113212. selector = '#' + selector;
  113213. }
  113214. else {
  113215. selector = this_1.parent.tagName;
  113216. }
  113217. var binding = functionToFire_1.bind(this_1, selector);
  113218. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  113219. this_1._registeredEvents.push({
  113220. htmlElement: this_1.parent,
  113221. eventName: eventName,
  113222. function: binding
  113223. });
  113224. }
  113225. else if (typeof this_1._configuration.events[eventName] === 'object') {
  113226. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  113227. // strict null checl is working incorrectly, must override:
  113228. var event_1 = this_1._configuration.events[eventName] || {};
  113229. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  113230. if (selector && selector.indexOf('#') !== 0) {
  113231. selector = '#' + selector;
  113232. }
  113233. var htmlElement = _this.parent.querySelector(selector);
  113234. if (htmlElement) {
  113235. var binding = functionToFire_1.bind(_this, selector);
  113236. htmlElement.addEventListener(eventName, binding, false);
  113237. _this._registeredEvents.push({
  113238. htmlElement: htmlElement,
  113239. eventName: eventName,
  113240. function: binding
  113241. });
  113242. }
  113243. });
  113244. }
  113245. }
  113246. };
  113247. var this_1 = this;
  113248. for (var eventName in this._configuration.events) {
  113249. _loop_1(eventName);
  113250. }
  113251. }
  113252. };
  113253. Template.prototype._getTemplateLocation = function (templateConfig) {
  113254. if (!templateConfig || typeof templateConfig === 'string') {
  113255. return templateConfig;
  113256. }
  113257. else {
  113258. return templateConfig.location;
  113259. }
  113260. };
  113261. return Template;
  113262. }());
  113263. exports.Template = Template;
  113264. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJLENBQUMscUJBQXFCLEdBQUcsSUFBSSxzQkFBVSxFQUFZLENBQUM7UUFDeEQsSUFBSSxDQUFDLFdBQVcsR0FBR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sSUFBSSxPQUFPLGNBQWMsS0FBSyxRQUFRLEVBQUU7WUFDdkQsT0FBTyxjQUFjLENBQUM7U0FDekI7YUFBTTtZQUNILE9BQU8sY0FBYyxDQUFDLFFBQVEsQ0FBQztTQUNsQztJQUNMLENBQUM7SUFDTCxlQUFDO0FBQUQsQ0FBQyxBQS9XRCxJQStXQztBQS9XWSw0QkFBUSJ9
  113265. /***/ }),
  113266. /* 62 */
  113267. /***/ (function(module, exports, __webpack_require__) {
  113268. /**!
  113269. @license
  113270. handlebars v4.0.11
  113271. Copyright (C) 2011-2017 by Yehuda Katz
  113272. Permission is hereby granted, free of charge, to any person obtaining a copy
  113273. of this software and associated documentation files (the "Software"), to deal
  113274. in the Software without restriction, including without limitation the rights
  113275. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  113276. copies of the Software, and to permit persons to whom the Software is
  113277. furnished to do so, subject to the following conditions:
  113278. The above copyright notice and this permission notice shall be included in
  113279. all copies or substantial portions of the Software.
  113280. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  113281. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  113282. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  113283. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  113284. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  113285. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  113286. THE SOFTWARE.
  113287. */
  113288. (function webpackUniversalModuleDefinition(root, factory) {
  113289. if(true)
  113290. module.exports = factory();
  113291. else if(typeof define === 'function' && define.amd)
  113292. define([], factory);
  113293. else if(typeof exports === 'object')
  113294. exports["Handlebars"] = factory();
  113295. else
  113296. root["Handlebars"] = factory();
  113297. })(this, function() {
  113298. return /******/ (function(modules) { // webpackBootstrap
  113299. /******/ // The module cache
  113300. /******/ var installedModules = {};
  113301. /******/ // The require function
  113302. /******/ function __webpack_require__(moduleId) {
  113303. /******/ // Check if module is in cache
  113304. /******/ if(installedModules[moduleId])
  113305. /******/ return installedModules[moduleId].exports;
  113306. /******/ // Create a new module (and put it into the cache)
  113307. /******/ var module = installedModules[moduleId] = {
  113308. /******/ exports: {},
  113309. /******/ id: moduleId,
  113310. /******/ loaded: false
  113311. /******/ };
  113312. /******/ // Execute the module function
  113313. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  113314. /******/ // Flag the module as loaded
  113315. /******/ module.loaded = true;
  113316. /******/ // Return the exports of the module
  113317. /******/ return module.exports;
  113318. /******/ }
  113319. /******/ // expose the modules object (__webpack_modules__)
  113320. /******/ __webpack_require__.m = modules;
  113321. /******/ // expose the module cache
  113322. /******/ __webpack_require__.c = installedModules;
  113323. /******/ // __webpack_public_path__
  113324. /******/ __webpack_require__.p = "";
  113325. /******/ // Load entry module and return exports
  113326. /******/ return __webpack_require__(0);
  113327. /******/ })
  113328. /************************************************************************/
  113329. /******/ ([
  113330. /* 0 */
  113331. /***/ (function(module, exports, __webpack_require__) {
  113332. 'use strict';
  113333. var _interopRequireDefault = __webpack_require__(1)['default'];
  113334. exports.__esModule = true;
  113335. var _handlebarsRuntime = __webpack_require__(2);
  113336. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  113337. // Compiler imports
  113338. var _handlebarsCompilerAst = __webpack_require__(35);
  113339. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  113340. var _handlebarsCompilerBase = __webpack_require__(36);
  113341. var _handlebarsCompilerCompiler = __webpack_require__(41);
  113342. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  113343. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  113344. var _handlebarsCompilerVisitor = __webpack_require__(39);
  113345. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  113346. var _handlebarsNoConflict = __webpack_require__(34);
  113347. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  113348. var _create = _handlebarsRuntime2['default'].create;
  113349. function create() {
  113350. var hb = _create();
  113351. hb.compile = function (input, options) {
  113352. return _handlebarsCompilerCompiler.compile(input, options, hb);
  113353. };
  113354. hb.precompile = function (input, options) {
  113355. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  113356. };
  113357. hb.AST = _handlebarsCompilerAst2['default'];
  113358. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  113359. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  113360. hb.Parser = _handlebarsCompilerBase.parser;
  113361. hb.parse = _handlebarsCompilerBase.parse;
  113362. return hb;
  113363. }
  113364. var inst = create();
  113365. inst.create = create;
  113366. _handlebarsNoConflict2['default'](inst);
  113367. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  113368. inst['default'] = inst;
  113369. exports['default'] = inst;
  113370. module.exports = exports['default'];
  113371. /***/ }),
  113372. /* 1 */
  113373. /***/ (function(module, exports) {
  113374. "use strict";
  113375. exports["default"] = function (obj) {
  113376. return obj && obj.__esModule ? obj : {
  113377. "default": obj
  113378. };
  113379. };
  113380. exports.__esModule = true;
  113381. /***/ }),
  113382. /* 2 */
  113383. /***/ (function(module, exports, __webpack_require__) {
  113384. 'use strict';
  113385. var _interopRequireWildcard = __webpack_require__(3)['default'];
  113386. var _interopRequireDefault = __webpack_require__(1)['default'];
  113387. exports.__esModule = true;
  113388. var _handlebarsBase = __webpack_require__(4);
  113389. var base = _interopRequireWildcard(_handlebarsBase);
  113390. // Each of these augment the Handlebars object. No need to setup here.
  113391. // (This is done to easily share code between commonjs and browse envs)
  113392. var _handlebarsSafeString = __webpack_require__(21);
  113393. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  113394. var _handlebarsException = __webpack_require__(6);
  113395. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  113396. var _handlebarsUtils = __webpack_require__(5);
  113397. var Utils = _interopRequireWildcard(_handlebarsUtils);
  113398. var _handlebarsRuntime = __webpack_require__(22);
  113399. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  113400. var _handlebarsNoConflict = __webpack_require__(34);
  113401. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  113402. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  113403. function create() {
  113404. var hb = new base.HandlebarsEnvironment();
  113405. Utils.extend(hb, base);
  113406. hb.SafeString = _handlebarsSafeString2['default'];
  113407. hb.Exception = _handlebarsException2['default'];
  113408. hb.Utils = Utils;
  113409. hb.escapeExpression = Utils.escapeExpression;
  113410. hb.VM = runtime;
  113411. hb.template = function (spec) {
  113412. return runtime.template(spec, hb);
  113413. };
  113414. return hb;
  113415. }
  113416. var inst = create();
  113417. inst.create = create;
  113418. _handlebarsNoConflict2['default'](inst);
  113419. inst['default'] = inst;
  113420. exports['default'] = inst;
  113421. module.exports = exports['default'];
  113422. /***/ }),
  113423. /* 3 */
  113424. /***/ (function(module, exports) {
  113425. "use strict";
  113426. exports["default"] = function (obj) {
  113427. if (obj && obj.__esModule) {
  113428. return obj;
  113429. } else {
  113430. var newObj = {};
  113431. if (obj != null) {
  113432. for (var key in obj) {
  113433. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  113434. }
  113435. }
  113436. newObj["default"] = obj;
  113437. return newObj;
  113438. }
  113439. };
  113440. exports.__esModule = true;
  113441. /***/ }),
  113442. /* 4 */
  113443. /***/ (function(module, exports, __webpack_require__) {
  113444. 'use strict';
  113445. var _interopRequireDefault = __webpack_require__(1)['default'];
  113446. exports.__esModule = true;
  113447. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  113448. var _utils = __webpack_require__(5);
  113449. var _exception = __webpack_require__(6);
  113450. var _exception2 = _interopRequireDefault(_exception);
  113451. var _helpers = __webpack_require__(10);
  113452. var _decorators = __webpack_require__(18);
  113453. var _logger = __webpack_require__(20);
  113454. var _logger2 = _interopRequireDefault(_logger);
  113455. var VERSION = '4.0.11';
  113456. exports.VERSION = VERSION;
  113457. var COMPILER_REVISION = 7;
  113458. exports.COMPILER_REVISION = COMPILER_REVISION;
  113459. var REVISION_CHANGES = {
  113460. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  113461. 2: '== 1.0.0-rc.3',
  113462. 3: '== 1.0.0-rc.4',
  113463. 4: '== 1.x.x',
  113464. 5: '== 2.0.0-alpha.x',
  113465. 6: '>= 2.0.0-beta.1',
  113466. 7: '>= 4.0.0'
  113467. };
  113468. exports.REVISION_CHANGES = REVISION_CHANGES;
  113469. var objectType = '[object Object]';
  113470. function HandlebarsEnvironment(helpers, partials, decorators) {
  113471. this.helpers = helpers || {};
  113472. this.partials = partials || {};
  113473. this.decorators = decorators || {};
  113474. _helpers.registerDefaultHelpers(this);
  113475. _decorators.registerDefaultDecorators(this);
  113476. }
  113477. HandlebarsEnvironment.prototype = {
  113478. constructor: HandlebarsEnvironment,
  113479. logger: _logger2['default'],
  113480. log: _logger2['default'].log,
  113481. registerHelper: function registerHelper(name, fn) {
  113482. if (_utils.toString.call(name) === objectType) {
  113483. if (fn) {
  113484. throw new _exception2['default']('Arg not supported with multiple helpers');
  113485. }
  113486. _utils.extend(this.helpers, name);
  113487. } else {
  113488. this.helpers[name] = fn;
  113489. }
  113490. },
  113491. unregisterHelper: function unregisterHelper(name) {
  113492. delete this.helpers[name];
  113493. },
  113494. registerPartial: function registerPartial(name, partial) {
  113495. if (_utils.toString.call(name) === objectType) {
  113496. _utils.extend(this.partials, name);
  113497. } else {
  113498. if (typeof partial === 'undefined') {
  113499. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  113500. }
  113501. this.partials[name] = partial;
  113502. }
  113503. },
  113504. unregisterPartial: function unregisterPartial(name) {
  113505. delete this.partials[name];
  113506. },
  113507. registerDecorator: function registerDecorator(name, fn) {
  113508. if (_utils.toString.call(name) === objectType) {
  113509. if (fn) {
  113510. throw new _exception2['default']('Arg not supported with multiple decorators');
  113511. }
  113512. _utils.extend(this.decorators, name);
  113513. } else {
  113514. this.decorators[name] = fn;
  113515. }
  113516. },
  113517. unregisterDecorator: function unregisterDecorator(name) {
  113518. delete this.decorators[name];
  113519. }
  113520. };
  113521. var log = _logger2['default'].log;
  113522. exports.log = log;
  113523. exports.createFrame = _utils.createFrame;
  113524. exports.logger = _logger2['default'];
  113525. /***/ }),
  113526. /* 5 */
  113527. /***/ (function(module, exports) {
  113528. 'use strict';
  113529. exports.__esModule = true;
  113530. exports.extend = extend;
  113531. exports.indexOf = indexOf;
  113532. exports.escapeExpression = escapeExpression;
  113533. exports.isEmpty = isEmpty;
  113534. exports.createFrame = createFrame;
  113535. exports.blockParams = blockParams;
  113536. exports.appendContextPath = appendContextPath;
  113537. var escape = {
  113538. '&': '&amp;',
  113539. '<': '&lt;',
  113540. '>': '&gt;',
  113541. '"': '&quot;',
  113542. "'": '&#x27;',
  113543. '`': '&#x60;',
  113544. '=': '&#x3D;'
  113545. };
  113546. var badChars = /[&<>"'`=]/g,
  113547. possible = /[&<>"'`=]/;
  113548. function escapeChar(chr) {
  113549. return escape[chr];
  113550. }
  113551. function extend(obj /* , ...source */) {
  113552. for (var i = 1; i < arguments.length; i++) {
  113553. for (var key in arguments[i]) {
  113554. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  113555. obj[key] = arguments[i][key];
  113556. }
  113557. }
  113558. }
  113559. return obj;
  113560. }
  113561. var toString = Object.prototype.toString;
  113562. exports.toString = toString;
  113563. // Sourced from lodash
  113564. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  113565. /* eslint-disable func-style */
  113566. var isFunction = function isFunction(value) {
  113567. return typeof value === 'function';
  113568. };
  113569. // fallback for older versions of Chrome and Safari
  113570. /* istanbul ignore next */
  113571. if (isFunction(/x/)) {
  113572. exports.isFunction = isFunction = function (value) {
  113573. return typeof value === 'function' && toString.call(value) === '[object Function]';
  113574. };
  113575. }
  113576. exports.isFunction = isFunction;
  113577. /* eslint-enable func-style */
  113578. /* istanbul ignore next */
  113579. var isArray = Array.isArray || function (value) {
  113580. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  113581. };
  113582. exports.isArray = isArray;
  113583. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  113584. function indexOf(array, value) {
  113585. for (var i = 0, len = array.length; i < len; i++) {
  113586. if (array[i] === value) {
  113587. return i;
  113588. }
  113589. }
  113590. return -1;
  113591. }
  113592. function escapeExpression(string) {
  113593. if (typeof string !== 'string') {
  113594. // don't escape SafeStrings, since they're already safe
  113595. if (string && string.toHTML) {
  113596. return string.toHTML();
  113597. } else if (string == null) {
  113598. return '';
  113599. } else if (!string) {
  113600. return string + '';
  113601. }
  113602. // Force a string conversion as this will be done by the append regardless and
  113603. // the regex test will do this transparently behind the scenes, causing issues if
  113604. // an object's to string has escaped characters in it.
  113605. string = '' + string;
  113606. }
  113607. if (!possible.test(string)) {
  113608. return string;
  113609. }
  113610. return string.replace(badChars, escapeChar);
  113611. }
  113612. function isEmpty(value) {
  113613. if (!value && value !== 0) {
  113614. return true;
  113615. } else if (isArray(value) && value.length === 0) {
  113616. return true;
  113617. } else {
  113618. return false;
  113619. }
  113620. }
  113621. function createFrame(object) {
  113622. var frame = extend({}, object);
  113623. frame._parent = object;
  113624. return frame;
  113625. }
  113626. function blockParams(params, ids) {
  113627. params.path = ids;
  113628. return params;
  113629. }
  113630. function appendContextPath(contextPath, id) {
  113631. return (contextPath ? contextPath + '.' : '') + id;
  113632. }
  113633. /***/ }),
  113634. /* 6 */
  113635. /***/ (function(module, exports, __webpack_require__) {
  113636. 'use strict';
  113637. var _Object$defineProperty = __webpack_require__(7)['default'];
  113638. exports.__esModule = true;
  113639. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  113640. function Exception(message, node) {
  113641. var loc = node && node.loc,
  113642. line = undefined,
  113643. column = undefined;
  113644. if (loc) {
  113645. line = loc.start.line;
  113646. column = loc.start.column;
  113647. message += ' - ' + line + ':' + column;
  113648. }
  113649. var tmp = Error.prototype.constructor.call(this, message);
  113650. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  113651. for (var idx = 0; idx < errorProps.length; idx++) {
  113652. this[errorProps[idx]] = tmp[errorProps[idx]];
  113653. }
  113654. /* istanbul ignore else */
  113655. if (Error.captureStackTrace) {
  113656. Error.captureStackTrace(this, Exception);
  113657. }
  113658. try {
  113659. if (loc) {
  113660. this.lineNumber = line;
  113661. // Work around issue under safari where we can't directly set the column value
  113662. /* istanbul ignore next */
  113663. if (_Object$defineProperty) {
  113664. Object.defineProperty(this, 'column', {
  113665. value: column,
  113666. enumerable: true
  113667. });
  113668. } else {
  113669. this.column = column;
  113670. }
  113671. }
  113672. } catch (nop) {
  113673. /* Ignore if the browser is very particular */
  113674. }
  113675. }
  113676. Exception.prototype = new Error();
  113677. exports['default'] = Exception;
  113678. module.exports = exports['default'];
  113679. /***/ }),
  113680. /* 7 */
  113681. /***/ (function(module, exports, __webpack_require__) {
  113682. module.exports = { "default": __webpack_require__(8), __esModule: true };
  113683. /***/ }),
  113684. /* 8 */
  113685. /***/ (function(module, exports, __webpack_require__) {
  113686. var $ = __webpack_require__(9);
  113687. module.exports = function defineProperty(it, key, desc){
  113688. return $.setDesc(it, key, desc);
  113689. };
  113690. /***/ }),
  113691. /* 9 */
  113692. /***/ (function(module, exports) {
  113693. var $Object = Object;
  113694. module.exports = {
  113695. create: $Object.create,
  113696. getProto: $Object.getPrototypeOf,
  113697. isEnum: {}.propertyIsEnumerable,
  113698. getDesc: $Object.getOwnPropertyDescriptor,
  113699. setDesc: $Object.defineProperty,
  113700. setDescs: $Object.defineProperties,
  113701. getKeys: $Object.keys,
  113702. getNames: $Object.getOwnPropertyNames,
  113703. getSymbols: $Object.getOwnPropertySymbols,
  113704. each: [].forEach
  113705. };
  113706. /***/ }),
  113707. /* 10 */
  113708. /***/ (function(module, exports, __webpack_require__) {
  113709. 'use strict';
  113710. var _interopRequireDefault = __webpack_require__(1)['default'];
  113711. exports.__esModule = true;
  113712. exports.registerDefaultHelpers = registerDefaultHelpers;
  113713. var _helpersBlockHelperMissing = __webpack_require__(11);
  113714. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  113715. var _helpersEach = __webpack_require__(12);
  113716. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  113717. var _helpersHelperMissing = __webpack_require__(13);
  113718. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  113719. var _helpersIf = __webpack_require__(14);
  113720. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  113721. var _helpersLog = __webpack_require__(15);
  113722. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  113723. var _helpersLookup = __webpack_require__(16);
  113724. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  113725. var _helpersWith = __webpack_require__(17);
  113726. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  113727. function registerDefaultHelpers(instance) {
  113728. _helpersBlockHelperMissing2['default'](instance);
  113729. _helpersEach2['default'](instance);
  113730. _helpersHelperMissing2['default'](instance);
  113731. _helpersIf2['default'](instance);
  113732. _helpersLog2['default'](instance);
  113733. _helpersLookup2['default'](instance);
  113734. _helpersWith2['default'](instance);
  113735. }
  113736. /***/ }),
  113737. /* 11 */
  113738. /***/ (function(module, exports, __webpack_require__) {
  113739. 'use strict';
  113740. exports.__esModule = true;
  113741. var _utils = __webpack_require__(5);
  113742. exports['default'] = function (instance) {
  113743. instance.registerHelper('blockHelperMissing', function (context, options) {
  113744. var inverse = options.inverse,
  113745. fn = options.fn;
  113746. if (context === true) {
  113747. return fn(this);
  113748. } else if (context === false || context == null) {
  113749. return inverse(this);
  113750. } else if (_utils.isArray(context)) {
  113751. if (context.length > 0) {
  113752. if (options.ids) {
  113753. options.ids = [options.name];
  113754. }
  113755. return instance.helpers.each(context, options);
  113756. } else {
  113757. return inverse(this);
  113758. }
  113759. } else {
  113760. if (options.data && options.ids) {
  113761. var data = _utils.createFrame(options.data);
  113762. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  113763. options = { data: data };
  113764. }
  113765. return fn(context, options);
  113766. }
  113767. });
  113768. };
  113769. module.exports = exports['default'];
  113770. /***/ }),
  113771. /* 12 */
  113772. /***/ (function(module, exports, __webpack_require__) {
  113773. 'use strict';
  113774. var _interopRequireDefault = __webpack_require__(1)['default'];
  113775. exports.__esModule = true;
  113776. var _utils = __webpack_require__(5);
  113777. var _exception = __webpack_require__(6);
  113778. var _exception2 = _interopRequireDefault(_exception);
  113779. exports['default'] = function (instance) {
  113780. instance.registerHelper('each', function (context, options) {
  113781. if (!options) {
  113782. throw new _exception2['default']('Must pass iterator to #each');
  113783. }
  113784. var fn = options.fn,
  113785. inverse = options.inverse,
  113786. i = 0,
  113787. ret = '',
  113788. data = undefined,
  113789. contextPath = undefined;
  113790. if (options.data && options.ids) {
  113791. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  113792. }
  113793. if (_utils.isFunction(context)) {
  113794. context = context.call(this);
  113795. }
  113796. if (options.data) {
  113797. data = _utils.createFrame(options.data);
  113798. }
  113799. function execIteration(field, index, last) {
  113800. if (data) {
  113801. data.key = field;
  113802. data.index = index;
  113803. data.first = index === 0;
  113804. data.last = !!last;
  113805. if (contextPath) {
  113806. data.contextPath = contextPath + field;
  113807. }
  113808. }
  113809. ret = ret + fn(context[field], {
  113810. data: data,
  113811. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  113812. });
  113813. }
  113814. if (context && typeof context === 'object') {
  113815. if (_utils.isArray(context)) {
  113816. for (var j = context.length; i < j; i++) {
  113817. if (i in context) {
  113818. execIteration(i, i, i === context.length - 1);
  113819. }
  113820. }
  113821. } else {
  113822. var priorKey = undefined;
  113823. for (var key in context) {
  113824. if (context.hasOwnProperty(key)) {
  113825. // We're running the iterations one step out of sync so we can detect
  113826. // the last iteration without have to scan the object twice and create
  113827. // an itermediate keys array.
  113828. if (priorKey !== undefined) {
  113829. execIteration(priorKey, i - 1);
  113830. }
  113831. priorKey = key;
  113832. i++;
  113833. }
  113834. }
  113835. if (priorKey !== undefined) {
  113836. execIteration(priorKey, i - 1, true);
  113837. }
  113838. }
  113839. }
  113840. if (i === 0) {
  113841. ret = inverse(this);
  113842. }
  113843. return ret;
  113844. });
  113845. };
  113846. module.exports = exports['default'];
  113847. /***/ }),
  113848. /* 13 */
  113849. /***/ (function(module, exports, __webpack_require__) {
  113850. 'use strict';
  113851. var _interopRequireDefault = __webpack_require__(1)['default'];
  113852. exports.__esModule = true;
  113853. var _exception = __webpack_require__(6);
  113854. var _exception2 = _interopRequireDefault(_exception);
  113855. exports['default'] = function (instance) {
  113856. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  113857. if (arguments.length === 1) {
  113858. // A missing field in a {{foo}} construct.
  113859. return undefined;
  113860. } else {
  113861. // Someone is actually trying to call something, blow up.
  113862. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  113863. }
  113864. });
  113865. };
  113866. module.exports = exports['default'];
  113867. /***/ }),
  113868. /* 14 */
  113869. /***/ (function(module, exports, __webpack_require__) {
  113870. 'use strict';
  113871. exports.__esModule = true;
  113872. var _utils = __webpack_require__(5);
  113873. exports['default'] = function (instance) {
  113874. instance.registerHelper('if', function (conditional, options) {
  113875. if (_utils.isFunction(conditional)) {
  113876. conditional = conditional.call(this);
  113877. }
  113878. // Default behavior is to render the positive path if the value is truthy and not empty.
  113879. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  113880. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  113881. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  113882. return options.inverse(this);
  113883. } else {
  113884. return options.fn(this);
  113885. }
  113886. });
  113887. instance.registerHelper('unless', function (conditional, options) {
  113888. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  113889. });
  113890. };
  113891. module.exports = exports['default'];
  113892. /***/ }),
  113893. /* 15 */
  113894. /***/ (function(module, exports) {
  113895. 'use strict';
  113896. exports.__esModule = true;
  113897. exports['default'] = function (instance) {
  113898. instance.registerHelper('log', function () /* message, options */{
  113899. var args = [undefined],
  113900. options = arguments[arguments.length - 1];
  113901. for (var i = 0; i < arguments.length - 1; i++) {
  113902. args.push(arguments[i]);
  113903. }
  113904. var level = 1;
  113905. if (options.hash.level != null) {
  113906. level = options.hash.level;
  113907. } else if (options.data && options.data.level != null) {
  113908. level = options.data.level;
  113909. }
  113910. args[0] = level;
  113911. instance.log.apply(instance, args);
  113912. });
  113913. };
  113914. module.exports = exports['default'];
  113915. /***/ }),
  113916. /* 16 */
  113917. /***/ (function(module, exports) {
  113918. 'use strict';
  113919. exports.__esModule = true;
  113920. exports['default'] = function (instance) {
  113921. instance.registerHelper('lookup', function (obj, field) {
  113922. return obj && obj[field];
  113923. });
  113924. };
  113925. module.exports = exports['default'];
  113926. /***/ }),
  113927. /* 17 */
  113928. /***/ (function(module, exports, __webpack_require__) {
  113929. 'use strict';
  113930. exports.__esModule = true;
  113931. var _utils = __webpack_require__(5);
  113932. exports['default'] = function (instance) {
  113933. instance.registerHelper('with', function (context, options) {
  113934. if (_utils.isFunction(context)) {
  113935. context = context.call(this);
  113936. }
  113937. var fn = options.fn;
  113938. if (!_utils.isEmpty(context)) {
  113939. var data = options.data;
  113940. if (options.data && options.ids) {
  113941. data = _utils.createFrame(options.data);
  113942. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  113943. }
  113944. return fn(context, {
  113945. data: data,
  113946. blockParams: _utils.blockParams([context], [data && data.contextPath])
  113947. });
  113948. } else {
  113949. return options.inverse(this);
  113950. }
  113951. });
  113952. };
  113953. module.exports = exports['default'];
  113954. /***/ }),
  113955. /* 18 */
  113956. /***/ (function(module, exports, __webpack_require__) {
  113957. 'use strict';
  113958. var _interopRequireDefault = __webpack_require__(1)['default'];
  113959. exports.__esModule = true;
  113960. exports.registerDefaultDecorators = registerDefaultDecorators;
  113961. var _decoratorsInline = __webpack_require__(19);
  113962. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  113963. function registerDefaultDecorators(instance) {
  113964. _decoratorsInline2['default'](instance);
  113965. }
  113966. /***/ }),
  113967. /* 19 */
  113968. /***/ (function(module, exports, __webpack_require__) {
  113969. 'use strict';
  113970. exports.__esModule = true;
  113971. var _utils = __webpack_require__(5);
  113972. exports['default'] = function (instance) {
  113973. instance.registerDecorator('inline', function (fn, props, container, options) {
  113974. var ret = fn;
  113975. if (!props.partials) {
  113976. props.partials = {};
  113977. ret = function (context, options) {
  113978. // Create a new partials stack frame prior to exec.
  113979. var original = container.partials;
  113980. container.partials = _utils.extend({}, original, props.partials);
  113981. var ret = fn(context, options);
  113982. container.partials = original;
  113983. return ret;
  113984. };
  113985. }
  113986. props.partials[options.args[0]] = options.fn;
  113987. return ret;
  113988. });
  113989. };
  113990. module.exports = exports['default'];
  113991. /***/ }),
  113992. /* 20 */
  113993. /***/ (function(module, exports, __webpack_require__) {
  113994. 'use strict';
  113995. exports.__esModule = true;
  113996. var _utils = __webpack_require__(5);
  113997. var logger = {
  113998. methodMap: ['debug', 'info', 'warn', 'error'],
  113999. level: 'info',
  114000. // Maps a given level value to the `methodMap` indexes above.
  114001. lookupLevel: function lookupLevel(level) {
  114002. if (typeof level === 'string') {
  114003. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  114004. if (levelMap >= 0) {
  114005. level = levelMap;
  114006. } else {
  114007. level = parseInt(level, 10);
  114008. }
  114009. }
  114010. return level;
  114011. },
  114012. // Can be overridden in the host environment
  114013. log: function log(level) {
  114014. level = logger.lookupLevel(level);
  114015. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  114016. var method = logger.methodMap[level];
  114017. if (!console[method]) {
  114018. // eslint-disable-line no-console
  114019. method = 'log';
  114020. }
  114021. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  114022. message[_key - 1] = arguments[_key];
  114023. }
  114024. console[method].apply(console, message); // eslint-disable-line no-console
  114025. }
  114026. }
  114027. };
  114028. exports['default'] = logger;
  114029. module.exports = exports['default'];
  114030. /***/ }),
  114031. /* 21 */
  114032. /***/ (function(module, exports) {
  114033. // Build out our basic SafeString type
  114034. 'use strict';
  114035. exports.__esModule = true;
  114036. function SafeString(string) {
  114037. this.string = string;
  114038. }
  114039. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  114040. return '' + this.string;
  114041. };
  114042. exports['default'] = SafeString;
  114043. module.exports = exports['default'];
  114044. /***/ }),
  114045. /* 22 */
  114046. /***/ (function(module, exports, __webpack_require__) {
  114047. 'use strict';
  114048. var _Object$seal = __webpack_require__(23)['default'];
  114049. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114050. var _interopRequireDefault = __webpack_require__(1)['default'];
  114051. exports.__esModule = true;
  114052. exports.checkRevision = checkRevision;
  114053. exports.template = template;
  114054. exports.wrapProgram = wrapProgram;
  114055. exports.resolvePartial = resolvePartial;
  114056. exports.invokePartial = invokePartial;
  114057. exports.noop = noop;
  114058. var _utils = __webpack_require__(5);
  114059. var Utils = _interopRequireWildcard(_utils);
  114060. var _exception = __webpack_require__(6);
  114061. var _exception2 = _interopRequireDefault(_exception);
  114062. var _base = __webpack_require__(4);
  114063. function checkRevision(compilerInfo) {
  114064. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  114065. currentRevision = _base.COMPILER_REVISION;
  114066. if (compilerRevision !== currentRevision) {
  114067. if (compilerRevision < currentRevision) {
  114068. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  114069. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  114070. throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
  114071. } else {
  114072. // Use the embedded version info since the runtime doesn't know about this revision yet
  114073. throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
  114074. }
  114075. }
  114076. }
  114077. function template(templateSpec, env) {
  114078. /* istanbul ignore next */
  114079. if (!env) {
  114080. throw new _exception2['default']('No environment passed to template');
  114081. }
  114082. if (!templateSpec || !templateSpec.main) {
  114083. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  114084. }
  114085. templateSpec.main.decorator = templateSpec.main_d;
  114086. // Note: Using env.VM references rather than local var references throughout this section to allow
  114087. // for external users to override these as psuedo-supported APIs.
  114088. env.VM.checkRevision(templateSpec.compiler);
  114089. function invokePartialWrapper(partial, context, options) {
  114090. if (options.hash) {
  114091. context = Utils.extend({}, context, options.hash);
  114092. if (options.ids) {
  114093. options.ids[0] = true;
  114094. }
  114095. }
  114096. partial = env.VM.resolvePartial.call(this, partial, context, options);
  114097. var result = env.VM.invokePartial.call(this, partial, context, options);
  114098. if (result == null && env.compile) {
  114099. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  114100. result = options.partials[options.name](context, options);
  114101. }
  114102. if (result != null) {
  114103. if (options.indent) {
  114104. var lines = result.split('\n');
  114105. for (var i = 0, l = lines.length; i < l; i++) {
  114106. if (!lines[i] && i + 1 === l) {
  114107. break;
  114108. }
  114109. lines[i] = options.indent + lines[i];
  114110. }
  114111. result = lines.join('\n');
  114112. }
  114113. return result;
  114114. } else {
  114115. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  114116. }
  114117. }
  114118. // Just add water
  114119. var container = {
  114120. strict: function strict(obj, name) {
  114121. if (!(name in obj)) {
  114122. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  114123. }
  114124. return obj[name];
  114125. },
  114126. lookup: function lookup(depths, name) {
  114127. var len = depths.length;
  114128. for (var i = 0; i < len; i++) {
  114129. if (depths[i] && depths[i][name] != null) {
  114130. return depths[i][name];
  114131. }
  114132. }
  114133. },
  114134. lambda: function lambda(current, context) {
  114135. return typeof current === 'function' ? current.call(context) : current;
  114136. },
  114137. escapeExpression: Utils.escapeExpression,
  114138. invokePartial: invokePartialWrapper,
  114139. fn: function fn(i) {
  114140. var ret = templateSpec[i];
  114141. ret.decorator = templateSpec[i + '_d'];
  114142. return ret;
  114143. },
  114144. programs: [],
  114145. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  114146. var programWrapper = this.programs[i],
  114147. fn = this.fn(i);
  114148. if (data || depths || blockParams || declaredBlockParams) {
  114149. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  114150. } else if (!programWrapper) {
  114151. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  114152. }
  114153. return programWrapper;
  114154. },
  114155. data: function data(value, depth) {
  114156. while (value && depth--) {
  114157. value = value._parent;
  114158. }
  114159. return value;
  114160. },
  114161. merge: function merge(param, common) {
  114162. var obj = param || common;
  114163. if (param && common && param !== common) {
  114164. obj = Utils.extend({}, common, param);
  114165. }
  114166. return obj;
  114167. },
  114168. // An empty object to use as replacement for null-contexts
  114169. nullContext: _Object$seal({}),
  114170. noop: env.VM.noop,
  114171. compilerInfo: templateSpec.compiler
  114172. };
  114173. function ret(context) {
  114174. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114175. var data = options.data;
  114176. ret._setup(options);
  114177. if (!options.partial && templateSpec.useData) {
  114178. data = initData(context, data);
  114179. }
  114180. var depths = undefined,
  114181. blockParams = templateSpec.useBlockParams ? [] : undefined;
  114182. if (templateSpec.useDepths) {
  114183. if (options.depths) {
  114184. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  114185. } else {
  114186. depths = [context];
  114187. }
  114188. }
  114189. function main(context /*, options*/) {
  114190. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  114191. }
  114192. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  114193. return main(context, options);
  114194. }
  114195. ret.isTop = true;
  114196. ret._setup = function (options) {
  114197. if (!options.partial) {
  114198. container.helpers = container.merge(options.helpers, env.helpers);
  114199. if (templateSpec.usePartial) {
  114200. container.partials = container.merge(options.partials, env.partials);
  114201. }
  114202. if (templateSpec.usePartial || templateSpec.useDecorators) {
  114203. container.decorators = container.merge(options.decorators, env.decorators);
  114204. }
  114205. } else {
  114206. container.helpers = options.helpers;
  114207. container.partials = options.partials;
  114208. container.decorators = options.decorators;
  114209. }
  114210. };
  114211. ret._child = function (i, data, blockParams, depths) {
  114212. if (templateSpec.useBlockParams && !blockParams) {
  114213. throw new _exception2['default']('must pass block params');
  114214. }
  114215. if (templateSpec.useDepths && !depths) {
  114216. throw new _exception2['default']('must pass parent depths');
  114217. }
  114218. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  114219. };
  114220. return ret;
  114221. }
  114222. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  114223. function prog(context) {
  114224. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114225. var currentDepths = depths;
  114226. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  114227. currentDepths = [context].concat(depths);
  114228. }
  114229. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  114230. }
  114231. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  114232. prog.program = i;
  114233. prog.depth = depths ? depths.length : 0;
  114234. prog.blockParams = declaredBlockParams || 0;
  114235. return prog;
  114236. }
  114237. function resolvePartial(partial, context, options) {
  114238. if (!partial) {
  114239. if (options.name === '@partial-block') {
  114240. partial = options.data['partial-block'];
  114241. } else {
  114242. partial = options.partials[options.name];
  114243. }
  114244. } else if (!partial.call && !options.name) {
  114245. // This is a dynamic partial that returned a string
  114246. options.name = partial;
  114247. partial = options.partials[partial];
  114248. }
  114249. return partial;
  114250. }
  114251. function invokePartial(partial, context, options) {
  114252. // Use the current closure context to save the partial-block if this partial
  114253. var currentPartialBlock = options.data && options.data['partial-block'];
  114254. options.partial = true;
  114255. if (options.ids) {
  114256. options.data.contextPath = options.ids[0] || options.data.contextPath;
  114257. }
  114258. var partialBlock = undefined;
  114259. if (options.fn && options.fn !== noop) {
  114260. (function () {
  114261. options.data = _base.createFrame(options.data);
  114262. // Wrapper function to get access to currentPartialBlock from the closure
  114263. var fn = options.fn;
  114264. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  114265. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  114266. // Restore the partial-block from the closure for the execution of the block
  114267. // i.e. the part inside the block of the partial call.
  114268. options.data = _base.createFrame(options.data);
  114269. options.data['partial-block'] = currentPartialBlock;
  114270. return fn(context, options);
  114271. };
  114272. if (fn.partials) {
  114273. options.partials = Utils.extend({}, options.partials, fn.partials);
  114274. }
  114275. })();
  114276. }
  114277. if (partial === undefined && partialBlock) {
  114278. partial = partialBlock;
  114279. }
  114280. if (partial === undefined) {
  114281. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  114282. } else if (partial instanceof Function) {
  114283. return partial(context, options);
  114284. }
  114285. }
  114286. function noop() {
  114287. return '';
  114288. }
  114289. function initData(context, data) {
  114290. if (!data || !('root' in data)) {
  114291. data = data ? _base.createFrame(data) : {};
  114292. data.root = context;
  114293. }
  114294. return data;
  114295. }
  114296. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  114297. if (fn.decorator) {
  114298. var props = {};
  114299. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  114300. Utils.extend(prog, props);
  114301. }
  114302. return prog;
  114303. }
  114304. /***/ }),
  114305. /* 23 */
  114306. /***/ (function(module, exports, __webpack_require__) {
  114307. module.exports = { "default": __webpack_require__(24), __esModule: true };
  114308. /***/ }),
  114309. /* 24 */
  114310. /***/ (function(module, exports, __webpack_require__) {
  114311. __webpack_require__(25);
  114312. module.exports = __webpack_require__(30).Object.seal;
  114313. /***/ }),
  114314. /* 25 */
  114315. /***/ (function(module, exports, __webpack_require__) {
  114316. // 19.1.2.17 Object.seal(O)
  114317. var isObject = __webpack_require__(26);
  114318. __webpack_require__(27)('seal', function($seal){
  114319. return function seal(it){
  114320. return $seal && isObject(it) ? $seal(it) : it;
  114321. };
  114322. });
  114323. /***/ }),
  114324. /* 26 */
  114325. /***/ (function(module, exports) {
  114326. module.exports = function(it){
  114327. return typeof it === 'object' ? it !== null : typeof it === 'function';
  114328. };
  114329. /***/ }),
  114330. /* 27 */
  114331. /***/ (function(module, exports, __webpack_require__) {
  114332. // most Object methods by ES6 should accept primitives
  114333. var $export = __webpack_require__(28)
  114334. , core = __webpack_require__(30)
  114335. , fails = __webpack_require__(33);
  114336. module.exports = function(KEY, exec){
  114337. var fn = (core.Object || {})[KEY] || Object[KEY]
  114338. , exp = {};
  114339. exp[KEY] = exec(fn);
  114340. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  114341. };
  114342. /***/ }),
  114343. /* 28 */
  114344. /***/ (function(module, exports, __webpack_require__) {
  114345. var global = __webpack_require__(29)
  114346. , core = __webpack_require__(30)
  114347. , ctx = __webpack_require__(31)
  114348. , PROTOTYPE = 'prototype';
  114349. var $export = function(type, name, source){
  114350. var IS_FORCED = type & $export.F
  114351. , IS_GLOBAL = type & $export.G
  114352. , IS_STATIC = type & $export.S
  114353. , IS_PROTO = type & $export.P
  114354. , IS_BIND = type & $export.B
  114355. , IS_WRAP = type & $export.W
  114356. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  114357. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  114358. , key, own, out;
  114359. if(IS_GLOBAL)source = name;
  114360. for(key in source){
  114361. // contains in native
  114362. own = !IS_FORCED && target && key in target;
  114363. if(own && key in exports)continue;
  114364. // export native or passed
  114365. out = own ? target[key] : source[key];
  114366. // prevent global pollution for namespaces
  114367. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  114368. // bind timers to global for call from export context
  114369. : IS_BIND && own ? ctx(out, global)
  114370. // wrap global constructors for prevent change them in library
  114371. : IS_WRAP && target[key] == out ? (function(C){
  114372. var F = function(param){
  114373. return this instanceof C ? new C(param) : C(param);
  114374. };
  114375. F[PROTOTYPE] = C[PROTOTYPE];
  114376. return F;
  114377. // make static versions for prototype methods
  114378. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  114379. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  114380. }
  114381. };
  114382. // type bitmap
  114383. $export.F = 1; // forced
  114384. $export.G = 2; // global
  114385. $export.S = 4; // static
  114386. $export.P = 8; // proto
  114387. $export.B = 16; // bind
  114388. $export.W = 32; // wrap
  114389. module.exports = $export;
  114390. /***/ }),
  114391. /* 29 */
  114392. /***/ (function(module, exports) {
  114393. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  114394. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  114395. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  114396. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  114397. /***/ }),
  114398. /* 30 */
  114399. /***/ (function(module, exports) {
  114400. var core = module.exports = {version: '1.2.6'};
  114401. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  114402. /***/ }),
  114403. /* 31 */
  114404. /***/ (function(module, exports, __webpack_require__) {
  114405. // optional / simple context binding
  114406. var aFunction = __webpack_require__(32);
  114407. module.exports = function(fn, that, length){
  114408. aFunction(fn);
  114409. if(that === undefined)return fn;
  114410. switch(length){
  114411. case 1: return function(a){
  114412. return fn.call(that, a);
  114413. };
  114414. case 2: return function(a, b){
  114415. return fn.call(that, a, b);
  114416. };
  114417. case 3: return function(a, b, c){
  114418. return fn.call(that, a, b, c);
  114419. };
  114420. }
  114421. return function(/* ...args */){
  114422. return fn.apply(that, arguments);
  114423. };
  114424. };
  114425. /***/ }),
  114426. /* 32 */
  114427. /***/ (function(module, exports) {
  114428. module.exports = function(it){
  114429. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  114430. return it;
  114431. };
  114432. /***/ }),
  114433. /* 33 */
  114434. /***/ (function(module, exports) {
  114435. module.exports = function(exec){
  114436. try {
  114437. return !!exec();
  114438. } catch(e){
  114439. return true;
  114440. }
  114441. };
  114442. /***/ }),
  114443. /* 34 */
  114444. /***/ (function(module, exports) {
  114445. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  114446. 'use strict';
  114447. exports.__esModule = true;
  114448. exports['default'] = function (Handlebars) {
  114449. /* istanbul ignore next */
  114450. var root = typeof global !== 'undefined' ? global : window,
  114451. $Handlebars = root.Handlebars;
  114452. /* istanbul ignore next */
  114453. Handlebars.noConflict = function () {
  114454. if (root.Handlebars === Handlebars) {
  114455. root.Handlebars = $Handlebars;
  114456. }
  114457. return Handlebars;
  114458. };
  114459. };
  114460. module.exports = exports['default'];
  114461. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  114462. /***/ }),
  114463. /* 35 */
  114464. /***/ (function(module, exports) {
  114465. 'use strict';
  114466. exports.__esModule = true;
  114467. var AST = {
  114468. // Public API used to evaluate derived attributes regarding AST nodes
  114469. helpers: {
  114470. // a mustache is definitely a helper if:
  114471. // * it is an eligible helper, and
  114472. // * it has at least one parameter or hash segment
  114473. helperExpression: function helperExpression(node) {
  114474. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  114475. },
  114476. scopedId: function scopedId(path) {
  114477. return (/^\.|this\b/.test(path.original)
  114478. );
  114479. },
  114480. // an ID is simple if it only has one part, and that part is not
  114481. // `..` or `this`.
  114482. simpleId: function simpleId(path) {
  114483. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  114484. }
  114485. }
  114486. };
  114487. // Must be exported as an object rather than the root of the module as the jison lexer
  114488. // must modify the object to operate properly.
  114489. exports['default'] = AST;
  114490. module.exports = exports['default'];
  114491. /***/ }),
  114492. /* 36 */
  114493. /***/ (function(module, exports, __webpack_require__) {
  114494. 'use strict';
  114495. var _interopRequireDefault = __webpack_require__(1)['default'];
  114496. var _interopRequireWildcard = __webpack_require__(3)['default'];
  114497. exports.__esModule = true;
  114498. exports.parse = parse;
  114499. var _parser = __webpack_require__(37);
  114500. var _parser2 = _interopRequireDefault(_parser);
  114501. var _whitespaceControl = __webpack_require__(38);
  114502. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  114503. var _helpers = __webpack_require__(40);
  114504. var Helpers = _interopRequireWildcard(_helpers);
  114505. var _utils = __webpack_require__(5);
  114506. exports.parser = _parser2['default'];
  114507. var yy = {};
  114508. _utils.extend(yy, Helpers);
  114509. function parse(input, options) {
  114510. // Just return if an already-compiled AST was passed in.
  114511. if (input.type === 'Program') {
  114512. return input;
  114513. }
  114514. _parser2['default'].yy = yy;
  114515. // Altering the shared object here, but this is ok as parser is a sync operation
  114516. yy.locInfo = function (locInfo) {
  114517. return new yy.SourceLocation(options && options.srcName, locInfo);
  114518. };
  114519. var strip = new _whitespaceControl2['default'](options);
  114520. return strip.accept(_parser2['default'].parse(input));
  114521. }
  114522. /***/ }),
  114523. /* 37 */
  114524. /***/ (function(module, exports) {
  114525. // File ignored in coverage tests via setting in .istanbul.yml
  114526. /* Jison generated parser */
  114527. "use strict";
  114528. exports.__esModule = true;
  114529. var handlebars = (function () {
  114530. var parser = { trace: function trace() {},
  114531. yy: {},
  114532. 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 },
  114533. 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" },
  114534. 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]],
  114535. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  114536. /**/) {
  114537. var $0 = $$.length - 1;
  114538. switch (yystate) {
  114539. case 1:
  114540. return $$[$0 - 1];
  114541. break;
  114542. case 2:
  114543. this.$ = yy.prepareProgram($$[$0]);
  114544. break;
  114545. case 3:
  114546. this.$ = $$[$0];
  114547. break;
  114548. case 4:
  114549. this.$ = $$[$0];
  114550. break;
  114551. case 5:
  114552. this.$ = $$[$0];
  114553. break;
  114554. case 6:
  114555. this.$ = $$[$0];
  114556. break;
  114557. case 7:
  114558. this.$ = $$[$0];
  114559. break;
  114560. case 8:
  114561. this.$ = $$[$0];
  114562. break;
  114563. case 9:
  114564. this.$ = {
  114565. type: 'CommentStatement',
  114566. value: yy.stripComment($$[$0]),
  114567. strip: yy.stripFlags($$[$0], $$[$0]),
  114568. loc: yy.locInfo(this._$)
  114569. };
  114570. break;
  114571. case 10:
  114572. this.$ = {
  114573. type: 'ContentStatement',
  114574. original: $$[$0],
  114575. value: $$[$0],
  114576. loc: yy.locInfo(this._$)
  114577. };
  114578. break;
  114579. case 11:
  114580. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114581. break;
  114582. case 12:
  114583. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  114584. break;
  114585. case 13:
  114586. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  114587. break;
  114588. case 14:
  114589. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  114590. break;
  114591. case 15:
  114592. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114593. break;
  114594. case 16:
  114595. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114596. break;
  114597. case 17:
  114598. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  114599. break;
  114600. case 18:
  114601. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  114602. break;
  114603. case 19:
  114604. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  114605. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  114606. program.chained = true;
  114607. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  114608. break;
  114609. case 20:
  114610. this.$ = $$[$0];
  114611. break;
  114612. case 21:
  114613. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  114614. break;
  114615. case 22:
  114616. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114617. break;
  114618. case 23:
  114619. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  114620. break;
  114621. case 24:
  114622. this.$ = {
  114623. type: 'PartialStatement',
  114624. name: $$[$0 - 3],
  114625. params: $$[$0 - 2],
  114626. hash: $$[$0 - 1],
  114627. indent: '',
  114628. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  114629. loc: yy.locInfo(this._$)
  114630. };
  114631. break;
  114632. case 25:
  114633. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  114634. break;
  114635. case 26:
  114636. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  114637. break;
  114638. case 27:
  114639. this.$ = $$[$0];
  114640. break;
  114641. case 28:
  114642. this.$ = $$[$0];
  114643. break;
  114644. case 29:
  114645. this.$ = {
  114646. type: 'SubExpression',
  114647. path: $$[$0 - 3],
  114648. params: $$[$0 - 2],
  114649. hash: $$[$0 - 1],
  114650. loc: yy.locInfo(this._$)
  114651. };
  114652. break;
  114653. case 30:
  114654. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  114655. break;
  114656. case 31:
  114657. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  114658. break;
  114659. case 32:
  114660. this.$ = yy.id($$[$0 - 1]);
  114661. break;
  114662. case 33:
  114663. this.$ = $$[$0];
  114664. break;
  114665. case 34:
  114666. this.$ = $$[$0];
  114667. break;
  114668. case 35:
  114669. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  114670. break;
  114671. case 36:
  114672. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  114673. break;
  114674. case 37:
  114675. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  114676. break;
  114677. case 38:
  114678. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  114679. break;
  114680. case 39:
  114681. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  114682. break;
  114683. case 40:
  114684. this.$ = $$[$0];
  114685. break;
  114686. case 41:
  114687. this.$ = $$[$0];
  114688. break;
  114689. case 42:
  114690. this.$ = yy.preparePath(true, $$[$0], this._$);
  114691. break;
  114692. case 43:
  114693. this.$ = yy.preparePath(false, $$[$0], this._$);
  114694. break;
  114695. case 44:
  114696. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  114697. break;
  114698. case 45:
  114699. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  114700. break;
  114701. case 46:
  114702. this.$ = [];
  114703. break;
  114704. case 47:
  114705. $$[$0 - 1].push($$[$0]);
  114706. break;
  114707. case 48:
  114708. this.$ = [$$[$0]];
  114709. break;
  114710. case 49:
  114711. $$[$0 - 1].push($$[$0]);
  114712. break;
  114713. case 50:
  114714. this.$ = [];
  114715. break;
  114716. case 51:
  114717. $$[$0 - 1].push($$[$0]);
  114718. break;
  114719. case 58:
  114720. this.$ = [];
  114721. break;
  114722. case 59:
  114723. $$[$0 - 1].push($$[$0]);
  114724. break;
  114725. case 64:
  114726. this.$ = [];
  114727. break;
  114728. case 65:
  114729. $$[$0 - 1].push($$[$0]);
  114730. break;
  114731. case 70:
  114732. this.$ = [];
  114733. break;
  114734. case 71:
  114735. $$[$0 - 1].push($$[$0]);
  114736. break;
  114737. case 78:
  114738. this.$ = [];
  114739. break;
  114740. case 79:
  114741. $$[$0 - 1].push($$[$0]);
  114742. break;
  114743. case 82:
  114744. this.$ = [];
  114745. break;
  114746. case 83:
  114747. $$[$0 - 1].push($$[$0]);
  114748. break;
  114749. case 86:
  114750. this.$ = [];
  114751. break;
  114752. case 87:
  114753. $$[$0 - 1].push($$[$0]);
  114754. break;
  114755. case 90:
  114756. this.$ = [];
  114757. break;
  114758. case 91:
  114759. $$[$0 - 1].push($$[$0]);
  114760. break;
  114761. case 94:
  114762. this.$ = [];
  114763. break;
  114764. case 95:
  114765. $$[$0 - 1].push($$[$0]);
  114766. break;
  114767. case 98:
  114768. this.$ = [$$[$0]];
  114769. break;
  114770. case 99:
  114771. $$[$0 - 1].push($$[$0]);
  114772. break;
  114773. case 100:
  114774. this.$ = [$$[$0]];
  114775. break;
  114776. case 101:
  114777. $$[$0 - 1].push($$[$0]);
  114778. break;
  114779. }
  114780. },
  114781. table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 13: 40, 15: [1, 20], 17: 39 }, { 20: 42, 56: 41, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 45, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 48, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 42, 56: 49, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 50, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 51] }, { 72: [1, 35], 86: 52 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 53, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 54, 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 55, 47: [2, 54] }, { 28: 60, 43: 61, 44: [1, 59], 47: [2, 56] }, { 13: 63, 15: [1, 20], 18: [1, 62] }, { 15: [2, 48], 18: [2, 48] }, { 33: [2, 86], 57: 64, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 65, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 66, 47: [1, 67] }, { 30: 68, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 69, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 70, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 71, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 75, 33: [2, 80], 50: 72, 63: 73, 64: 76, 65: [1, 44], 69: 74, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 80] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 51] }, { 20: 75, 53: 81, 54: [2, 84], 63: 82, 64: 76, 65: [1, 44], 69: 83, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 84, 47: [1, 67] }, { 47: [2, 55] }, { 4: 85, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 86, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 87, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 88, 47: [1, 67] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 75, 33: [2, 88], 58: 89, 63: 90, 64: 76, 65: [1, 44], 69: 91, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 92, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 93, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 31: 94, 33: [2, 60], 63: 95, 64: 76, 65: [1, 44], 69: 96, 70: 77, 71: 78, 72: [1, 79], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 66], 36: 97, 63: 98, 64: 76, 65: [1, 44], 69: 99, 70: 77, 71: 78, 72: [1, 79], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 22: 100, 23: [2, 52], 63: 101, 64: 76, 65: [1, 44], 69: 102, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 92], 62: 103, 63: 104, 64: 76, 65: [1, 44], 69: 105, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 106] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 107, 72: [1, 108], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 109], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 110] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 112, 46: 111, 47: [2, 76] }, { 33: [2, 70], 40: 113, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 114] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 75, 63: 116, 64: 76, 65: [1, 44], 67: 115, 68: [2, 96], 69: 117, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 118] }, { 32: 119, 33: [2, 62], 74: 120, 75: [1, 121] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 122, 74: 123, 75: [1, 121] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 124] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 125] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 109] }, { 20: 75, 63: 126, 64: 76, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 75, 33: [2, 72], 41: 127, 63: 128, 64: 76, 65: [1, 44], 69: 129, 70: 77, 71: 78, 72: [1, 79], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 130] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 131] }, { 33: [2, 63] }, { 72: [1, 133], 76: 132 }, { 33: [1, 134] }, { 33: [2, 69] }, { 15: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 135, 74: 136, 75: [1, 121] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 138], 77: [1, 137] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 139] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }],
  114782. 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] },
  114783. parseError: function parseError(str, hash) {
  114784. throw new Error(str);
  114785. },
  114786. parse: function parse(input) {
  114787. var self = this,
  114788. stack = [0],
  114789. vstack = [null],
  114790. lstack = [],
  114791. table = this.table,
  114792. yytext = "",
  114793. yylineno = 0,
  114794. yyleng = 0,
  114795. recovering = 0,
  114796. TERROR = 2,
  114797. EOF = 1;
  114798. this.lexer.setInput(input);
  114799. this.lexer.yy = this.yy;
  114800. this.yy.lexer = this.lexer;
  114801. this.yy.parser = this;
  114802. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  114803. var yyloc = this.lexer.yylloc;
  114804. lstack.push(yyloc);
  114805. var ranges = this.lexer.options && this.lexer.options.ranges;
  114806. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  114807. function popStack(n) {
  114808. stack.length = stack.length - 2 * n;
  114809. vstack.length = vstack.length - n;
  114810. lstack.length = lstack.length - n;
  114811. }
  114812. function lex() {
  114813. var token;
  114814. token = self.lexer.lex() || 1;
  114815. if (typeof token !== "number") {
  114816. token = self.symbols_[token] || token;
  114817. }
  114818. return token;
  114819. }
  114820. var symbol,
  114821. preErrorSymbol,
  114822. state,
  114823. action,
  114824. a,
  114825. r,
  114826. yyval = {},
  114827. p,
  114828. len,
  114829. newState,
  114830. expected;
  114831. while (true) {
  114832. state = stack[stack.length - 1];
  114833. if (this.defaultActions[state]) {
  114834. action = this.defaultActions[state];
  114835. } else {
  114836. if (symbol === null || typeof symbol == "undefined") {
  114837. symbol = lex();
  114838. }
  114839. action = table[state] && table[state][symbol];
  114840. }
  114841. if (typeof action === "undefined" || !action.length || !action[0]) {
  114842. var errStr = "";
  114843. if (!recovering) {
  114844. expected = [];
  114845. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  114846. expected.push("'" + this.terminals_[p] + "'");
  114847. }
  114848. if (this.lexer.showPosition) {
  114849. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  114850. } else {
  114851. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  114852. }
  114853. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  114854. }
  114855. }
  114856. if (action[0] instanceof Array && action.length > 1) {
  114857. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  114858. }
  114859. switch (action[0]) {
  114860. case 1:
  114861. stack.push(symbol);
  114862. vstack.push(this.lexer.yytext);
  114863. lstack.push(this.lexer.yylloc);
  114864. stack.push(action[1]);
  114865. symbol = null;
  114866. if (!preErrorSymbol) {
  114867. yyleng = this.lexer.yyleng;
  114868. yytext = this.lexer.yytext;
  114869. yylineno = this.lexer.yylineno;
  114870. yyloc = this.lexer.yylloc;
  114871. if (recovering > 0) recovering--;
  114872. } else {
  114873. symbol = preErrorSymbol;
  114874. preErrorSymbol = null;
  114875. }
  114876. break;
  114877. case 2:
  114878. len = this.productions_[action[1]][1];
  114879. yyval.$ = vstack[vstack.length - len];
  114880. yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
  114881. if (ranges) {
  114882. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  114883. }
  114884. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  114885. if (typeof r !== "undefined") {
  114886. return r;
  114887. }
  114888. if (len) {
  114889. stack = stack.slice(0, -1 * len * 2);
  114890. vstack = vstack.slice(0, -1 * len);
  114891. lstack = lstack.slice(0, -1 * len);
  114892. }
  114893. stack.push(this.productions_[action[1]][0]);
  114894. vstack.push(yyval.$);
  114895. lstack.push(yyval._$);
  114896. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  114897. stack.push(newState);
  114898. break;
  114899. case 3:
  114900. return true;
  114901. }
  114902. }
  114903. return true;
  114904. }
  114905. };
  114906. /* Jison generated lexer */
  114907. var lexer = (function () {
  114908. var lexer = { EOF: 1,
  114909. parseError: function parseError(str, hash) {
  114910. if (this.yy.parser) {
  114911. this.yy.parser.parseError(str, hash);
  114912. } else {
  114913. throw new Error(str);
  114914. }
  114915. },
  114916. setInput: function setInput(input) {
  114917. this._input = input;
  114918. this._more = this._less = this.done = false;
  114919. this.yylineno = this.yyleng = 0;
  114920. this.yytext = this.matched = this.match = '';
  114921. this.conditionStack = ['INITIAL'];
  114922. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  114923. if (this.options.ranges) this.yylloc.range = [0, 0];
  114924. this.offset = 0;
  114925. return this;
  114926. },
  114927. input: function input() {
  114928. var ch = this._input[0];
  114929. this.yytext += ch;
  114930. this.yyleng++;
  114931. this.offset++;
  114932. this.match += ch;
  114933. this.matched += ch;
  114934. var lines = ch.match(/(?:\r\n?|\n).*/g);
  114935. if (lines) {
  114936. this.yylineno++;
  114937. this.yylloc.last_line++;
  114938. } else {
  114939. this.yylloc.last_column++;
  114940. }
  114941. if (this.options.ranges) this.yylloc.range[1]++;
  114942. this._input = this._input.slice(1);
  114943. return ch;
  114944. },
  114945. unput: function unput(ch) {
  114946. var len = ch.length;
  114947. var lines = ch.split(/(?:\r\n?|\n)/g);
  114948. this._input = ch + this._input;
  114949. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  114950. //this.yyleng -= len;
  114951. this.offset -= len;
  114952. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  114953. this.match = this.match.substr(0, this.match.length - 1);
  114954. this.matched = this.matched.substr(0, this.matched.length - 1);
  114955. if (lines.length - 1) this.yylineno -= lines.length - 1;
  114956. var r = this.yylloc.range;
  114957. this.yylloc = { first_line: this.yylloc.first_line,
  114958. last_line: this.yylineno + 1,
  114959. first_column: this.yylloc.first_column,
  114960. last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
  114961. };
  114962. if (this.options.ranges) {
  114963. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  114964. }
  114965. return this;
  114966. },
  114967. more: function more() {
  114968. this._more = true;
  114969. return this;
  114970. },
  114971. less: function less(n) {
  114972. this.unput(this.match.slice(n));
  114973. },
  114974. pastInput: function pastInput() {
  114975. var past = this.matched.substr(0, this.matched.length - this.match.length);
  114976. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  114977. },
  114978. upcomingInput: function upcomingInput() {
  114979. var next = this.match;
  114980. if (next.length < 20) {
  114981. next += this._input.substr(0, 20 - next.length);
  114982. }
  114983. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  114984. },
  114985. showPosition: function showPosition() {
  114986. var pre = this.pastInput();
  114987. var c = new Array(pre.length + 1).join("-");
  114988. return pre + this.upcomingInput() + "\n" + c + "^";
  114989. },
  114990. next: function next() {
  114991. if (this.done) {
  114992. return this.EOF;
  114993. }
  114994. if (!this._input) this.done = true;
  114995. var token, match, tempMatch, index, col, lines;
  114996. if (!this._more) {
  114997. this.yytext = '';
  114998. this.match = '';
  114999. }
  115000. var rules = this._currentRules();
  115001. for (var i = 0; i < rules.length; i++) {
  115002. tempMatch = this._input.match(this.rules[rules[i]]);
  115003. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  115004. match = tempMatch;
  115005. index = i;
  115006. if (!this.options.flex) break;
  115007. }
  115008. }
  115009. if (match) {
  115010. lines = match[0].match(/(?:\r\n?|\n).*/g);
  115011. if (lines) this.yylineno += lines.length;
  115012. this.yylloc = { first_line: this.yylloc.last_line,
  115013. last_line: this.yylineno + 1,
  115014. first_column: this.yylloc.last_column,
  115015. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  115016. this.yytext += match[0];
  115017. this.match += match[0];
  115018. this.matches = match;
  115019. this.yyleng = this.yytext.length;
  115020. if (this.options.ranges) {
  115021. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  115022. }
  115023. this._more = false;
  115024. this._input = this._input.slice(match[0].length);
  115025. this.matched += match[0];
  115026. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  115027. if (this.done && this._input) this.done = false;
  115028. if (token) return token;else return;
  115029. }
  115030. if (this._input === "") {
  115031. return this.EOF;
  115032. } else {
  115033. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  115034. }
  115035. },
  115036. lex: function lex() {
  115037. var r = this.next();
  115038. if (typeof r !== 'undefined') {
  115039. return r;
  115040. } else {
  115041. return this.lex();
  115042. }
  115043. },
  115044. begin: function begin(condition) {
  115045. this.conditionStack.push(condition);
  115046. },
  115047. popState: function popState() {
  115048. return this.conditionStack.pop();
  115049. },
  115050. _currentRules: function _currentRules() {
  115051. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  115052. },
  115053. topState: function topState() {
  115054. return this.conditionStack[this.conditionStack.length - 2];
  115055. },
  115056. pushState: function begin(condition) {
  115057. this.begin(condition);
  115058. } };
  115059. lexer.options = {};
  115060. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  115061. /**/) {
  115062. function strip(start, end) {
  115063. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  115064. }
  115065. var YYSTATE = YY_START;
  115066. switch ($avoiding_name_collisions) {
  115067. case 0:
  115068. if (yy_.yytext.slice(-2) === "\\\\") {
  115069. strip(0, 1);
  115070. this.begin("mu");
  115071. } else if (yy_.yytext.slice(-1) === "\\") {
  115072. strip(0, 1);
  115073. this.begin("emu");
  115074. } else {
  115075. this.begin("mu");
  115076. }
  115077. if (yy_.yytext) return 15;
  115078. break;
  115079. case 1:
  115080. return 15;
  115081. break;
  115082. case 2:
  115083. this.popState();
  115084. return 15;
  115085. break;
  115086. case 3:
  115087. this.begin('raw');return 15;
  115088. break;
  115089. case 4:
  115090. this.popState();
  115091. // Should be using `this.topState()` below, but it currently
  115092. // returns the second top instead of the first top. Opened an
  115093. // issue about it at https://github.com/zaach/jison/issues/291
  115094. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  115095. return 15;
  115096. } else {
  115097. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  115098. return 'END_RAW_BLOCK';
  115099. }
  115100. break;
  115101. case 5:
  115102. return 15;
  115103. break;
  115104. case 6:
  115105. this.popState();
  115106. return 14;
  115107. break;
  115108. case 7:
  115109. return 65;
  115110. break;
  115111. case 8:
  115112. return 68;
  115113. break;
  115114. case 9:
  115115. return 19;
  115116. break;
  115117. case 10:
  115118. this.popState();
  115119. this.begin('raw');
  115120. return 23;
  115121. break;
  115122. case 11:
  115123. return 55;
  115124. break;
  115125. case 12:
  115126. return 60;
  115127. break;
  115128. case 13:
  115129. return 29;
  115130. break;
  115131. case 14:
  115132. return 47;
  115133. break;
  115134. case 15:
  115135. this.popState();return 44;
  115136. break;
  115137. case 16:
  115138. this.popState();return 44;
  115139. break;
  115140. case 17:
  115141. return 34;
  115142. break;
  115143. case 18:
  115144. return 39;
  115145. break;
  115146. case 19:
  115147. return 51;
  115148. break;
  115149. case 20:
  115150. return 48;
  115151. break;
  115152. case 21:
  115153. this.unput(yy_.yytext);
  115154. this.popState();
  115155. this.begin('com');
  115156. break;
  115157. case 22:
  115158. this.popState();
  115159. return 14;
  115160. break;
  115161. case 23:
  115162. return 48;
  115163. break;
  115164. case 24:
  115165. return 73;
  115166. break;
  115167. case 25:
  115168. return 72;
  115169. break;
  115170. case 26:
  115171. return 72;
  115172. break;
  115173. case 27:
  115174. return 87;
  115175. break;
  115176. case 28:
  115177. // ignore whitespace
  115178. break;
  115179. case 29:
  115180. this.popState();return 54;
  115181. break;
  115182. case 30:
  115183. this.popState();return 33;
  115184. break;
  115185. case 31:
  115186. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  115187. break;
  115188. case 32:
  115189. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  115190. break;
  115191. case 33:
  115192. return 85;
  115193. break;
  115194. case 34:
  115195. return 82;
  115196. break;
  115197. case 35:
  115198. return 82;
  115199. break;
  115200. case 36:
  115201. return 83;
  115202. break;
  115203. case 37:
  115204. return 84;
  115205. break;
  115206. case 38:
  115207. return 81;
  115208. break;
  115209. case 39:
  115210. return 75;
  115211. break;
  115212. case 40:
  115213. return 77;
  115214. break;
  115215. case 41:
  115216. return 72;
  115217. break;
  115218. case 42:
  115219. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  115220. break;
  115221. case 43:
  115222. return 'INVALID';
  115223. break;
  115224. case 44:
  115225. return 5;
  115226. break;
  115227. }
  115228. };
  115229. lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^\/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]*?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  115230. lexer.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
  115231. return lexer;
  115232. })();
  115233. parser.lexer = lexer;
  115234. function Parser() {
  115235. this.yy = {};
  115236. }Parser.prototype = parser;parser.Parser = Parser;
  115237. return new Parser();
  115238. })();exports["default"] = handlebars;
  115239. module.exports = exports["default"];
  115240. /***/ }),
  115241. /* 38 */
  115242. /***/ (function(module, exports, __webpack_require__) {
  115243. 'use strict';
  115244. var _interopRequireDefault = __webpack_require__(1)['default'];
  115245. exports.__esModule = true;
  115246. var _visitor = __webpack_require__(39);
  115247. var _visitor2 = _interopRequireDefault(_visitor);
  115248. function WhitespaceControl() {
  115249. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  115250. this.options = options;
  115251. }
  115252. WhitespaceControl.prototype = new _visitor2['default']();
  115253. WhitespaceControl.prototype.Program = function (program) {
  115254. var doStandalone = !this.options.ignoreStandalone;
  115255. var isRoot = !this.isRootSeen;
  115256. this.isRootSeen = true;
  115257. var body = program.body;
  115258. for (var i = 0, l = body.length; i < l; i++) {
  115259. var current = body[i],
  115260. strip = this.accept(current);
  115261. if (!strip) {
  115262. continue;
  115263. }
  115264. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  115265. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  115266. openStandalone = strip.openStandalone && _isPrevWhitespace,
  115267. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  115268. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  115269. if (strip.close) {
  115270. omitRight(body, i, true);
  115271. }
  115272. if (strip.open) {
  115273. omitLeft(body, i, true);
  115274. }
  115275. if (doStandalone && inlineStandalone) {
  115276. omitRight(body, i);
  115277. if (omitLeft(body, i)) {
  115278. // If we are on a standalone node, save the indent info for partials
  115279. if (current.type === 'PartialStatement') {
  115280. // Pull out the whitespace from the final line
  115281. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  115282. }
  115283. }
  115284. }
  115285. if (doStandalone && openStandalone) {
  115286. omitRight((current.program || current.inverse).body);
  115287. // Strip out the previous content node if it's whitespace only
  115288. omitLeft(body, i);
  115289. }
  115290. if (doStandalone && closeStandalone) {
  115291. // Always strip the next node
  115292. omitRight(body, i);
  115293. omitLeft((current.inverse || current.program).body);
  115294. }
  115295. }
  115296. return program;
  115297. };
  115298. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  115299. this.accept(block.program);
  115300. this.accept(block.inverse);
  115301. // Find the inverse program that is involed with whitespace stripping.
  115302. var program = block.program || block.inverse,
  115303. inverse = block.program && block.inverse,
  115304. firstInverse = inverse,
  115305. lastInverse = inverse;
  115306. if (inverse && inverse.chained) {
  115307. firstInverse = inverse.body[0].program;
  115308. // Walk the inverse chain to find the last inverse that is actually in the chain.
  115309. while (lastInverse.chained) {
  115310. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  115311. }
  115312. }
  115313. var strip = {
  115314. open: block.openStrip.open,
  115315. close: block.closeStrip.close,
  115316. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  115317. // so our parent can determine if we actually are standalone
  115318. openStandalone: isNextWhitespace(program.body),
  115319. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  115320. };
  115321. if (block.openStrip.close) {
  115322. omitRight(program.body, null, true);
  115323. }
  115324. if (inverse) {
  115325. var inverseStrip = block.inverseStrip;
  115326. if (inverseStrip.open) {
  115327. omitLeft(program.body, null, true);
  115328. }
  115329. if (inverseStrip.close) {
  115330. omitRight(firstInverse.body, null, true);
  115331. }
  115332. if (block.closeStrip.open) {
  115333. omitLeft(lastInverse.body, null, true);
  115334. }
  115335. // Find standalone else statments
  115336. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  115337. omitLeft(program.body);
  115338. omitRight(firstInverse.body);
  115339. }
  115340. } else if (block.closeStrip.open) {
  115341. omitLeft(program.body, null, true);
  115342. }
  115343. return strip;
  115344. };
  115345. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  115346. return mustache.strip;
  115347. };
  115348. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  115349. /* istanbul ignore next */
  115350. var strip = node.strip || {};
  115351. return {
  115352. inlineStandalone: true,
  115353. open: strip.open,
  115354. close: strip.close
  115355. };
  115356. };
  115357. function isPrevWhitespace(body, i, isRoot) {
  115358. if (i === undefined) {
  115359. i = body.length;
  115360. }
  115361. // Nodes that end with newlines are considered whitespace (but are special
  115362. // cased for strip operations)
  115363. var prev = body[i - 1],
  115364. sibling = body[i - 2];
  115365. if (!prev) {
  115366. return isRoot;
  115367. }
  115368. if (prev.type === 'ContentStatement') {
  115369. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  115370. }
  115371. }
  115372. function isNextWhitespace(body, i, isRoot) {
  115373. if (i === undefined) {
  115374. i = -1;
  115375. }
  115376. var next = body[i + 1],
  115377. sibling = body[i + 2];
  115378. if (!next) {
  115379. return isRoot;
  115380. }
  115381. if (next.type === 'ContentStatement') {
  115382. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  115383. }
  115384. }
  115385. // Marks the node to the right of the position as omitted.
  115386. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  115387. //
  115388. // If i is undefined, then the first child will be marked as such.
  115389. //
  115390. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  115391. // content is met.
  115392. function omitRight(body, i, multiple) {
  115393. var current = body[i == null ? 0 : i + 1];
  115394. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  115395. return;
  115396. }
  115397. var original = current.value;
  115398. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  115399. current.rightStripped = current.value !== original;
  115400. }
  115401. // Marks the node to the left of the position as omitted.
  115402. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  115403. //
  115404. // If i is undefined then the last child will be marked as such.
  115405. //
  115406. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  115407. // content is met.
  115408. function omitLeft(body, i, multiple) {
  115409. var current = body[i == null ? body.length - 1 : i - 1];
  115410. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  115411. return;
  115412. }
  115413. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  115414. var original = current.value;
  115415. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  115416. current.leftStripped = current.value !== original;
  115417. return current.leftStripped;
  115418. }
  115419. exports['default'] = WhitespaceControl;
  115420. module.exports = exports['default'];
  115421. /***/ }),
  115422. /* 39 */
  115423. /***/ (function(module, exports, __webpack_require__) {
  115424. 'use strict';
  115425. var _interopRequireDefault = __webpack_require__(1)['default'];
  115426. exports.__esModule = true;
  115427. var _exception = __webpack_require__(6);
  115428. var _exception2 = _interopRequireDefault(_exception);
  115429. function Visitor() {
  115430. this.parents = [];
  115431. }
  115432. Visitor.prototype = {
  115433. constructor: Visitor,
  115434. mutating: false,
  115435. // Visits a given value. If mutating, will replace the value if necessary.
  115436. acceptKey: function acceptKey(node, name) {
  115437. var value = this.accept(node[name]);
  115438. if (this.mutating) {
  115439. // Hacky sanity check: This may have a few false positives for type for the helper
  115440. // methods but will generally do the right thing without a lot of overhead.
  115441. if (value && !Visitor.prototype[value.type]) {
  115442. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  115443. }
  115444. node[name] = value;
  115445. }
  115446. },
  115447. // Performs an accept operation with added sanity check to ensure
  115448. // required keys are not removed.
  115449. acceptRequired: function acceptRequired(node, name) {
  115450. this.acceptKey(node, name);
  115451. if (!node[name]) {
  115452. throw new _exception2['default'](node.type + ' requires ' + name);
  115453. }
  115454. },
  115455. // Traverses a given array. If mutating, empty respnses will be removed
  115456. // for child elements.
  115457. acceptArray: function acceptArray(array) {
  115458. for (var i = 0, l = array.length; i < l; i++) {
  115459. this.acceptKey(array, i);
  115460. if (!array[i]) {
  115461. array.splice(i, 1);
  115462. i--;
  115463. l--;
  115464. }
  115465. }
  115466. },
  115467. accept: function accept(object) {
  115468. if (!object) {
  115469. return;
  115470. }
  115471. /* istanbul ignore next: Sanity code */
  115472. if (!this[object.type]) {
  115473. throw new _exception2['default']('Unknown type: ' + object.type, object);
  115474. }
  115475. if (this.current) {
  115476. this.parents.unshift(this.current);
  115477. }
  115478. this.current = object;
  115479. var ret = this[object.type](object);
  115480. this.current = this.parents.shift();
  115481. if (!this.mutating || ret) {
  115482. return ret;
  115483. } else if (ret !== false) {
  115484. return object;
  115485. }
  115486. },
  115487. Program: function Program(program) {
  115488. this.acceptArray(program.body);
  115489. },
  115490. MustacheStatement: visitSubExpression,
  115491. Decorator: visitSubExpression,
  115492. BlockStatement: visitBlock,
  115493. DecoratorBlock: visitBlock,
  115494. PartialStatement: visitPartial,
  115495. PartialBlockStatement: function PartialBlockStatement(partial) {
  115496. visitPartial.call(this, partial);
  115497. this.acceptKey(partial, 'program');
  115498. },
  115499. ContentStatement: function ContentStatement() /* content */{},
  115500. CommentStatement: function CommentStatement() /* comment */{},
  115501. SubExpression: visitSubExpression,
  115502. PathExpression: function PathExpression() /* path */{},
  115503. StringLiteral: function StringLiteral() /* string */{},
  115504. NumberLiteral: function NumberLiteral() /* number */{},
  115505. BooleanLiteral: function BooleanLiteral() /* bool */{},
  115506. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  115507. NullLiteral: function NullLiteral() /* literal */{},
  115508. Hash: function Hash(hash) {
  115509. this.acceptArray(hash.pairs);
  115510. },
  115511. HashPair: function HashPair(pair) {
  115512. this.acceptRequired(pair, 'value');
  115513. }
  115514. };
  115515. function visitSubExpression(mustache) {
  115516. this.acceptRequired(mustache, 'path');
  115517. this.acceptArray(mustache.params);
  115518. this.acceptKey(mustache, 'hash');
  115519. }
  115520. function visitBlock(block) {
  115521. visitSubExpression.call(this, block);
  115522. this.acceptKey(block, 'program');
  115523. this.acceptKey(block, 'inverse');
  115524. }
  115525. function visitPartial(partial) {
  115526. this.acceptRequired(partial, 'name');
  115527. this.acceptArray(partial.params);
  115528. this.acceptKey(partial, 'hash');
  115529. }
  115530. exports['default'] = Visitor;
  115531. module.exports = exports['default'];
  115532. /***/ }),
  115533. /* 40 */
  115534. /***/ (function(module, exports, __webpack_require__) {
  115535. 'use strict';
  115536. var _interopRequireDefault = __webpack_require__(1)['default'];
  115537. exports.__esModule = true;
  115538. exports.SourceLocation = SourceLocation;
  115539. exports.id = id;
  115540. exports.stripFlags = stripFlags;
  115541. exports.stripComment = stripComment;
  115542. exports.preparePath = preparePath;
  115543. exports.prepareMustache = prepareMustache;
  115544. exports.prepareRawBlock = prepareRawBlock;
  115545. exports.prepareBlock = prepareBlock;
  115546. exports.prepareProgram = prepareProgram;
  115547. exports.preparePartialBlock = preparePartialBlock;
  115548. var _exception = __webpack_require__(6);
  115549. var _exception2 = _interopRequireDefault(_exception);
  115550. function validateClose(open, close) {
  115551. close = close.path ? close.path.original : close;
  115552. if (open.path.original !== close) {
  115553. var errorNode = { loc: open.path.loc };
  115554. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  115555. }
  115556. }
  115557. function SourceLocation(source, locInfo) {
  115558. this.source = source;
  115559. this.start = {
  115560. line: locInfo.first_line,
  115561. column: locInfo.first_column
  115562. };
  115563. this.end = {
  115564. line: locInfo.last_line,
  115565. column: locInfo.last_column
  115566. };
  115567. }
  115568. function id(token) {
  115569. if (/^\[.*\]$/.test(token)) {
  115570. return token.substr(1, token.length - 2);
  115571. } else {
  115572. return token;
  115573. }
  115574. }
  115575. function stripFlags(open, close) {
  115576. return {
  115577. open: open.charAt(2) === '~',
  115578. close: close.charAt(close.length - 3) === '~'
  115579. };
  115580. }
  115581. function stripComment(comment) {
  115582. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  115583. }
  115584. function preparePath(data, parts, loc) {
  115585. loc = this.locInfo(loc);
  115586. var original = data ? '@' : '',
  115587. dig = [],
  115588. depth = 0,
  115589. depthString = '';
  115590. for (var i = 0, l = parts.length; i < l; i++) {
  115591. var part = parts[i].part,
  115592. // If we have [] syntax then we do not treat path references as operators,
  115593. // i.e. foo.[this] resolves to approximately context.foo['this']
  115594. isLiteral = parts[i].original !== part;
  115595. original += (parts[i].separator || '') + part;
  115596. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  115597. if (dig.length > 0) {
  115598. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  115599. } else if (part === '..') {
  115600. depth++;
  115601. depthString += '../';
  115602. }
  115603. } else {
  115604. dig.push(part);
  115605. }
  115606. }
  115607. return {
  115608. type: 'PathExpression',
  115609. data: data,
  115610. depth: depth,
  115611. parts: dig,
  115612. original: original,
  115613. loc: loc
  115614. };
  115615. }
  115616. function prepareMustache(path, params, hash, open, strip, locInfo) {
  115617. // Must use charAt to support IE pre-10
  115618. var escapeFlag = open.charAt(3) || open.charAt(2),
  115619. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  115620. var decorator = /\*/.test(open);
  115621. return {
  115622. type: decorator ? 'Decorator' : 'MustacheStatement',
  115623. path: path,
  115624. params: params,
  115625. hash: hash,
  115626. escaped: escaped,
  115627. strip: strip,
  115628. loc: this.locInfo(locInfo)
  115629. };
  115630. }
  115631. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  115632. validateClose(openRawBlock, close);
  115633. locInfo = this.locInfo(locInfo);
  115634. var program = {
  115635. type: 'Program',
  115636. body: contents,
  115637. strip: {},
  115638. loc: locInfo
  115639. };
  115640. return {
  115641. type: 'BlockStatement',
  115642. path: openRawBlock.path,
  115643. params: openRawBlock.params,
  115644. hash: openRawBlock.hash,
  115645. program: program,
  115646. openStrip: {},
  115647. inverseStrip: {},
  115648. closeStrip: {},
  115649. loc: locInfo
  115650. };
  115651. }
  115652. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  115653. if (close && close.path) {
  115654. validateClose(openBlock, close);
  115655. }
  115656. var decorator = /\*/.test(openBlock.open);
  115657. program.blockParams = openBlock.blockParams;
  115658. var inverse = undefined,
  115659. inverseStrip = undefined;
  115660. if (inverseAndProgram) {
  115661. if (decorator) {
  115662. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  115663. }
  115664. if (inverseAndProgram.chain) {
  115665. inverseAndProgram.program.body[0].closeStrip = close.strip;
  115666. }
  115667. inverseStrip = inverseAndProgram.strip;
  115668. inverse = inverseAndProgram.program;
  115669. }
  115670. if (inverted) {
  115671. inverted = inverse;
  115672. inverse = program;
  115673. program = inverted;
  115674. }
  115675. return {
  115676. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  115677. path: openBlock.path,
  115678. params: openBlock.params,
  115679. hash: openBlock.hash,
  115680. program: program,
  115681. inverse: inverse,
  115682. openStrip: openBlock.strip,
  115683. inverseStrip: inverseStrip,
  115684. closeStrip: close && close.strip,
  115685. loc: this.locInfo(locInfo)
  115686. };
  115687. }
  115688. function prepareProgram(statements, loc) {
  115689. if (!loc && statements.length) {
  115690. var firstLoc = statements[0].loc,
  115691. lastLoc = statements[statements.length - 1].loc;
  115692. /* istanbul ignore else */
  115693. if (firstLoc && lastLoc) {
  115694. loc = {
  115695. source: firstLoc.source,
  115696. start: {
  115697. line: firstLoc.start.line,
  115698. column: firstLoc.start.column
  115699. },
  115700. end: {
  115701. line: lastLoc.end.line,
  115702. column: lastLoc.end.column
  115703. }
  115704. };
  115705. }
  115706. }
  115707. return {
  115708. type: 'Program',
  115709. body: statements,
  115710. strip: {},
  115711. loc: loc
  115712. };
  115713. }
  115714. function preparePartialBlock(open, program, close, locInfo) {
  115715. validateClose(open, close);
  115716. return {
  115717. type: 'PartialBlockStatement',
  115718. name: open.path,
  115719. params: open.params,
  115720. hash: open.hash,
  115721. program: program,
  115722. openStrip: open.strip,
  115723. closeStrip: close && close.strip,
  115724. loc: this.locInfo(locInfo)
  115725. };
  115726. }
  115727. /***/ }),
  115728. /* 41 */
  115729. /***/ (function(module, exports, __webpack_require__) {
  115730. /* eslint-disable new-cap */
  115731. 'use strict';
  115732. var _interopRequireDefault = __webpack_require__(1)['default'];
  115733. exports.__esModule = true;
  115734. exports.Compiler = Compiler;
  115735. exports.precompile = precompile;
  115736. exports.compile = compile;
  115737. var _exception = __webpack_require__(6);
  115738. var _exception2 = _interopRequireDefault(_exception);
  115739. var _utils = __webpack_require__(5);
  115740. var _ast = __webpack_require__(35);
  115741. var _ast2 = _interopRequireDefault(_ast);
  115742. var slice = [].slice;
  115743. function Compiler() {}
  115744. // the foundHelper register will disambiguate helper lookup from finding a
  115745. // function in a context. This is necessary for mustache compatibility, which
  115746. // requires that context functions in blocks are evaluated by blockHelperMissing,
  115747. // and then proceed as if the resulting value was provided to blockHelperMissing.
  115748. Compiler.prototype = {
  115749. compiler: Compiler,
  115750. equals: function equals(other) {
  115751. var len = this.opcodes.length;
  115752. if (other.opcodes.length !== len) {
  115753. return false;
  115754. }
  115755. for (var i = 0; i < len; i++) {
  115756. var opcode = this.opcodes[i],
  115757. otherOpcode = other.opcodes[i];
  115758. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  115759. return false;
  115760. }
  115761. }
  115762. // We know that length is the same between the two arrays because they are directly tied
  115763. // to the opcode behavior above.
  115764. len = this.children.length;
  115765. for (var i = 0; i < len; i++) {
  115766. if (!this.children[i].equals(other.children[i])) {
  115767. return false;
  115768. }
  115769. }
  115770. return true;
  115771. },
  115772. guid: 0,
  115773. compile: function compile(program, options) {
  115774. this.sourceNode = [];
  115775. this.opcodes = [];
  115776. this.children = [];
  115777. this.options = options;
  115778. this.stringParams = options.stringParams;
  115779. this.trackIds = options.trackIds;
  115780. options.blockParams = options.blockParams || [];
  115781. // These changes will propagate to the other compiler components
  115782. var knownHelpers = options.knownHelpers;
  115783. options.knownHelpers = {
  115784. 'helperMissing': true,
  115785. 'blockHelperMissing': true,
  115786. 'each': true,
  115787. 'if': true,
  115788. 'unless': true,
  115789. 'with': true,
  115790. 'log': true,
  115791. 'lookup': true
  115792. };
  115793. if (knownHelpers) {
  115794. for (var _name in knownHelpers) {
  115795. /* istanbul ignore else */
  115796. if (_name in knownHelpers) {
  115797. this.options.knownHelpers[_name] = knownHelpers[_name];
  115798. }
  115799. }
  115800. }
  115801. return this.accept(program);
  115802. },
  115803. compileProgram: function compileProgram(program) {
  115804. var childCompiler = new this.compiler(),
  115805. // eslint-disable-line new-cap
  115806. result = childCompiler.compile(program, this.options),
  115807. guid = this.guid++;
  115808. this.usePartial = this.usePartial || result.usePartial;
  115809. this.children[guid] = result;
  115810. this.useDepths = this.useDepths || result.useDepths;
  115811. return guid;
  115812. },
  115813. accept: function accept(node) {
  115814. /* istanbul ignore next: Sanity code */
  115815. if (!this[node.type]) {
  115816. throw new _exception2['default']('Unknown type: ' + node.type, node);
  115817. }
  115818. this.sourceNode.unshift(node);
  115819. var ret = this[node.type](node);
  115820. this.sourceNode.shift();
  115821. return ret;
  115822. },
  115823. Program: function Program(program) {
  115824. this.options.blockParams.unshift(program.blockParams);
  115825. var body = program.body,
  115826. bodyLength = body.length;
  115827. for (var i = 0; i < bodyLength; i++) {
  115828. this.accept(body[i]);
  115829. }
  115830. this.options.blockParams.shift();
  115831. this.isSimple = bodyLength === 1;
  115832. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  115833. return this;
  115834. },
  115835. BlockStatement: function BlockStatement(block) {
  115836. transformLiteralToPath(block);
  115837. var program = block.program,
  115838. inverse = block.inverse;
  115839. program = program && this.compileProgram(program);
  115840. inverse = inverse && this.compileProgram(inverse);
  115841. var type = this.classifySexpr(block);
  115842. if (type === 'helper') {
  115843. this.helperSexpr(block, program, inverse);
  115844. } else if (type === 'simple') {
  115845. this.simpleSexpr(block);
  115846. // now that the simple mustache is resolved, we need to
  115847. // evaluate it by executing `blockHelperMissing`
  115848. this.opcode('pushProgram', program);
  115849. this.opcode('pushProgram', inverse);
  115850. this.opcode('emptyHash');
  115851. this.opcode('blockValue', block.path.original);
  115852. } else {
  115853. this.ambiguousSexpr(block, program, inverse);
  115854. // now that the simple mustache is resolved, we need to
  115855. // evaluate it by executing `blockHelperMissing`
  115856. this.opcode('pushProgram', program);
  115857. this.opcode('pushProgram', inverse);
  115858. this.opcode('emptyHash');
  115859. this.opcode('ambiguousBlockValue');
  115860. }
  115861. this.opcode('append');
  115862. },
  115863. DecoratorBlock: function DecoratorBlock(decorator) {
  115864. var program = decorator.program && this.compileProgram(decorator.program);
  115865. var params = this.setupFullMustacheParams(decorator, program, undefined),
  115866. path = decorator.path;
  115867. this.useDecorators = true;
  115868. this.opcode('registerDecorator', params.length, path.original);
  115869. },
  115870. PartialStatement: function PartialStatement(partial) {
  115871. this.usePartial = true;
  115872. var program = partial.program;
  115873. if (program) {
  115874. program = this.compileProgram(partial.program);
  115875. }
  115876. var params = partial.params;
  115877. if (params.length > 1) {
  115878. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  115879. } else if (!params.length) {
  115880. if (this.options.explicitPartialContext) {
  115881. this.opcode('pushLiteral', 'undefined');
  115882. } else {
  115883. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  115884. }
  115885. }
  115886. var partialName = partial.name.original,
  115887. isDynamic = partial.name.type === 'SubExpression';
  115888. if (isDynamic) {
  115889. this.accept(partial.name);
  115890. }
  115891. this.setupFullMustacheParams(partial, program, undefined, true);
  115892. var indent = partial.indent || '';
  115893. if (this.options.preventIndent && indent) {
  115894. this.opcode('appendContent', indent);
  115895. indent = '';
  115896. }
  115897. this.opcode('invokePartial', isDynamic, partialName, indent);
  115898. this.opcode('append');
  115899. },
  115900. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  115901. this.PartialStatement(partialBlock);
  115902. },
  115903. MustacheStatement: function MustacheStatement(mustache) {
  115904. this.SubExpression(mustache);
  115905. if (mustache.escaped && !this.options.noEscape) {
  115906. this.opcode('appendEscaped');
  115907. } else {
  115908. this.opcode('append');
  115909. }
  115910. },
  115911. Decorator: function Decorator(decorator) {
  115912. this.DecoratorBlock(decorator);
  115913. },
  115914. ContentStatement: function ContentStatement(content) {
  115915. if (content.value) {
  115916. this.opcode('appendContent', content.value);
  115917. }
  115918. },
  115919. CommentStatement: function CommentStatement() {},
  115920. SubExpression: function SubExpression(sexpr) {
  115921. transformLiteralToPath(sexpr);
  115922. var type = this.classifySexpr(sexpr);
  115923. if (type === 'simple') {
  115924. this.simpleSexpr(sexpr);
  115925. } else if (type === 'helper') {
  115926. this.helperSexpr(sexpr);
  115927. } else {
  115928. this.ambiguousSexpr(sexpr);
  115929. }
  115930. },
  115931. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  115932. var path = sexpr.path,
  115933. name = path.parts[0],
  115934. isBlock = program != null || inverse != null;
  115935. this.opcode('getContext', path.depth);
  115936. this.opcode('pushProgram', program);
  115937. this.opcode('pushProgram', inverse);
  115938. path.strict = true;
  115939. this.accept(path);
  115940. this.opcode('invokeAmbiguous', name, isBlock);
  115941. },
  115942. simpleSexpr: function simpleSexpr(sexpr) {
  115943. var path = sexpr.path;
  115944. path.strict = true;
  115945. this.accept(path);
  115946. this.opcode('resolvePossibleLambda');
  115947. },
  115948. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  115949. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  115950. path = sexpr.path,
  115951. name = path.parts[0];
  115952. if (this.options.knownHelpers[name]) {
  115953. this.opcode('invokeKnownHelper', params.length, name);
  115954. } else if (this.options.knownHelpersOnly) {
  115955. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  115956. } else {
  115957. path.strict = true;
  115958. path.falsy = true;
  115959. this.accept(path);
  115960. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  115961. }
  115962. },
  115963. PathExpression: function PathExpression(path) {
  115964. this.addDepth(path.depth);
  115965. this.opcode('getContext', path.depth);
  115966. var name = path.parts[0],
  115967. scoped = _ast2['default'].helpers.scopedId(path),
  115968. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  115969. if (blockParamId) {
  115970. this.opcode('lookupBlockParam', blockParamId, path.parts);
  115971. } else if (!name) {
  115972. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  115973. this.opcode('pushContext');
  115974. } else if (path.data) {
  115975. this.options.data = true;
  115976. this.opcode('lookupData', path.depth, path.parts, path.strict);
  115977. } else {
  115978. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  115979. }
  115980. },
  115981. StringLiteral: function StringLiteral(string) {
  115982. this.opcode('pushString', string.value);
  115983. },
  115984. NumberLiteral: function NumberLiteral(number) {
  115985. this.opcode('pushLiteral', number.value);
  115986. },
  115987. BooleanLiteral: function BooleanLiteral(bool) {
  115988. this.opcode('pushLiteral', bool.value);
  115989. },
  115990. UndefinedLiteral: function UndefinedLiteral() {
  115991. this.opcode('pushLiteral', 'undefined');
  115992. },
  115993. NullLiteral: function NullLiteral() {
  115994. this.opcode('pushLiteral', 'null');
  115995. },
  115996. Hash: function Hash(hash) {
  115997. var pairs = hash.pairs,
  115998. i = 0,
  115999. l = pairs.length;
  116000. this.opcode('pushHash');
  116001. for (; i < l; i++) {
  116002. this.pushParam(pairs[i].value);
  116003. }
  116004. while (i--) {
  116005. this.opcode('assignToHash', pairs[i].key);
  116006. }
  116007. this.opcode('popHash');
  116008. },
  116009. // HELPERS
  116010. opcode: function opcode(name) {
  116011. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  116012. },
  116013. addDepth: function addDepth(depth) {
  116014. if (!depth) {
  116015. return;
  116016. }
  116017. this.useDepths = true;
  116018. },
  116019. classifySexpr: function classifySexpr(sexpr) {
  116020. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  116021. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  116022. // a mustache is an eligible helper if:
  116023. // * its id is simple (a single part, not `this` or `..`)
  116024. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  116025. // if a mustache is an eligible helper but not a definite
  116026. // helper, it is ambiguous, and will be resolved in a later
  116027. // pass or at runtime.
  116028. var isEligible = !isBlockParam && (isHelper || isSimple);
  116029. // if ambiguous, we can possibly resolve the ambiguity now
  116030. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  116031. if (isEligible && !isHelper) {
  116032. var _name2 = sexpr.path.parts[0],
  116033. options = this.options;
  116034. if (options.knownHelpers[_name2]) {
  116035. isHelper = true;
  116036. } else if (options.knownHelpersOnly) {
  116037. isEligible = false;
  116038. }
  116039. }
  116040. if (isHelper) {
  116041. return 'helper';
  116042. } else if (isEligible) {
  116043. return 'ambiguous';
  116044. } else {
  116045. return 'simple';
  116046. }
  116047. },
  116048. pushParams: function pushParams(params) {
  116049. for (var i = 0, l = params.length; i < l; i++) {
  116050. this.pushParam(params[i]);
  116051. }
  116052. },
  116053. pushParam: function pushParam(val) {
  116054. var value = val.value != null ? val.value : val.original || '';
  116055. if (this.stringParams) {
  116056. if (value.replace) {
  116057. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  116058. }
  116059. if (val.depth) {
  116060. this.addDepth(val.depth);
  116061. }
  116062. this.opcode('getContext', val.depth || 0);
  116063. this.opcode('pushStringParam', value, val.type);
  116064. if (val.type === 'SubExpression') {
  116065. // SubExpressions get evaluated and passed in
  116066. // in string params mode.
  116067. this.accept(val);
  116068. }
  116069. } else {
  116070. if (this.trackIds) {
  116071. var blockParamIndex = undefined;
  116072. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  116073. blockParamIndex = this.blockParamIndex(val.parts[0]);
  116074. }
  116075. if (blockParamIndex) {
  116076. var blockParamChild = val.parts.slice(1).join('.');
  116077. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  116078. } else {
  116079. value = val.original || value;
  116080. if (value.replace) {
  116081. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  116082. }
  116083. this.opcode('pushId', val.type, value);
  116084. }
  116085. }
  116086. this.accept(val);
  116087. }
  116088. },
  116089. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  116090. var params = sexpr.params;
  116091. this.pushParams(params);
  116092. this.opcode('pushProgram', program);
  116093. this.opcode('pushProgram', inverse);
  116094. if (sexpr.hash) {
  116095. this.accept(sexpr.hash);
  116096. } else {
  116097. this.opcode('emptyHash', omitEmpty);
  116098. }
  116099. return params;
  116100. },
  116101. blockParamIndex: function blockParamIndex(name) {
  116102. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  116103. var blockParams = this.options.blockParams[depth],
  116104. param = blockParams && _utils.indexOf(blockParams, name);
  116105. if (blockParams && param >= 0) {
  116106. return [depth, param];
  116107. }
  116108. }
  116109. }
  116110. };
  116111. function precompile(input, options, env) {
  116112. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  116113. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  116114. }
  116115. options = options || {};
  116116. if (!('data' in options)) {
  116117. options.data = true;
  116118. }
  116119. if (options.compat) {
  116120. options.useDepths = true;
  116121. }
  116122. var ast = env.parse(input, options),
  116123. environment = new env.Compiler().compile(ast, options);
  116124. return new env.JavaScriptCompiler().compile(environment, options);
  116125. }
  116126. function compile(input, options, env) {
  116127. if (options === undefined) options = {};
  116128. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  116129. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  116130. }
  116131. options = _utils.extend({}, options);
  116132. if (!('data' in options)) {
  116133. options.data = true;
  116134. }
  116135. if (options.compat) {
  116136. options.useDepths = true;
  116137. }
  116138. var compiled = undefined;
  116139. function compileInput() {
  116140. var ast = env.parse(input, options),
  116141. environment = new env.Compiler().compile(ast, options),
  116142. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  116143. return env.template(templateSpec);
  116144. }
  116145. // Template is only compiled on first use and cached after that point.
  116146. function ret(context, execOptions) {
  116147. if (!compiled) {
  116148. compiled = compileInput();
  116149. }
  116150. return compiled.call(this, context, execOptions);
  116151. }
  116152. ret._setup = function (setupOptions) {
  116153. if (!compiled) {
  116154. compiled = compileInput();
  116155. }
  116156. return compiled._setup(setupOptions);
  116157. };
  116158. ret._child = function (i, data, blockParams, depths) {
  116159. if (!compiled) {
  116160. compiled = compileInput();
  116161. }
  116162. return compiled._child(i, data, blockParams, depths);
  116163. };
  116164. return ret;
  116165. }
  116166. function argEquals(a, b) {
  116167. if (a === b) {
  116168. return true;
  116169. }
  116170. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  116171. for (var i = 0; i < a.length; i++) {
  116172. if (!argEquals(a[i], b[i])) {
  116173. return false;
  116174. }
  116175. }
  116176. return true;
  116177. }
  116178. }
  116179. function transformLiteralToPath(sexpr) {
  116180. if (!sexpr.path.parts) {
  116181. var literal = sexpr.path;
  116182. // Casting to string here to make false and 0 literal values play nicely with the rest
  116183. // of the system.
  116184. sexpr.path = {
  116185. type: 'PathExpression',
  116186. data: false,
  116187. depth: 0,
  116188. parts: [literal.original + ''],
  116189. original: literal.original + '',
  116190. loc: literal.loc
  116191. };
  116192. }
  116193. }
  116194. /***/ }),
  116195. /* 42 */
  116196. /***/ (function(module, exports, __webpack_require__) {
  116197. 'use strict';
  116198. var _interopRequireDefault = __webpack_require__(1)['default'];
  116199. exports.__esModule = true;
  116200. var _base = __webpack_require__(4);
  116201. var _exception = __webpack_require__(6);
  116202. var _exception2 = _interopRequireDefault(_exception);
  116203. var _utils = __webpack_require__(5);
  116204. var _codeGen = __webpack_require__(43);
  116205. var _codeGen2 = _interopRequireDefault(_codeGen);
  116206. function Literal(value) {
  116207. this.value = value;
  116208. }
  116209. function JavaScriptCompiler() {}
  116210. JavaScriptCompiler.prototype = {
  116211. // PUBLIC API: You can override these methods in a subclass to provide
  116212. // alternative compiled forms for name lookup and buffering semantics
  116213. nameLookup: function nameLookup(parent, name /* , type*/) {
  116214. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  116215. return [parent, '.', name];
  116216. } else {
  116217. return [parent, '[', JSON.stringify(name), ']'];
  116218. }
  116219. },
  116220. depthedLookup: function depthedLookup(name) {
  116221. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  116222. },
  116223. compilerInfo: function compilerInfo() {
  116224. var revision = _base.COMPILER_REVISION,
  116225. versions = _base.REVISION_CHANGES[revision];
  116226. return [revision, versions];
  116227. },
  116228. appendToBuffer: function appendToBuffer(source, location, explicit) {
  116229. // Force a source as this simplifies the merge logic.
  116230. if (!_utils.isArray(source)) {
  116231. source = [source];
  116232. }
  116233. source = this.source.wrap(source, location);
  116234. if (this.environment.isSimple) {
  116235. return ['return ', source, ';'];
  116236. } else if (explicit) {
  116237. // This is a case where the buffer operation occurs as a child of another
  116238. // construct, generally braces. We have to explicitly output these buffer
  116239. // operations to ensure that the emitted code goes in the correct location.
  116240. return ['buffer += ', source, ';'];
  116241. } else {
  116242. source.appendToBuffer = true;
  116243. return source;
  116244. }
  116245. },
  116246. initializeBuffer: function initializeBuffer() {
  116247. return this.quotedString('');
  116248. },
  116249. // END PUBLIC API
  116250. compile: function compile(environment, options, context, asObject) {
  116251. this.environment = environment;
  116252. this.options = options;
  116253. this.stringParams = this.options.stringParams;
  116254. this.trackIds = this.options.trackIds;
  116255. this.precompile = !asObject;
  116256. this.name = this.environment.name;
  116257. this.isChild = !!context;
  116258. this.context = context || {
  116259. decorators: [],
  116260. programs: [],
  116261. environments: []
  116262. };
  116263. this.preamble();
  116264. this.stackSlot = 0;
  116265. this.stackVars = [];
  116266. this.aliases = {};
  116267. this.registers = { list: [] };
  116268. this.hashes = [];
  116269. this.compileStack = [];
  116270. this.inlineStack = [];
  116271. this.blockParams = [];
  116272. this.compileChildren(environment, options);
  116273. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  116274. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  116275. var opcodes = environment.opcodes,
  116276. opcode = undefined,
  116277. firstLoc = undefined,
  116278. i = undefined,
  116279. l = undefined;
  116280. for (i = 0, l = opcodes.length; i < l; i++) {
  116281. opcode = opcodes[i];
  116282. this.source.currentLocation = opcode.loc;
  116283. firstLoc = firstLoc || opcode.loc;
  116284. this[opcode.opcode].apply(this, opcode.args);
  116285. }
  116286. // Flush any trailing content that might be pending.
  116287. this.source.currentLocation = firstLoc;
  116288. this.pushSource('');
  116289. /* istanbul ignore next */
  116290. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  116291. throw new _exception2['default']('Compile completed with content left on stack');
  116292. }
  116293. if (!this.decorators.isEmpty()) {
  116294. this.useDecorators = true;
  116295. this.decorators.prepend('var decorators = container.decorators;\n');
  116296. this.decorators.push('return fn;');
  116297. if (asObject) {
  116298. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  116299. } else {
  116300. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  116301. this.decorators.push('}\n');
  116302. this.decorators = this.decorators.merge();
  116303. }
  116304. } else {
  116305. this.decorators = undefined;
  116306. }
  116307. var fn = this.createFunctionContext(asObject);
  116308. if (!this.isChild) {
  116309. var ret = {
  116310. compiler: this.compilerInfo(),
  116311. main: fn
  116312. };
  116313. if (this.decorators) {
  116314. ret.main_d = this.decorators; // eslint-disable-line camelcase
  116315. ret.useDecorators = true;
  116316. }
  116317. var _context = this.context;
  116318. var programs = _context.programs;
  116319. var decorators = _context.decorators;
  116320. for (i = 0, l = programs.length; i < l; i++) {
  116321. if (programs[i]) {
  116322. ret[i] = programs[i];
  116323. if (decorators[i]) {
  116324. ret[i + '_d'] = decorators[i];
  116325. ret.useDecorators = true;
  116326. }
  116327. }
  116328. }
  116329. if (this.environment.usePartial) {
  116330. ret.usePartial = true;
  116331. }
  116332. if (this.options.data) {
  116333. ret.useData = true;
  116334. }
  116335. if (this.useDepths) {
  116336. ret.useDepths = true;
  116337. }
  116338. if (this.useBlockParams) {
  116339. ret.useBlockParams = true;
  116340. }
  116341. if (this.options.compat) {
  116342. ret.compat = true;
  116343. }
  116344. if (!asObject) {
  116345. ret.compiler = JSON.stringify(ret.compiler);
  116346. this.source.currentLocation = { start: { line: 1, column: 0 } };
  116347. ret = this.objectLiteral(ret);
  116348. if (options.srcName) {
  116349. ret = ret.toStringWithSourceMap({ file: options.destName });
  116350. ret.map = ret.map && ret.map.toString();
  116351. } else {
  116352. ret = ret.toString();
  116353. }
  116354. } else {
  116355. ret.compilerOptions = this.options;
  116356. }
  116357. return ret;
  116358. } else {
  116359. return fn;
  116360. }
  116361. },
  116362. preamble: function preamble() {
  116363. // track the last context pushed into place to allow skipping the
  116364. // getContext opcode when it would be a noop
  116365. this.lastContext = 0;
  116366. this.source = new _codeGen2['default'](this.options.srcName);
  116367. this.decorators = new _codeGen2['default'](this.options.srcName);
  116368. },
  116369. createFunctionContext: function createFunctionContext(asObject) {
  116370. var varDeclarations = '';
  116371. var locals = this.stackVars.concat(this.registers.list);
  116372. if (locals.length > 0) {
  116373. varDeclarations += ', ' + locals.join(', ');
  116374. }
  116375. // Generate minimizer alias mappings
  116376. //
  116377. // When using true SourceNodes, this will update all references to the given alias
  116378. // as the source nodes are reused in situ. For the non-source node compilation mode,
  116379. // aliases will not be used, but this case is already being run on the client and
  116380. // we aren't concern about minimizing the template size.
  116381. var aliasCount = 0;
  116382. for (var alias in this.aliases) {
  116383. // eslint-disable-line guard-for-in
  116384. var node = this.aliases[alias];
  116385. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  116386. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  116387. node.children[0] = 'alias' + aliasCount;
  116388. }
  116389. }
  116390. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  116391. if (this.useBlockParams || this.useDepths) {
  116392. params.push('blockParams');
  116393. }
  116394. if (this.useDepths) {
  116395. params.push('depths');
  116396. }
  116397. // Perform a second pass over the output to merge content when possible
  116398. var source = this.mergeSource(varDeclarations);
  116399. if (asObject) {
  116400. params.push(source);
  116401. return Function.apply(this, params);
  116402. } else {
  116403. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  116404. }
  116405. },
  116406. mergeSource: function mergeSource(varDeclarations) {
  116407. var isSimple = this.environment.isSimple,
  116408. appendOnly = !this.forceBuffer,
  116409. appendFirst = undefined,
  116410. sourceSeen = undefined,
  116411. bufferStart = undefined,
  116412. bufferEnd = undefined;
  116413. this.source.each(function (line) {
  116414. if (line.appendToBuffer) {
  116415. if (bufferStart) {
  116416. line.prepend(' + ');
  116417. } else {
  116418. bufferStart = line;
  116419. }
  116420. bufferEnd = line;
  116421. } else {
  116422. if (bufferStart) {
  116423. if (!sourceSeen) {
  116424. appendFirst = true;
  116425. } else {
  116426. bufferStart.prepend('buffer += ');
  116427. }
  116428. bufferEnd.add(';');
  116429. bufferStart = bufferEnd = undefined;
  116430. }
  116431. sourceSeen = true;
  116432. if (!isSimple) {
  116433. appendOnly = false;
  116434. }
  116435. }
  116436. });
  116437. if (appendOnly) {
  116438. if (bufferStart) {
  116439. bufferStart.prepend('return ');
  116440. bufferEnd.add(';');
  116441. } else if (!sourceSeen) {
  116442. this.source.push('return "";');
  116443. }
  116444. } else {
  116445. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  116446. if (bufferStart) {
  116447. bufferStart.prepend('return buffer + ');
  116448. bufferEnd.add(';');
  116449. } else {
  116450. this.source.push('return buffer;');
  116451. }
  116452. }
  116453. if (varDeclarations) {
  116454. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  116455. }
  116456. return this.source.merge();
  116457. },
  116458. // [blockValue]
  116459. //
  116460. // On stack, before: hash, inverse, program, value
  116461. // On stack, after: return value of blockHelperMissing
  116462. //
  116463. // The purpose of this opcode is to take a block of the form
  116464. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  116465. // replace it on the stack with the result of properly
  116466. // invoking blockHelperMissing.
  116467. blockValue: function blockValue(name) {
  116468. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  116469. params = [this.contextName(0)];
  116470. this.setupHelperArgs(name, 0, params);
  116471. var blockName = this.popStack();
  116472. params.splice(1, 0, blockName);
  116473. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  116474. },
  116475. // [ambiguousBlockValue]
  116476. //
  116477. // On stack, before: hash, inverse, program, value
  116478. // Compiler value, before: lastHelper=value of last found helper, if any
  116479. // On stack, after, if no lastHelper: same as [blockValue]
  116480. // On stack, after, if lastHelper: value
  116481. ambiguousBlockValue: function ambiguousBlockValue() {
  116482. // We're being a bit cheeky and reusing the options value from the prior exec
  116483. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  116484. params = [this.contextName(0)];
  116485. this.setupHelperArgs('', 0, params, true);
  116486. this.flushInline();
  116487. var current = this.topStack();
  116488. params.splice(1, 0, current);
  116489. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  116490. },
  116491. // [appendContent]
  116492. //
  116493. // On stack, before: ...
  116494. // On stack, after: ...
  116495. //
  116496. // Appends the string value of `content` to the current buffer
  116497. appendContent: function appendContent(content) {
  116498. if (this.pendingContent) {
  116499. content = this.pendingContent + content;
  116500. } else {
  116501. this.pendingLocation = this.source.currentLocation;
  116502. }
  116503. this.pendingContent = content;
  116504. },
  116505. // [append]
  116506. //
  116507. // On stack, before: value, ...
  116508. // On stack, after: ...
  116509. //
  116510. // Coerces `value` to a String and appends it to the current buffer.
  116511. //
  116512. // If `value` is truthy, or 0, it is coerced into a string and appended
  116513. // Otherwise, the empty string is appended
  116514. append: function append() {
  116515. if (this.isInline()) {
  116516. this.replaceStack(function (current) {
  116517. return [' != null ? ', current, ' : ""'];
  116518. });
  116519. this.pushSource(this.appendToBuffer(this.popStack()));
  116520. } else {
  116521. var local = this.popStack();
  116522. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  116523. if (this.environment.isSimple) {
  116524. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  116525. }
  116526. }
  116527. },
  116528. // [appendEscaped]
  116529. //
  116530. // On stack, before: value, ...
  116531. // On stack, after: ...
  116532. //
  116533. // Escape `value` and append it to the buffer
  116534. appendEscaped: function appendEscaped() {
  116535. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  116536. },
  116537. // [getContext]
  116538. //
  116539. // On stack, before: ...
  116540. // On stack, after: ...
  116541. // Compiler value, after: lastContext=depth
  116542. //
  116543. // Set the value of the `lastContext` compiler value to the depth
  116544. getContext: function getContext(depth) {
  116545. this.lastContext = depth;
  116546. },
  116547. // [pushContext]
  116548. //
  116549. // On stack, before: ...
  116550. // On stack, after: currentContext, ...
  116551. //
  116552. // Pushes the value of the current context onto the stack.
  116553. pushContext: function pushContext() {
  116554. this.pushStackLiteral(this.contextName(this.lastContext));
  116555. },
  116556. // [lookupOnContext]
  116557. //
  116558. // On stack, before: ...
  116559. // On stack, after: currentContext[name], ...
  116560. //
  116561. // Looks up the value of `name` on the current context and pushes
  116562. // it onto the stack.
  116563. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  116564. var i = 0;
  116565. if (!scoped && this.options.compat && !this.lastContext) {
  116566. // The depthed query is expected to handle the undefined logic for the root level that
  116567. // is implemented below, so we evaluate that directly in compat mode
  116568. this.push(this.depthedLookup(parts[i++]));
  116569. } else {
  116570. this.pushContext();
  116571. }
  116572. this.resolvePath('context', parts, i, falsy, strict);
  116573. },
  116574. // [lookupBlockParam]
  116575. //
  116576. // On stack, before: ...
  116577. // On stack, after: blockParam[name], ...
  116578. //
  116579. // Looks up the value of `parts` on the given block param and pushes
  116580. // it onto the stack.
  116581. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  116582. this.useBlockParams = true;
  116583. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  116584. this.resolvePath('context', parts, 1);
  116585. },
  116586. // [lookupData]
  116587. //
  116588. // On stack, before: ...
  116589. // On stack, after: data, ...
  116590. //
  116591. // Push the data lookup operator
  116592. lookupData: function lookupData(depth, parts, strict) {
  116593. if (!depth) {
  116594. this.pushStackLiteral('data');
  116595. } else {
  116596. this.pushStackLiteral('container.data(data, ' + depth + ')');
  116597. }
  116598. this.resolvePath('data', parts, 0, true, strict);
  116599. },
  116600. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  116601. // istanbul ignore next
  116602. var _this = this;
  116603. if (this.options.strict || this.options.assumeObjects) {
  116604. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  116605. return;
  116606. }
  116607. var len = parts.length;
  116608. for (; i < len; i++) {
  116609. /* eslint-disable no-loop-func */
  116610. this.replaceStack(function (current) {
  116611. var lookup = _this.nameLookup(current, parts[i], type);
  116612. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  116613. // needs to have the special handling for these values.
  116614. if (!falsy) {
  116615. return [' != null ? ', lookup, ' : ', current];
  116616. } else {
  116617. // Otherwise we can use generic falsy handling
  116618. return [' && ', lookup];
  116619. }
  116620. });
  116621. /* eslint-enable no-loop-func */
  116622. }
  116623. },
  116624. // [resolvePossibleLambda]
  116625. //
  116626. // On stack, before: value, ...
  116627. // On stack, after: resolved value, ...
  116628. //
  116629. // If the `value` is a lambda, replace it on the stack by
  116630. // the return value of the lambda
  116631. resolvePossibleLambda: function resolvePossibleLambda() {
  116632. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  116633. },
  116634. // [pushStringParam]
  116635. //
  116636. // On stack, before: ...
  116637. // On stack, after: string, currentContext, ...
  116638. //
  116639. // This opcode is designed for use in string mode, which
  116640. // provides the string value of a parameter along with its
  116641. // depth rather than resolving it immediately.
  116642. pushStringParam: function pushStringParam(string, type) {
  116643. this.pushContext();
  116644. this.pushString(type);
  116645. // If it's a subexpression, the string result
  116646. // will be pushed after this opcode.
  116647. if (type !== 'SubExpression') {
  116648. if (typeof string === 'string') {
  116649. this.pushString(string);
  116650. } else {
  116651. this.pushStackLiteral(string);
  116652. }
  116653. }
  116654. },
  116655. emptyHash: function emptyHash(omitEmpty) {
  116656. if (this.trackIds) {
  116657. this.push('{}'); // hashIds
  116658. }
  116659. if (this.stringParams) {
  116660. this.push('{}'); // hashContexts
  116661. this.push('{}'); // hashTypes
  116662. }
  116663. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  116664. },
  116665. pushHash: function pushHash() {
  116666. if (this.hash) {
  116667. this.hashes.push(this.hash);
  116668. }
  116669. this.hash = { values: [], types: [], contexts: [], ids: [] };
  116670. },
  116671. popHash: function popHash() {
  116672. var hash = this.hash;
  116673. this.hash = this.hashes.pop();
  116674. if (this.trackIds) {
  116675. this.push(this.objectLiteral(hash.ids));
  116676. }
  116677. if (this.stringParams) {
  116678. this.push(this.objectLiteral(hash.contexts));
  116679. this.push(this.objectLiteral(hash.types));
  116680. }
  116681. this.push(this.objectLiteral(hash.values));
  116682. },
  116683. // [pushString]
  116684. //
  116685. // On stack, before: ...
  116686. // On stack, after: quotedString(string), ...
  116687. //
  116688. // Push a quoted version of `string` onto the stack
  116689. pushString: function pushString(string) {
  116690. this.pushStackLiteral(this.quotedString(string));
  116691. },
  116692. // [pushLiteral]
  116693. //
  116694. // On stack, before: ...
  116695. // On stack, after: value, ...
  116696. //
  116697. // Pushes a value onto the stack. This operation prevents
  116698. // the compiler from creating a temporary variable to hold
  116699. // it.
  116700. pushLiteral: function pushLiteral(value) {
  116701. this.pushStackLiteral(value);
  116702. },
  116703. // [pushProgram]
  116704. //
  116705. // On stack, before: ...
  116706. // On stack, after: program(guid), ...
  116707. //
  116708. // Push a program expression onto the stack. This takes
  116709. // a compile-time guid and converts it into a runtime-accessible
  116710. // expression.
  116711. pushProgram: function pushProgram(guid) {
  116712. if (guid != null) {
  116713. this.pushStackLiteral(this.programExpression(guid));
  116714. } else {
  116715. this.pushStackLiteral(null);
  116716. }
  116717. },
  116718. // [registerDecorator]
  116719. //
  116720. // On stack, before: hash, program, params..., ...
  116721. // On stack, after: ...
  116722. //
  116723. // Pops off the decorator's parameters, invokes the decorator,
  116724. // and inserts the decorator into the decorators list.
  116725. registerDecorator: function registerDecorator(paramSize, name) {
  116726. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  116727. options = this.setupHelperArgs(name, paramSize);
  116728. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  116729. },
  116730. // [invokeHelper]
  116731. //
  116732. // On stack, before: hash, inverse, program, params..., ...
  116733. // On stack, after: result of helper invocation
  116734. //
  116735. // Pops off the helper's parameters, invokes the helper,
  116736. // and pushes the helper's return value onto the stack.
  116737. //
  116738. // If the helper is not found, `helperMissing` is called.
  116739. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  116740. var nonHelper = this.popStack(),
  116741. helper = this.setupHelper(paramSize, name),
  116742. simple = isSimple ? [helper.name, ' || '] : '';
  116743. var lookup = ['('].concat(simple, nonHelper);
  116744. if (!this.options.strict) {
  116745. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  116746. }
  116747. lookup.push(')');
  116748. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  116749. },
  116750. // [invokeKnownHelper]
  116751. //
  116752. // On stack, before: hash, inverse, program, params..., ...
  116753. // On stack, after: result of helper invocation
  116754. //
  116755. // This operation is used when the helper is known to exist,
  116756. // so a `helperMissing` fallback is not required.
  116757. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  116758. var helper = this.setupHelper(paramSize, name);
  116759. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  116760. },
  116761. // [invokeAmbiguous]
  116762. //
  116763. // On stack, before: hash, inverse, program, params..., ...
  116764. // On stack, after: result of disambiguation
  116765. //
  116766. // This operation is used when an expression like `{{foo}}`
  116767. // is provided, but we don't know at compile-time whether it
  116768. // is a helper or a path.
  116769. //
  116770. // This operation emits more code than the other options,
  116771. // and can be avoided by passing the `knownHelpers` and
  116772. // `knownHelpersOnly` flags at compile-time.
  116773. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  116774. this.useRegister('helper');
  116775. var nonHelper = this.popStack();
  116776. this.emptyHash();
  116777. var helper = this.setupHelper(0, name, helperCall);
  116778. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  116779. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  116780. if (!this.options.strict) {
  116781. lookup[0] = '(helper = ';
  116782. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  116783. }
  116784. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  116785. },
  116786. // [invokePartial]
  116787. //
  116788. // On stack, before: context, ...
  116789. // On stack after: result of partial invocation
  116790. //
  116791. // This operation pops off a context, invokes a partial with that context,
  116792. // and pushes the result of the invocation back.
  116793. invokePartial: function invokePartial(isDynamic, name, indent) {
  116794. var params = [],
  116795. options = this.setupParams(name, 1, params);
  116796. if (isDynamic) {
  116797. name = this.popStack();
  116798. delete options.name;
  116799. }
  116800. if (indent) {
  116801. options.indent = JSON.stringify(indent);
  116802. }
  116803. options.helpers = 'helpers';
  116804. options.partials = 'partials';
  116805. options.decorators = 'container.decorators';
  116806. if (!isDynamic) {
  116807. params.unshift(this.nameLookup('partials', name, 'partial'));
  116808. } else {
  116809. params.unshift(name);
  116810. }
  116811. if (this.options.compat) {
  116812. options.depths = 'depths';
  116813. }
  116814. options = this.objectLiteral(options);
  116815. params.push(options);
  116816. this.push(this.source.functionCall('container.invokePartial', '', params));
  116817. },
  116818. // [assignToHash]
  116819. //
  116820. // On stack, before: value, ..., hash, ...
  116821. // On stack, after: ..., hash, ...
  116822. //
  116823. // Pops a value off the stack and assigns it to the current hash
  116824. assignToHash: function assignToHash(key) {
  116825. var value = this.popStack(),
  116826. context = undefined,
  116827. type = undefined,
  116828. id = undefined;
  116829. if (this.trackIds) {
  116830. id = this.popStack();
  116831. }
  116832. if (this.stringParams) {
  116833. type = this.popStack();
  116834. context = this.popStack();
  116835. }
  116836. var hash = this.hash;
  116837. if (context) {
  116838. hash.contexts[key] = context;
  116839. }
  116840. if (type) {
  116841. hash.types[key] = type;
  116842. }
  116843. if (id) {
  116844. hash.ids[key] = id;
  116845. }
  116846. hash.values[key] = value;
  116847. },
  116848. pushId: function pushId(type, name, child) {
  116849. if (type === 'BlockParam') {
  116850. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  116851. } else if (type === 'PathExpression') {
  116852. this.pushString(name);
  116853. } else if (type === 'SubExpression') {
  116854. this.pushStackLiteral('true');
  116855. } else {
  116856. this.pushStackLiteral('null');
  116857. }
  116858. },
  116859. // HELPERS
  116860. compiler: JavaScriptCompiler,
  116861. compileChildren: function compileChildren(environment, options) {
  116862. var children = environment.children,
  116863. child = undefined,
  116864. compiler = undefined;
  116865. for (var i = 0, l = children.length; i < l; i++) {
  116866. child = children[i];
  116867. compiler = new this.compiler(); // eslint-disable-line new-cap
  116868. var existing = this.matchExistingProgram(child);
  116869. if (existing == null) {
  116870. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  116871. var index = this.context.programs.length;
  116872. child.index = index;
  116873. child.name = 'program' + index;
  116874. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  116875. this.context.decorators[index] = compiler.decorators;
  116876. this.context.environments[index] = child;
  116877. this.useDepths = this.useDepths || compiler.useDepths;
  116878. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  116879. child.useDepths = this.useDepths;
  116880. child.useBlockParams = this.useBlockParams;
  116881. } else {
  116882. child.index = existing.index;
  116883. child.name = 'program' + existing.index;
  116884. this.useDepths = this.useDepths || existing.useDepths;
  116885. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  116886. }
  116887. }
  116888. },
  116889. matchExistingProgram: function matchExistingProgram(child) {
  116890. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  116891. var environment = this.context.environments[i];
  116892. if (environment && environment.equals(child)) {
  116893. return environment;
  116894. }
  116895. }
  116896. },
  116897. programExpression: function programExpression(guid) {
  116898. var child = this.environment.children[guid],
  116899. programParams = [child.index, 'data', child.blockParams];
  116900. if (this.useBlockParams || this.useDepths) {
  116901. programParams.push('blockParams');
  116902. }
  116903. if (this.useDepths) {
  116904. programParams.push('depths');
  116905. }
  116906. return 'container.program(' + programParams.join(', ') + ')';
  116907. },
  116908. useRegister: function useRegister(name) {
  116909. if (!this.registers[name]) {
  116910. this.registers[name] = true;
  116911. this.registers.list.push(name);
  116912. }
  116913. },
  116914. push: function push(expr) {
  116915. if (!(expr instanceof Literal)) {
  116916. expr = this.source.wrap(expr);
  116917. }
  116918. this.inlineStack.push(expr);
  116919. return expr;
  116920. },
  116921. pushStackLiteral: function pushStackLiteral(item) {
  116922. this.push(new Literal(item));
  116923. },
  116924. pushSource: function pushSource(source) {
  116925. if (this.pendingContent) {
  116926. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  116927. this.pendingContent = undefined;
  116928. }
  116929. if (source) {
  116930. this.source.push(source);
  116931. }
  116932. },
  116933. replaceStack: function replaceStack(callback) {
  116934. var prefix = ['('],
  116935. stack = undefined,
  116936. createdStack = undefined,
  116937. usedLiteral = undefined;
  116938. /* istanbul ignore next */
  116939. if (!this.isInline()) {
  116940. throw new _exception2['default']('replaceStack on non-inline');
  116941. }
  116942. // We want to merge the inline statement into the replacement statement via ','
  116943. var top = this.popStack(true);
  116944. if (top instanceof Literal) {
  116945. // Literals do not need to be inlined
  116946. stack = [top.value];
  116947. prefix = ['(', stack];
  116948. usedLiteral = true;
  116949. } else {
  116950. // Get or create the current stack name for use by the inline
  116951. createdStack = true;
  116952. var _name = this.incrStack();
  116953. prefix = ['((', this.push(_name), ' = ', top, ')'];
  116954. stack = this.topStack();
  116955. }
  116956. var item = callback.call(this, stack);
  116957. if (!usedLiteral) {
  116958. this.popStack();
  116959. }
  116960. if (createdStack) {
  116961. this.stackSlot--;
  116962. }
  116963. this.push(prefix.concat(item, ')'));
  116964. },
  116965. incrStack: function incrStack() {
  116966. this.stackSlot++;
  116967. if (this.stackSlot > this.stackVars.length) {
  116968. this.stackVars.push('stack' + this.stackSlot);
  116969. }
  116970. return this.topStackName();
  116971. },
  116972. topStackName: function topStackName() {
  116973. return 'stack' + this.stackSlot;
  116974. },
  116975. flushInline: function flushInline() {
  116976. var inlineStack = this.inlineStack;
  116977. this.inlineStack = [];
  116978. for (var i = 0, len = inlineStack.length; i < len; i++) {
  116979. var entry = inlineStack[i];
  116980. /* istanbul ignore if */
  116981. if (entry instanceof Literal) {
  116982. this.compileStack.push(entry);
  116983. } else {
  116984. var stack = this.incrStack();
  116985. this.pushSource([stack, ' = ', entry, ';']);
  116986. this.compileStack.push(stack);
  116987. }
  116988. }
  116989. },
  116990. isInline: function isInline() {
  116991. return this.inlineStack.length;
  116992. },
  116993. popStack: function popStack(wrapped) {
  116994. var inline = this.isInline(),
  116995. item = (inline ? this.inlineStack : this.compileStack).pop();
  116996. if (!wrapped && item instanceof Literal) {
  116997. return item.value;
  116998. } else {
  116999. if (!inline) {
  117000. /* istanbul ignore next */
  117001. if (!this.stackSlot) {
  117002. throw new _exception2['default']('Invalid stack pop');
  117003. }
  117004. this.stackSlot--;
  117005. }
  117006. return item;
  117007. }
  117008. },
  117009. topStack: function topStack() {
  117010. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  117011. item = stack[stack.length - 1];
  117012. /* istanbul ignore if */
  117013. if (item instanceof Literal) {
  117014. return item.value;
  117015. } else {
  117016. return item;
  117017. }
  117018. },
  117019. contextName: function contextName(context) {
  117020. if (this.useDepths && context) {
  117021. return 'depths[' + context + ']';
  117022. } else {
  117023. return 'depth' + context;
  117024. }
  117025. },
  117026. quotedString: function quotedString(str) {
  117027. return this.source.quotedString(str);
  117028. },
  117029. objectLiteral: function objectLiteral(obj) {
  117030. return this.source.objectLiteral(obj);
  117031. },
  117032. aliasable: function aliasable(name) {
  117033. var ret = this.aliases[name];
  117034. if (ret) {
  117035. ret.referenceCount++;
  117036. return ret;
  117037. }
  117038. ret = this.aliases[name] = this.source.wrap(name);
  117039. ret.aliasable = true;
  117040. ret.referenceCount = 1;
  117041. return ret;
  117042. },
  117043. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  117044. var params = [],
  117045. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  117046. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  117047. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  117048. return {
  117049. params: params,
  117050. paramsInit: paramsInit,
  117051. name: foundHelper,
  117052. callParams: [callContext].concat(params)
  117053. };
  117054. },
  117055. setupParams: function setupParams(helper, paramSize, params) {
  117056. var options = {},
  117057. contexts = [],
  117058. types = [],
  117059. ids = [],
  117060. objectArgs = !params,
  117061. param = undefined;
  117062. if (objectArgs) {
  117063. params = [];
  117064. }
  117065. options.name = this.quotedString(helper);
  117066. options.hash = this.popStack();
  117067. if (this.trackIds) {
  117068. options.hashIds = this.popStack();
  117069. }
  117070. if (this.stringParams) {
  117071. options.hashTypes = this.popStack();
  117072. options.hashContexts = this.popStack();
  117073. }
  117074. var inverse = this.popStack(),
  117075. program = this.popStack();
  117076. // Avoid setting fn and inverse if neither are set. This allows
  117077. // helpers to do a check for `if (options.fn)`
  117078. if (program || inverse) {
  117079. options.fn = program || 'container.noop';
  117080. options.inverse = inverse || 'container.noop';
  117081. }
  117082. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  117083. // so we need to pop them off the stack in reverse order
  117084. var i = paramSize;
  117085. while (i--) {
  117086. param = this.popStack();
  117087. params[i] = param;
  117088. if (this.trackIds) {
  117089. ids[i] = this.popStack();
  117090. }
  117091. if (this.stringParams) {
  117092. types[i] = this.popStack();
  117093. contexts[i] = this.popStack();
  117094. }
  117095. }
  117096. if (objectArgs) {
  117097. options.args = this.source.generateArray(params);
  117098. }
  117099. if (this.trackIds) {
  117100. options.ids = this.source.generateArray(ids);
  117101. }
  117102. if (this.stringParams) {
  117103. options.types = this.source.generateArray(types);
  117104. options.contexts = this.source.generateArray(contexts);
  117105. }
  117106. if (this.options.data) {
  117107. options.data = 'data';
  117108. }
  117109. if (this.useBlockParams) {
  117110. options.blockParams = 'blockParams';
  117111. }
  117112. return options;
  117113. },
  117114. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  117115. var options = this.setupParams(helper, paramSize, params);
  117116. options = this.objectLiteral(options);
  117117. if (useRegister) {
  117118. this.useRegister('options');
  117119. params.push('options');
  117120. return ['options=', options];
  117121. } else if (params) {
  117122. params.push(options);
  117123. return '';
  117124. } else {
  117125. return options;
  117126. }
  117127. }
  117128. };
  117129. (function () {
  117130. var reservedWords = ('break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false').split(' ');
  117131. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  117132. for (var i = 0, l = reservedWords.length; i < l; i++) {
  117133. compilerWords[reservedWords[i]] = true;
  117134. }
  117135. })();
  117136. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  117137. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  117138. };
  117139. function strictLookup(requireTerminal, compiler, parts, type) {
  117140. var stack = compiler.popStack(),
  117141. i = 0,
  117142. len = parts.length;
  117143. if (requireTerminal) {
  117144. len--;
  117145. }
  117146. for (; i < len; i++) {
  117147. stack = compiler.nameLookup(stack, parts[i], type);
  117148. }
  117149. if (requireTerminal) {
  117150. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  117151. } else {
  117152. return stack;
  117153. }
  117154. }
  117155. exports['default'] = JavaScriptCompiler;
  117156. module.exports = exports['default'];
  117157. /***/ }),
  117158. /* 43 */
  117159. /***/ (function(module, exports, __webpack_require__) {
  117160. /* global define */
  117161. 'use strict';
  117162. exports.__esModule = true;
  117163. var _utils = __webpack_require__(5);
  117164. var SourceNode = undefined;
  117165. try {
  117166. /* istanbul ignore next */
  117167. if (false) {
  117168. // We don't support this in AMD environments. For these environments, we asusme that
  117169. // they are running on the browser and thus have no need for the source-map library.
  117170. var SourceMap = require('source-map');
  117171. SourceNode = SourceMap.SourceNode;
  117172. }
  117173. } catch (err) {}
  117174. /* NOP */
  117175. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  117176. if (!SourceNode) {
  117177. SourceNode = function (line, column, srcFile, chunks) {
  117178. this.src = '';
  117179. if (chunks) {
  117180. this.add(chunks);
  117181. }
  117182. };
  117183. /* istanbul ignore next */
  117184. SourceNode.prototype = {
  117185. add: function add(chunks) {
  117186. if (_utils.isArray(chunks)) {
  117187. chunks = chunks.join('');
  117188. }
  117189. this.src += chunks;
  117190. },
  117191. prepend: function prepend(chunks) {
  117192. if (_utils.isArray(chunks)) {
  117193. chunks = chunks.join('');
  117194. }
  117195. this.src = chunks + this.src;
  117196. },
  117197. toStringWithSourceMap: function toStringWithSourceMap() {
  117198. return { code: this.toString() };
  117199. },
  117200. toString: function toString() {
  117201. return this.src;
  117202. }
  117203. };
  117204. }
  117205. function castChunk(chunk, codeGen, loc) {
  117206. if (_utils.isArray(chunk)) {
  117207. var ret = [];
  117208. for (var i = 0, len = chunk.length; i < len; i++) {
  117209. ret.push(codeGen.wrap(chunk[i], loc));
  117210. }
  117211. return ret;
  117212. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  117213. // Handle primitives that the SourceNode will throw up on
  117214. return chunk + '';
  117215. }
  117216. return chunk;
  117217. }
  117218. function CodeGen(srcFile) {
  117219. this.srcFile = srcFile;
  117220. this.source = [];
  117221. }
  117222. CodeGen.prototype = {
  117223. isEmpty: function isEmpty() {
  117224. return !this.source.length;
  117225. },
  117226. prepend: function prepend(source, loc) {
  117227. this.source.unshift(this.wrap(source, loc));
  117228. },
  117229. push: function push(source, loc) {
  117230. this.source.push(this.wrap(source, loc));
  117231. },
  117232. merge: function merge() {
  117233. var source = this.empty();
  117234. this.each(function (line) {
  117235. source.add([' ', line, '\n']);
  117236. });
  117237. return source;
  117238. },
  117239. each: function each(iter) {
  117240. for (var i = 0, len = this.source.length; i < len; i++) {
  117241. iter(this.source[i]);
  117242. }
  117243. },
  117244. empty: function empty() {
  117245. var loc = this.currentLocation || { start: {} };
  117246. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  117247. },
  117248. wrap: function wrap(chunk) {
  117249. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  117250. if (chunk instanceof SourceNode) {
  117251. return chunk;
  117252. }
  117253. chunk = castChunk(chunk, this, loc);
  117254. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  117255. },
  117256. functionCall: function functionCall(fn, type, params) {
  117257. params = this.generateList(params);
  117258. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  117259. },
  117260. quotedString: function quotedString(str) {
  117261. return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
  117262. .replace(/\u2029/g, '\\u2029') + '"';
  117263. },
  117264. objectLiteral: function objectLiteral(obj) {
  117265. var pairs = [];
  117266. for (var key in obj) {
  117267. if (obj.hasOwnProperty(key)) {
  117268. var value = castChunk(obj[key], this);
  117269. if (value !== 'undefined') {
  117270. pairs.push([this.quotedString(key), ':', value]);
  117271. }
  117272. }
  117273. }
  117274. var ret = this.generateList(pairs);
  117275. ret.prepend('{');
  117276. ret.add('}');
  117277. return ret;
  117278. },
  117279. generateList: function generateList(entries) {
  117280. var ret = this.empty();
  117281. for (var i = 0, len = entries.length; i < len; i++) {
  117282. if (i) {
  117283. ret.add(',');
  117284. }
  117285. ret.add(castChunk(entries[i], this));
  117286. }
  117287. return ret;
  117288. },
  117289. generateArray: function generateArray(entries) {
  117290. var ret = this.generateList(entries);
  117291. ret.prepend('[');
  117292. ret.add(']');
  117293. return ret;
  117294. }
  117295. };
  117296. exports['default'] = CodeGen;
  117297. module.exports = exports['default'];
  117298. /***/ })
  117299. /******/ ])
  117300. });
  117301. ;
  117302. /***/ }),
  117303. /* 63 */
  117304. /***/ (function(module, exports, __webpack_require__) {
  117305. "use strict";
  117306. Object.defineProperty(exports, "__esModule", { value: true });
  117307. /**
  117308. * The EventManager is in charge of registering user interctions with the viewer.
  117309. * It is used in the TemplateManager
  117310. */
  117311. var EventManager = /** @class */ (function () {
  117312. function EventManager(_templateManager) {
  117313. var _this = this;
  117314. this._templateManager = _templateManager;
  117315. this._callbacksContainer = {};
  117316. this._templateManager.onEventTriggered.add(function (eventData) {
  117317. _this._eventTriggered(eventData);
  117318. });
  117319. }
  117320. /**
  117321. * Register a new callback to a specific template.
  117322. * The best example for the usage can be found in the DefaultViewer
  117323. *
  117324. * @param templateName the templateName to register the event to
  117325. * @param callback The callback to be executed
  117326. * @param eventType the type of event to register
  117327. * @param selector an optional selector. if not defined the parent object in the template will be selected
  117328. */
  117329. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  117330. if (!this._callbacksContainer[templateName]) {
  117331. this._callbacksContainer[templateName] = [];
  117332. }
  117333. this._callbacksContainer[templateName].push({
  117334. eventType: eventType,
  117335. callback: callback,
  117336. selector: selector
  117337. });
  117338. };
  117339. /**
  117340. * This will remove a registered event from the defined template.
  117341. * Each one of the variables apart from the template name are optional, but one must be provided.
  117342. *
  117343. * @param templateName the templateName
  117344. * @param callback the callback to remove (optional)
  117345. * @param eventType the event type to remove (optional)
  117346. * @param selector the selector from which to remove the event (optional)
  117347. */
  117348. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  117349. var callbackDefs = this._callbacksContainer[templateName] || [];
  117350. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  117351. };
  117352. EventManager.prototype._eventTriggered = function (data) {
  117353. var templateName = data.template.name;
  117354. var eventType = data.event.type;
  117355. var selector = data.selector;
  117356. var callbackDefs = this._callbacksContainer[templateName] || [];
  117357. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  117358. callbackDef.callback(data);
  117359. });
  117360. };
  117361. /**
  117362. * Dispose the event manager
  117363. */
  117364. EventManager.prototype.dispose = function () {
  117365. this._callbacksContainer = {};
  117366. };
  117367. return EventManager;
  117368. }());
  117369. exports.EventManager = EventManager;
  117370. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBaUI7UUFDakQsSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztRQUM5QixJQUFJLENBQUMsZ0JBQWdCLENBQUMsZ0JBQWdCLENBQUMsR0FBRyxDQUFDLFVBQUEsU0FBUztZQUNoRCxLQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsQ0FBQyxDQUFDO1FBQ3BDLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUVEOzs7Ozs7OztPQVFHO0lBQ0ksdUNBQWdC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UFDLEtBQUssQ0FBQyxJQUFJLENBQUM7UUFDaEMsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQztRQUU3QixJQUFJLFlBQVksR0FBRyxJQUFJLENBQUMsbUJBQW1CLENBQUMsWUFBWSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQ2hFLFlBQVksQ0FBQyxNQUFNLENBQUMsVUFBQSxXQUFXLElBQUksT0FBQSxDQUFDLENBQUMsV0FBVyxDQUFDLFNBQVMsSUFBSSxXQUFXLENBQUMsU0FBUyxLQUFLLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLENBQUMsUUFBUSxJQUFJLFdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxXQUFXO1lBQ25MLFdBQVcsQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  117371. /***/ }),
  117372. /* 64 */
  117373. /***/ (function(module, exports, __webpack_require__) {
  117374. /*!
  117375. * PEP v0.4.3 | https://github.com/jquery/PEP
  117376. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  117377. */
  117378. (function (global, factory) {
  117379. true ? module.exports = factory() :
  117380. typeof define === 'function' && define.amd ? define(factory) :
  117381. (global.PointerEventsPolyfill = factory());
  117382. }(this, function () { 'use strict';
  117383. /**
  117384. * This is the constructor for new PointerEvents.
  117385. *
  117386. * New Pointer Events must be given a type, and an optional dictionary of
  117387. * initialization properties.
  117388. *
  117389. * Due to certain platform requirements, events returned from the constructor
  117390. * identify as MouseEvents.
  117391. *
  117392. * @constructor
  117393. * @param {String} inType The type of the event to create.
  117394. * @param {Object} [inDict] An optional dictionary of initial event properties.
  117395. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  117396. */
  117397. var MOUSE_PROPS = [
  117398. 'bubbles',
  117399. 'cancelable',
  117400. 'view',
  117401. 'detail',
  117402. 'screenX',
  117403. 'screenY',
  117404. 'clientX',
  117405. 'clientY',
  117406. 'ctrlKey',
  117407. 'altKey',
  117408. 'shiftKey',
  117409. 'metaKey',
  117410. 'button',
  117411. 'relatedTarget',
  117412. 'pageX',
  117413. 'pageY'
  117414. ];
  117415. var MOUSE_DEFAULTS = [
  117416. false,
  117417. false,
  117418. null,
  117419. null,
  117420. 0,
  117421. 0,
  117422. 0,
  117423. 0,
  117424. false,
  117425. false,
  117426. false,
  117427. false,
  117428. 0,
  117429. null,
  117430. 0,
  117431. 0
  117432. ];
  117433. function PointerEvent(inType, inDict) {
  117434. inDict = inDict || Object.create(null);
  117435. var e = document.createEvent('Event');
  117436. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  117437. // define inherited MouseEvent properties
  117438. // skip bubbles and cancelable since they're set above in initEvent()
  117439. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  117440. p = MOUSE_PROPS[i];
  117441. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  117442. }
  117443. e.buttons = inDict.buttons || 0;
  117444. // Spec requires that pointers without pressure specified use 0.5 for down
  117445. // state and 0 for up state.
  117446. var pressure = 0;
  117447. if (inDict.pressure && e.buttons) {
  117448. pressure = inDict.pressure;
  117449. } else {
  117450. pressure = e.buttons ? 0.5 : 0;
  117451. }
  117452. // add x/y properties aliased to clientX/Y
  117453. e.x = e.clientX;
  117454. e.y = e.clientY;
  117455. // define the properties of the PointerEvent interface
  117456. e.pointerId = inDict.pointerId || 0;
  117457. e.width = inDict.width || 0;
  117458. e.height = inDict.height || 0;
  117459. e.pressure = pressure;
  117460. e.tiltX = inDict.tiltX || 0;
  117461. e.tiltY = inDict.tiltY || 0;
  117462. e.twist = inDict.twist || 0;
  117463. e.tangentialPressure = inDict.tangentialPressure || 0;
  117464. e.pointerType = inDict.pointerType || '';
  117465. e.hwTimestamp = inDict.hwTimestamp || 0;
  117466. e.isPrimary = inDict.isPrimary || false;
  117467. return e;
  117468. }
  117469. /**
  117470. * This module implements a map of pointer states
  117471. */
  117472. var USE_MAP = window.Map && window.Map.prototype.forEach;
  117473. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  117474. function SparseArrayMap() {
  117475. this.array = [];
  117476. this.size = 0;
  117477. }
  117478. SparseArrayMap.prototype = {
  117479. set: function(k, v) {
  117480. if (v === undefined) {
  117481. return this.delete(k);
  117482. }
  117483. if (!this.has(k)) {
  117484. this.size++;
  117485. }
  117486. this.array[k] = v;
  117487. },
  117488. has: function(k) {
  117489. return this.array[k] !== undefined;
  117490. },
  117491. delete: function(k) {
  117492. if (this.has(k)) {
  117493. delete this.array[k];
  117494. this.size--;
  117495. }
  117496. },
  117497. get: function(k) {
  117498. return this.array[k];
  117499. },
  117500. clear: function() {
  117501. this.array.length = 0;
  117502. this.size = 0;
  117503. },
  117504. // return value, key, map
  117505. forEach: function(callback, thisArg) {
  117506. return this.array.forEach(function(v, k) {
  117507. callback.call(thisArg, v, k, this);
  117508. }, this);
  117509. }
  117510. };
  117511. var CLONE_PROPS = [
  117512. // MouseEvent
  117513. 'bubbles',
  117514. 'cancelable',
  117515. 'view',
  117516. 'detail',
  117517. 'screenX',
  117518. 'screenY',
  117519. 'clientX',
  117520. 'clientY',
  117521. 'ctrlKey',
  117522. 'altKey',
  117523. 'shiftKey',
  117524. 'metaKey',
  117525. 'button',
  117526. 'relatedTarget',
  117527. // DOM Level 3
  117528. 'buttons',
  117529. // PointerEvent
  117530. 'pointerId',
  117531. 'width',
  117532. 'height',
  117533. 'pressure',
  117534. 'tiltX',
  117535. 'tiltY',
  117536. 'pointerType',
  117537. 'hwTimestamp',
  117538. 'isPrimary',
  117539. // event instance
  117540. 'type',
  117541. 'target',
  117542. 'currentTarget',
  117543. 'which',
  117544. 'pageX',
  117545. 'pageY',
  117546. 'timeStamp'
  117547. ];
  117548. var CLONE_DEFAULTS = [
  117549. // MouseEvent
  117550. false,
  117551. false,
  117552. null,
  117553. null,
  117554. 0,
  117555. 0,
  117556. 0,
  117557. 0,
  117558. false,
  117559. false,
  117560. false,
  117561. false,
  117562. 0,
  117563. null,
  117564. // DOM Level 3
  117565. 0,
  117566. // PointerEvent
  117567. 0,
  117568. 0,
  117569. 0,
  117570. 0,
  117571. 0,
  117572. 0,
  117573. '',
  117574. 0,
  117575. false,
  117576. // event instance
  117577. '',
  117578. null,
  117579. null,
  117580. 0,
  117581. 0,
  117582. 0,
  117583. 0
  117584. ];
  117585. var BOUNDARY_EVENTS = {
  117586. 'pointerover': 1,
  117587. 'pointerout': 1,
  117588. 'pointerenter': 1,
  117589. 'pointerleave': 1
  117590. };
  117591. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  117592. /**
  117593. * This module is for normalizing events. Mouse and Touch events will be
  117594. * collected here, and fire PointerEvents that have the same semantics, no
  117595. * matter the source.
  117596. * Events fired:
  117597. * - pointerdown: a pointing is added
  117598. * - pointerup: a pointer is removed
  117599. * - pointermove: a pointer is moved
  117600. * - pointerover: a pointer crosses into an element
  117601. * - pointerout: a pointer leaves an element
  117602. * - pointercancel: a pointer will no longer generate events
  117603. */
  117604. var dispatcher = {
  117605. pointermap: new PointerMap(),
  117606. eventMap: Object.create(null),
  117607. captureInfo: Object.create(null),
  117608. // Scope objects for native events.
  117609. // This exists for ease of testing.
  117610. eventSources: Object.create(null),
  117611. eventSourceList: [],
  117612. /**
  117613. * Add a new event source that will generate pointer events.
  117614. *
  117615. * `inSource` must contain an array of event names named `events`, and
  117616. * functions with the names specified in the `events` array.
  117617. * @param {string} name A name for the event source
  117618. * @param {Object} source A new source of platform events.
  117619. */
  117620. registerSource: function(name, source) {
  117621. var s = source;
  117622. var newEvents = s.events;
  117623. if (newEvents) {
  117624. newEvents.forEach(function(e) {
  117625. if (s[e]) {
  117626. this.eventMap[e] = s[e].bind(s);
  117627. }
  117628. }, this);
  117629. this.eventSources[name] = s;
  117630. this.eventSourceList.push(s);
  117631. }
  117632. },
  117633. register: function(element) {
  117634. var l = this.eventSourceList.length;
  117635. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  117636. // call eventsource register
  117637. es.register.call(es, element);
  117638. }
  117639. },
  117640. unregister: function(element) {
  117641. var l = this.eventSourceList.length;
  117642. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  117643. // call eventsource register
  117644. es.unregister.call(es, element);
  117645. }
  117646. },
  117647. contains: /*scope.external.contains || */function(container, contained) {
  117648. try {
  117649. return container.contains(contained);
  117650. } catch (ex) {
  117651. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  117652. return false;
  117653. }
  117654. },
  117655. // EVENTS
  117656. down: function(inEvent) {
  117657. inEvent.bubbles = true;
  117658. this.fireEvent('pointerdown', inEvent);
  117659. },
  117660. move: function(inEvent) {
  117661. inEvent.bubbles = true;
  117662. this.fireEvent('pointermove', inEvent);
  117663. },
  117664. up: function(inEvent) {
  117665. inEvent.bubbles = true;
  117666. this.fireEvent('pointerup', inEvent);
  117667. },
  117668. enter: function(inEvent) {
  117669. inEvent.bubbles = false;
  117670. this.fireEvent('pointerenter', inEvent);
  117671. },
  117672. leave: function(inEvent) {
  117673. inEvent.bubbles = false;
  117674. this.fireEvent('pointerleave', inEvent);
  117675. },
  117676. over: function(inEvent) {
  117677. inEvent.bubbles = true;
  117678. this.fireEvent('pointerover', inEvent);
  117679. },
  117680. out: function(inEvent) {
  117681. inEvent.bubbles = true;
  117682. this.fireEvent('pointerout', inEvent);
  117683. },
  117684. cancel: function(inEvent) {
  117685. inEvent.bubbles = true;
  117686. this.fireEvent('pointercancel', inEvent);
  117687. },
  117688. leaveOut: function(event) {
  117689. this.out(event);
  117690. this.propagate(event, this.leave, false);
  117691. },
  117692. enterOver: function(event) {
  117693. this.over(event);
  117694. this.propagate(event, this.enter, true);
  117695. },
  117696. // LISTENER LOGIC
  117697. eventHandler: function(inEvent) {
  117698. // This is used to prevent multiple dispatch of pointerevents from
  117699. // platform events. This can happen when two elements in different scopes
  117700. // are set up to create pointer events, which is relevant to Shadow DOM.
  117701. if (inEvent._handledByPE) {
  117702. return;
  117703. }
  117704. var type = inEvent.type;
  117705. var fn = this.eventMap && this.eventMap[type];
  117706. if (fn) {
  117707. fn(inEvent);
  117708. }
  117709. inEvent._handledByPE = true;
  117710. },
  117711. // set up event listeners
  117712. listen: function(target, events) {
  117713. events.forEach(function(e) {
  117714. this.addEvent(target, e);
  117715. }, this);
  117716. },
  117717. // remove event listeners
  117718. unlisten: function(target, events) {
  117719. events.forEach(function(e) {
  117720. this.removeEvent(target, e);
  117721. }, this);
  117722. },
  117723. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  117724. target.addEventListener(eventName, this.boundHandler);
  117725. },
  117726. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  117727. target.removeEventListener(eventName, this.boundHandler);
  117728. },
  117729. // EVENT CREATION AND TRACKING
  117730. /**
  117731. * Creates a new Event of type `inType`, based on the information in
  117732. * `inEvent`.
  117733. *
  117734. * @param {string} inType A string representing the type of event to create
  117735. * @param {Event} inEvent A platform event with a target
  117736. * @return {Event} A PointerEvent of type `inType`
  117737. */
  117738. makeEvent: function(inType, inEvent) {
  117739. // relatedTarget must be null if pointer is captured
  117740. if (this.captureInfo[inEvent.pointerId]) {
  117741. inEvent.relatedTarget = null;
  117742. }
  117743. var e = new PointerEvent(inType, inEvent);
  117744. if (inEvent.preventDefault) {
  117745. e.preventDefault = inEvent.preventDefault;
  117746. }
  117747. e._target = e._target || inEvent.target;
  117748. return e;
  117749. },
  117750. // make and dispatch an event in one call
  117751. fireEvent: function(inType, inEvent) {
  117752. var e = this.makeEvent(inType, inEvent);
  117753. return this.dispatchEvent(e);
  117754. },
  117755. /**
  117756. * Returns a snapshot of inEvent, with writable properties.
  117757. *
  117758. * @param {Event} inEvent An event that contains properties to copy.
  117759. * @return {Object} An object containing shallow copies of `inEvent`'s
  117760. * properties.
  117761. */
  117762. cloneEvent: function(inEvent) {
  117763. var eventCopy = Object.create(null);
  117764. var p;
  117765. for (var i = 0; i < CLONE_PROPS.length; i++) {
  117766. p = CLONE_PROPS[i];
  117767. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  117768. // Work around SVGInstanceElement shadow tree
  117769. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  117770. // This is the behavior implemented by Firefox.
  117771. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  117772. if (eventCopy[p] instanceof SVGElementInstance) {
  117773. eventCopy[p] = eventCopy[p].correspondingUseElement;
  117774. }
  117775. }
  117776. }
  117777. // keep the semantics of preventDefault
  117778. if (inEvent.preventDefault) {
  117779. eventCopy.preventDefault = function() {
  117780. inEvent.preventDefault();
  117781. };
  117782. }
  117783. return eventCopy;
  117784. },
  117785. getTarget: function(inEvent) {
  117786. var capture = this.captureInfo[inEvent.pointerId];
  117787. if (!capture) {
  117788. return inEvent._target;
  117789. }
  117790. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  117791. return capture;
  117792. }
  117793. },
  117794. propagate: function(event, fn, propagateDown) {
  117795. var target = event.target;
  117796. var targets = [];
  117797. // Order of conditions due to document.contains() missing in IE.
  117798. while (target !== document && !target.contains(event.relatedTarget)) {
  117799. targets.push(target);
  117800. target = target.parentNode;
  117801. // Touch: Do not propagate if node is detached.
  117802. if (!target) {
  117803. return;
  117804. }
  117805. }
  117806. if (propagateDown) {
  117807. targets.reverse();
  117808. }
  117809. targets.forEach(function(target) {
  117810. event.target = target;
  117811. fn.call(this, event);
  117812. }, this);
  117813. },
  117814. setCapture: function(inPointerId, inTarget, skipDispatch) {
  117815. if (this.captureInfo[inPointerId]) {
  117816. this.releaseCapture(inPointerId, skipDispatch);
  117817. }
  117818. this.captureInfo[inPointerId] = inTarget;
  117819. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  117820. document.addEventListener('pointerup', this.implicitRelease);
  117821. document.addEventListener('pointercancel', this.implicitRelease);
  117822. var e = new PointerEvent('gotpointercapture');
  117823. e.pointerId = inPointerId;
  117824. e._target = inTarget;
  117825. if (!skipDispatch) {
  117826. this.asyncDispatchEvent(e);
  117827. }
  117828. },
  117829. releaseCapture: function(inPointerId, skipDispatch) {
  117830. var t = this.captureInfo[inPointerId];
  117831. if (!t) {
  117832. return;
  117833. }
  117834. this.captureInfo[inPointerId] = undefined;
  117835. document.removeEventListener('pointerup', this.implicitRelease);
  117836. document.removeEventListener('pointercancel', this.implicitRelease);
  117837. var e = new PointerEvent('lostpointercapture');
  117838. e.pointerId = inPointerId;
  117839. e._target = t;
  117840. if (!skipDispatch) {
  117841. this.asyncDispatchEvent(e);
  117842. }
  117843. },
  117844. /**
  117845. * Dispatches the event to its target.
  117846. *
  117847. * @param {Event} inEvent The event to be dispatched.
  117848. * @return {Boolean} True if an event handler returns true, false otherwise.
  117849. */
  117850. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  117851. var t = this.getTarget(inEvent);
  117852. if (t) {
  117853. return t.dispatchEvent(inEvent);
  117854. }
  117855. },
  117856. asyncDispatchEvent: function(inEvent) {
  117857. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  117858. }
  117859. };
  117860. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  117861. var targeting = {
  117862. shadow: function(inEl) {
  117863. if (inEl) {
  117864. return inEl.shadowRoot || inEl.webkitShadowRoot;
  117865. }
  117866. },
  117867. canTarget: function(shadow) {
  117868. return shadow && Boolean(shadow.elementFromPoint);
  117869. },
  117870. targetingShadow: function(inEl) {
  117871. var s = this.shadow(inEl);
  117872. if (this.canTarget(s)) {
  117873. return s;
  117874. }
  117875. },
  117876. olderShadow: function(shadow) {
  117877. var os = shadow.olderShadowRoot;
  117878. if (!os) {
  117879. var se = shadow.querySelector('shadow');
  117880. if (se) {
  117881. os = se.olderShadowRoot;
  117882. }
  117883. }
  117884. return os;
  117885. },
  117886. allShadows: function(element) {
  117887. var shadows = [];
  117888. var s = this.shadow(element);
  117889. while (s) {
  117890. shadows.push(s);
  117891. s = this.olderShadow(s);
  117892. }
  117893. return shadows;
  117894. },
  117895. searchRoot: function(inRoot, x, y) {
  117896. if (inRoot) {
  117897. var t = inRoot.elementFromPoint(x, y);
  117898. var st, sr;
  117899. // is element a shadow host?
  117900. sr = this.targetingShadow(t);
  117901. while (sr) {
  117902. // find the the element inside the shadow root
  117903. st = sr.elementFromPoint(x, y);
  117904. if (!st) {
  117905. // check for older shadows
  117906. sr = this.olderShadow(sr);
  117907. } else {
  117908. // shadowed element may contain a shadow root
  117909. var ssr = this.targetingShadow(st);
  117910. return this.searchRoot(ssr, x, y) || st;
  117911. }
  117912. }
  117913. // light dom element is the target
  117914. return t;
  117915. }
  117916. },
  117917. owner: function(element) {
  117918. var s = element;
  117919. // walk up until you hit the shadow root or document
  117920. while (s.parentNode) {
  117921. s = s.parentNode;
  117922. }
  117923. // the owner element is expected to be a Document or ShadowRoot
  117924. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  117925. s = document;
  117926. }
  117927. return s;
  117928. },
  117929. findTarget: function(inEvent) {
  117930. var x = inEvent.clientX;
  117931. var y = inEvent.clientY;
  117932. // if the listener is in the shadow root, it is much faster to start there
  117933. var s = this.owner(inEvent.target);
  117934. // if x, y is not in this root, fall back to document search
  117935. if (!s.elementFromPoint(x, y)) {
  117936. s = document;
  117937. }
  117938. return this.searchRoot(s, x, y);
  117939. }
  117940. };
  117941. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  117942. var map = Array.prototype.map.call.bind(Array.prototype.map);
  117943. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  117944. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  117945. var MO = window.MutationObserver || window.WebKitMutationObserver;
  117946. var SELECTOR = '[touch-action]';
  117947. var OBSERVER_INIT = {
  117948. subtree: true,
  117949. childList: true,
  117950. attributes: true,
  117951. attributeOldValue: true,
  117952. attributeFilter: ['touch-action']
  117953. };
  117954. function Installer(add, remove, changed, binder) {
  117955. this.addCallback = add.bind(binder);
  117956. this.removeCallback = remove.bind(binder);
  117957. this.changedCallback = changed.bind(binder);
  117958. if (MO) {
  117959. this.observer = new MO(this.mutationWatcher.bind(this));
  117960. }
  117961. }
  117962. Installer.prototype = {
  117963. watchSubtree: function(target) {
  117964. // Only watch scopes that can target find, as these are top-level.
  117965. // Otherwise we can see duplicate additions and removals that add noise.
  117966. //
  117967. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  117968. // a removal without an insertion when a node is redistributed among
  117969. // shadows. Since it all ends up correct in the document, watching only
  117970. // the document will yield the correct mutations to watch.
  117971. if (this.observer && targeting.canTarget(target)) {
  117972. this.observer.observe(target, OBSERVER_INIT);
  117973. }
  117974. },
  117975. enableOnSubtree: function(target) {
  117976. this.watchSubtree(target);
  117977. if (target === document && document.readyState !== 'complete') {
  117978. this.installOnLoad();
  117979. } else {
  117980. this.installNewSubtree(target);
  117981. }
  117982. },
  117983. installNewSubtree: function(target) {
  117984. forEach(this.findElements(target), this.addElement, this);
  117985. },
  117986. findElements: function(target) {
  117987. if (target.querySelectorAll) {
  117988. return target.querySelectorAll(SELECTOR);
  117989. }
  117990. return [];
  117991. },
  117992. removeElement: function(el) {
  117993. this.removeCallback(el);
  117994. },
  117995. addElement: function(el) {
  117996. this.addCallback(el);
  117997. },
  117998. elementChanged: function(el, oldValue) {
  117999. this.changedCallback(el, oldValue);
  118000. },
  118001. concatLists: function(accum, list) {
  118002. return accum.concat(toArray(list));
  118003. },
  118004. // register all touch-action = none nodes on document load
  118005. installOnLoad: function() {
  118006. document.addEventListener('readystatechange', function() {
  118007. if (document.readyState === 'complete') {
  118008. this.installNewSubtree(document);
  118009. }
  118010. }.bind(this));
  118011. },
  118012. isElement: function(n) {
  118013. return n.nodeType === Node.ELEMENT_NODE;
  118014. },
  118015. flattenMutationTree: function(inNodes) {
  118016. // find children with touch-action
  118017. var tree = map(inNodes, this.findElements, this);
  118018. // make sure the added nodes are accounted for
  118019. tree.push(filter(inNodes, this.isElement));
  118020. // flatten the list
  118021. return tree.reduce(this.concatLists, []);
  118022. },
  118023. mutationWatcher: function(mutations) {
  118024. mutations.forEach(this.mutationHandler, this);
  118025. },
  118026. mutationHandler: function(m) {
  118027. if (m.type === 'childList') {
  118028. var added = this.flattenMutationTree(m.addedNodes);
  118029. added.forEach(this.addElement, this);
  118030. var removed = this.flattenMutationTree(m.removedNodes);
  118031. removed.forEach(this.removeElement, this);
  118032. } else if (m.type === 'attributes') {
  118033. this.elementChanged(m.target, m.oldValue);
  118034. }
  118035. }
  118036. };
  118037. function shadowSelector(v) {
  118038. return 'body /shadow-deep/ ' + selector(v);
  118039. }
  118040. function selector(v) {
  118041. return '[touch-action="' + v + '"]';
  118042. }
  118043. function rule(v) {
  118044. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  118045. }
  118046. var attrib2css = [
  118047. 'none',
  118048. 'auto',
  118049. 'pan-x',
  118050. 'pan-y',
  118051. {
  118052. rule: 'pan-x pan-y',
  118053. selectors: [
  118054. 'pan-x pan-y',
  118055. 'pan-y pan-x'
  118056. ]
  118057. }
  118058. ];
  118059. var styles = '';
  118060. // only install stylesheet if the browser has touch action support
  118061. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  118062. // only add shadow selectors if shadowdom is supported
  118063. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  118064. function applyAttributeStyles() {
  118065. if (hasNativePE) {
  118066. attrib2css.forEach(function(r) {
  118067. if (String(r) === r) {
  118068. styles += selector(r) + rule(r) + '\n';
  118069. if (hasShadowRoot) {
  118070. styles += shadowSelector(r) + rule(r) + '\n';
  118071. }
  118072. } else {
  118073. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  118074. if (hasShadowRoot) {
  118075. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  118076. }
  118077. }
  118078. });
  118079. var el = document.createElement('style');
  118080. el.textContent = styles;
  118081. document.head.appendChild(el);
  118082. }
  118083. }
  118084. var pointermap = dispatcher.pointermap;
  118085. // radius around touchend that swallows mouse events
  118086. var DEDUP_DIST = 25;
  118087. // left, middle, right, back, forward
  118088. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  118089. var HAS_BUTTONS = false;
  118090. try {
  118091. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  118092. } catch (e) {}
  118093. // handler block for native mouse events
  118094. var mouseEvents = {
  118095. POINTER_ID: 1,
  118096. POINTER_TYPE: 'mouse',
  118097. events: [
  118098. 'mousedown',
  118099. 'mousemove',
  118100. 'mouseup',
  118101. 'mouseover',
  118102. 'mouseout'
  118103. ],
  118104. register: function(target) {
  118105. dispatcher.listen(target, this.events);
  118106. },
  118107. unregister: function(target) {
  118108. dispatcher.unlisten(target, this.events);
  118109. },
  118110. lastTouches: [],
  118111. // collide with the global mouse listener
  118112. isEventSimulatedFromTouch: function(inEvent) {
  118113. var lts = this.lastTouches;
  118114. var x = inEvent.clientX;
  118115. var y = inEvent.clientY;
  118116. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  118117. // simulated mouse events will be swallowed near a primary touchend
  118118. var dx = Math.abs(x - t.x);
  118119. var dy = Math.abs(y - t.y);
  118120. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  118121. return true;
  118122. }
  118123. }
  118124. },
  118125. prepareEvent: function(inEvent) {
  118126. var e = dispatcher.cloneEvent(inEvent);
  118127. // forward mouse preventDefault
  118128. var pd = e.preventDefault;
  118129. e.preventDefault = function() {
  118130. inEvent.preventDefault();
  118131. pd();
  118132. };
  118133. e.pointerId = this.POINTER_ID;
  118134. e.isPrimary = true;
  118135. e.pointerType = this.POINTER_TYPE;
  118136. return e;
  118137. },
  118138. prepareButtonsForMove: function(e, inEvent) {
  118139. var p = pointermap.get(this.POINTER_ID);
  118140. // Update buttons state after possible out-of-document mouseup.
  118141. if (inEvent.which === 0 || !p) {
  118142. e.buttons = 0;
  118143. } else {
  118144. e.buttons = p.buttons;
  118145. }
  118146. inEvent.buttons = e.buttons;
  118147. },
  118148. mousedown: function(inEvent) {
  118149. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118150. var p = pointermap.get(this.POINTER_ID);
  118151. var e = this.prepareEvent(inEvent);
  118152. if (!HAS_BUTTONS) {
  118153. e.buttons = BUTTON_TO_BUTTONS[e.button];
  118154. if (p) { e.buttons |= p.buttons; }
  118155. inEvent.buttons = e.buttons;
  118156. }
  118157. pointermap.set(this.POINTER_ID, inEvent);
  118158. if (!p || p.buttons === 0) {
  118159. dispatcher.down(e);
  118160. } else {
  118161. dispatcher.move(e);
  118162. }
  118163. }
  118164. },
  118165. mousemove: function(inEvent) {
  118166. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118167. var e = this.prepareEvent(inEvent);
  118168. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  118169. e.button = -1;
  118170. pointermap.set(this.POINTER_ID, inEvent);
  118171. dispatcher.move(e);
  118172. }
  118173. },
  118174. mouseup: function(inEvent) {
  118175. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118176. var p = pointermap.get(this.POINTER_ID);
  118177. var e = this.prepareEvent(inEvent);
  118178. if (!HAS_BUTTONS) {
  118179. var up = BUTTON_TO_BUTTONS[e.button];
  118180. // Produces wrong state of buttons in Browsers without `buttons` support
  118181. // when a mouse button that was pressed outside the document is released
  118182. // inside and other buttons are still pressed down.
  118183. e.buttons = p ? p.buttons & ~up : 0;
  118184. inEvent.buttons = e.buttons;
  118185. }
  118186. pointermap.set(this.POINTER_ID, inEvent);
  118187. // Support: Firefox <=44 only
  118188. // FF Ubuntu includes the lifted button in the `buttons` property on
  118189. // mouseup.
  118190. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  118191. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  118192. if (e.buttons === 0) {
  118193. dispatcher.up(e);
  118194. } else {
  118195. dispatcher.move(e);
  118196. }
  118197. }
  118198. },
  118199. mouseover: function(inEvent) {
  118200. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118201. var e = this.prepareEvent(inEvent);
  118202. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  118203. e.button = -1;
  118204. pointermap.set(this.POINTER_ID, inEvent);
  118205. dispatcher.enterOver(e);
  118206. }
  118207. },
  118208. mouseout: function(inEvent) {
  118209. if (!this.isEventSimulatedFromTouch(inEvent)) {
  118210. var e = this.prepareEvent(inEvent);
  118211. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  118212. e.button = -1;
  118213. dispatcher.leaveOut(e);
  118214. }
  118215. },
  118216. cancel: function(inEvent) {
  118217. var e = this.prepareEvent(inEvent);
  118218. dispatcher.cancel(e);
  118219. this.deactivateMouse();
  118220. },
  118221. deactivateMouse: function() {
  118222. pointermap.delete(this.POINTER_ID);
  118223. }
  118224. };
  118225. var captureInfo = dispatcher.captureInfo;
  118226. var findTarget = targeting.findTarget.bind(targeting);
  118227. var allShadows = targeting.allShadows.bind(targeting);
  118228. var pointermap$1 = dispatcher.pointermap;
  118229. // This should be long enough to ignore compat mouse events made by touch
  118230. var DEDUP_TIMEOUT = 2500;
  118231. var CLICK_COUNT_TIMEOUT = 200;
  118232. var ATTRIB = 'touch-action';
  118233. var INSTALLER;
  118234. // handler block for native touch events
  118235. var touchEvents = {
  118236. events: [
  118237. 'touchstart',
  118238. 'touchmove',
  118239. 'touchend',
  118240. 'touchcancel'
  118241. ],
  118242. register: function(target) {
  118243. INSTALLER.enableOnSubtree(target);
  118244. },
  118245. unregister: function() {
  118246. // TODO(dfreedman): is it worth it to disconnect the MO?
  118247. },
  118248. elementAdded: function(el) {
  118249. var a = el.getAttribute(ATTRIB);
  118250. var st = this.touchActionToScrollType(a);
  118251. if (st) {
  118252. el._scrollType = st;
  118253. dispatcher.listen(el, this.events);
  118254. // set touch-action on shadows as well
  118255. allShadows(el).forEach(function(s) {
  118256. s._scrollType = st;
  118257. dispatcher.listen(s, this.events);
  118258. }, this);
  118259. }
  118260. },
  118261. elementRemoved: function(el) {
  118262. el._scrollType = undefined;
  118263. dispatcher.unlisten(el, this.events);
  118264. // remove touch-action from shadow
  118265. allShadows(el).forEach(function(s) {
  118266. s._scrollType = undefined;
  118267. dispatcher.unlisten(s, this.events);
  118268. }, this);
  118269. },
  118270. elementChanged: function(el, oldValue) {
  118271. var a = el.getAttribute(ATTRIB);
  118272. var st = this.touchActionToScrollType(a);
  118273. var oldSt = this.touchActionToScrollType(oldValue);
  118274. // simply update scrollType if listeners are already established
  118275. if (st && oldSt) {
  118276. el._scrollType = st;
  118277. allShadows(el).forEach(function(s) {
  118278. s._scrollType = st;
  118279. }, this);
  118280. } else if (oldSt) {
  118281. this.elementRemoved(el);
  118282. } else if (st) {
  118283. this.elementAdded(el);
  118284. }
  118285. },
  118286. scrollTypes: {
  118287. EMITTER: 'none',
  118288. XSCROLLER: 'pan-x',
  118289. YSCROLLER: 'pan-y',
  118290. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  118291. },
  118292. touchActionToScrollType: function(touchAction) {
  118293. var t = touchAction;
  118294. var st = this.scrollTypes;
  118295. if (t === 'none') {
  118296. return 'none';
  118297. } else if (t === st.XSCROLLER) {
  118298. return 'X';
  118299. } else if (t === st.YSCROLLER) {
  118300. return 'Y';
  118301. } else if (st.SCROLLER.exec(t)) {
  118302. return 'XY';
  118303. }
  118304. },
  118305. POINTER_TYPE: 'touch',
  118306. firstTouch: null,
  118307. isPrimaryTouch: function(inTouch) {
  118308. return this.firstTouch === inTouch.identifier;
  118309. },
  118310. setPrimaryTouch: function(inTouch) {
  118311. // set primary touch if there no pointers, or the only pointer is the mouse
  118312. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  118313. this.firstTouch = inTouch.identifier;
  118314. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  118315. this.scrolling = false;
  118316. this.cancelResetClickCount();
  118317. }
  118318. },
  118319. removePrimaryPointer: function(inPointer) {
  118320. if (inPointer.isPrimary) {
  118321. this.firstTouch = null;
  118322. this.firstXY = null;
  118323. this.resetClickCount();
  118324. }
  118325. },
  118326. clickCount: 0,
  118327. resetId: null,
  118328. resetClickCount: function() {
  118329. var fn = function() {
  118330. this.clickCount = 0;
  118331. this.resetId = null;
  118332. }.bind(this);
  118333. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  118334. },
  118335. cancelResetClickCount: function() {
  118336. if (this.resetId) {
  118337. clearTimeout(this.resetId);
  118338. }
  118339. },
  118340. typeToButtons: function(type) {
  118341. var ret = 0;
  118342. if (type === 'touchstart' || type === 'touchmove') {
  118343. ret = 1;
  118344. }
  118345. return ret;
  118346. },
  118347. touchToPointer: function(inTouch) {
  118348. var cte = this.currentTouchEvent;
  118349. var e = dispatcher.cloneEvent(inTouch);
  118350. // We reserve pointerId 1 for Mouse.
  118351. // Touch identifiers can start at 0.
  118352. // Add 2 to the touch identifier for compatibility.
  118353. var id = e.pointerId = inTouch.identifier + 2;
  118354. e.target = captureInfo[id] || findTarget(e);
  118355. e.bubbles = true;
  118356. e.cancelable = true;
  118357. e.detail = this.clickCount;
  118358. e.button = 0;
  118359. e.buttons = this.typeToButtons(cte.type);
  118360. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  118361. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  118362. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  118363. e.isPrimary = this.isPrimaryTouch(inTouch);
  118364. e.pointerType = this.POINTER_TYPE;
  118365. // forward modifier keys
  118366. e.altKey = cte.altKey;
  118367. e.ctrlKey = cte.ctrlKey;
  118368. e.metaKey = cte.metaKey;
  118369. e.shiftKey = cte.shiftKey;
  118370. // forward touch preventDefaults
  118371. var self = this;
  118372. e.preventDefault = function() {
  118373. self.scrolling = false;
  118374. self.firstXY = null;
  118375. cte.preventDefault();
  118376. };
  118377. return e;
  118378. },
  118379. processTouches: function(inEvent, inFunction) {
  118380. var tl = inEvent.changedTouches;
  118381. this.currentTouchEvent = inEvent;
  118382. for (var i = 0, t; i < tl.length; i++) {
  118383. t = tl[i];
  118384. inFunction.call(this, this.touchToPointer(t));
  118385. }
  118386. },
  118387. // For single axis scrollers, determines whether the element should emit
  118388. // pointer events or behave as a scroller
  118389. shouldScroll: function(inEvent) {
  118390. if (this.firstXY) {
  118391. var ret;
  118392. var scrollAxis = inEvent.currentTarget._scrollType;
  118393. if (scrollAxis === 'none') {
  118394. // this element is a touch-action: none, should never scroll
  118395. ret = false;
  118396. } else if (scrollAxis === 'XY') {
  118397. // this element should always scroll
  118398. ret = true;
  118399. } else {
  118400. var t = inEvent.changedTouches[0];
  118401. // check the intended scroll axis, and other axis
  118402. var a = scrollAxis;
  118403. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  118404. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  118405. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  118406. // if delta in the scroll axis > delta other axis, scroll instead of
  118407. // making events
  118408. ret = da >= doa;
  118409. }
  118410. this.firstXY = null;
  118411. return ret;
  118412. }
  118413. },
  118414. findTouch: function(inTL, inId) {
  118415. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  118416. if (t.identifier === inId) {
  118417. return true;
  118418. }
  118419. }
  118420. },
  118421. // In some instances, a touchstart can happen without a touchend. This
  118422. // leaves the pointermap in a broken state.
  118423. // Therefore, on every touchstart, we remove the touches that did not fire a
  118424. // touchend event.
  118425. // To keep state globally consistent, we fire a
  118426. // pointercancel for this "abandoned" touch
  118427. vacuumTouches: function(inEvent) {
  118428. var tl = inEvent.touches;
  118429. // pointermap.size should be < tl.length here, as the touchstart has not
  118430. // been processed yet.
  118431. if (pointermap$1.size >= tl.length) {
  118432. var d = [];
  118433. pointermap$1.forEach(function(value, key) {
  118434. // Never remove pointerId == 1, which is mouse.
  118435. // Touch identifiers are 2 smaller than their pointerId, which is the
  118436. // index in pointermap.
  118437. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  118438. var p = value.out;
  118439. d.push(p);
  118440. }
  118441. }, this);
  118442. d.forEach(this.cancelOut, this);
  118443. }
  118444. },
  118445. touchstart: function(inEvent) {
  118446. this.vacuumTouches(inEvent);
  118447. this.setPrimaryTouch(inEvent.changedTouches[0]);
  118448. this.dedupSynthMouse(inEvent);
  118449. if (!this.scrolling) {
  118450. this.clickCount++;
  118451. this.processTouches(inEvent, this.overDown);
  118452. }
  118453. },
  118454. overDown: function(inPointer) {
  118455. pointermap$1.set(inPointer.pointerId, {
  118456. target: inPointer.target,
  118457. out: inPointer,
  118458. outTarget: inPointer.target
  118459. });
  118460. dispatcher.enterOver(inPointer);
  118461. dispatcher.down(inPointer);
  118462. },
  118463. touchmove: function(inEvent) {
  118464. if (!this.scrolling) {
  118465. if (this.shouldScroll(inEvent)) {
  118466. this.scrolling = true;
  118467. this.touchcancel(inEvent);
  118468. } else {
  118469. inEvent.preventDefault();
  118470. this.processTouches(inEvent, this.moveOverOut);
  118471. }
  118472. }
  118473. },
  118474. moveOverOut: function(inPointer) {
  118475. var event = inPointer;
  118476. var pointer = pointermap$1.get(event.pointerId);
  118477. // a finger drifted off the screen, ignore it
  118478. if (!pointer) {
  118479. return;
  118480. }
  118481. var outEvent = pointer.out;
  118482. var outTarget = pointer.outTarget;
  118483. dispatcher.move(event);
  118484. if (outEvent && outTarget !== event.target) {
  118485. outEvent.relatedTarget = event.target;
  118486. event.relatedTarget = outTarget;
  118487. // recover from retargeting by shadow
  118488. outEvent.target = outTarget;
  118489. if (event.target) {
  118490. dispatcher.leaveOut(outEvent);
  118491. dispatcher.enterOver(event);
  118492. } else {
  118493. // clean up case when finger leaves the screen
  118494. event.target = outTarget;
  118495. event.relatedTarget = null;
  118496. this.cancelOut(event);
  118497. }
  118498. }
  118499. pointer.out = event;
  118500. pointer.outTarget = event.target;
  118501. },
  118502. touchend: function(inEvent) {
  118503. this.dedupSynthMouse(inEvent);
  118504. this.processTouches(inEvent, this.upOut);
  118505. },
  118506. upOut: function(inPointer) {
  118507. if (!this.scrolling) {
  118508. dispatcher.up(inPointer);
  118509. dispatcher.leaveOut(inPointer);
  118510. }
  118511. this.cleanUpPointer(inPointer);
  118512. },
  118513. touchcancel: function(inEvent) {
  118514. this.processTouches(inEvent, this.cancelOut);
  118515. },
  118516. cancelOut: function(inPointer) {
  118517. dispatcher.cancel(inPointer);
  118518. dispatcher.leaveOut(inPointer);
  118519. this.cleanUpPointer(inPointer);
  118520. },
  118521. cleanUpPointer: function(inPointer) {
  118522. pointermap$1.delete(inPointer.pointerId);
  118523. this.removePrimaryPointer(inPointer);
  118524. },
  118525. // prevent synth mouse events from creating pointer events
  118526. dedupSynthMouse: function(inEvent) {
  118527. var lts = mouseEvents.lastTouches;
  118528. var t = inEvent.changedTouches[0];
  118529. // only the primary finger will synth mouse events
  118530. if (this.isPrimaryTouch(t)) {
  118531. // remember x/y of last touch
  118532. var lt = { x: t.clientX, y: t.clientY };
  118533. lts.push(lt);
  118534. var fn = (function(lts, lt) {
  118535. var i = lts.indexOf(lt);
  118536. if (i > -1) {
  118537. lts.splice(i, 1);
  118538. }
  118539. }).bind(null, lts, lt);
  118540. setTimeout(fn, DEDUP_TIMEOUT);
  118541. }
  118542. }
  118543. };
  118544. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  118545. touchEvents.elementChanged, touchEvents);
  118546. var pointermap$2 = dispatcher.pointermap;
  118547. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  118548. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  118549. var msEvents = {
  118550. events: [
  118551. 'MSPointerDown',
  118552. 'MSPointerMove',
  118553. 'MSPointerUp',
  118554. 'MSPointerOut',
  118555. 'MSPointerOver',
  118556. 'MSPointerCancel',
  118557. 'MSGotPointerCapture',
  118558. 'MSLostPointerCapture'
  118559. ],
  118560. register: function(target) {
  118561. dispatcher.listen(target, this.events);
  118562. },
  118563. unregister: function(target) {
  118564. dispatcher.unlisten(target, this.events);
  118565. },
  118566. POINTER_TYPES: [
  118567. '',
  118568. 'unavailable',
  118569. 'touch',
  118570. 'pen',
  118571. 'mouse'
  118572. ],
  118573. prepareEvent: function(inEvent) {
  118574. var e = inEvent;
  118575. if (HAS_BITMAP_TYPE) {
  118576. e = dispatcher.cloneEvent(inEvent);
  118577. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  118578. }
  118579. return e;
  118580. },
  118581. cleanup: function(id) {
  118582. pointermap$2.delete(id);
  118583. },
  118584. MSPointerDown: function(inEvent) {
  118585. pointermap$2.set(inEvent.pointerId, inEvent);
  118586. var e = this.prepareEvent(inEvent);
  118587. dispatcher.down(e);
  118588. },
  118589. MSPointerMove: function(inEvent) {
  118590. var e = this.prepareEvent(inEvent);
  118591. dispatcher.move(e);
  118592. },
  118593. MSPointerUp: function(inEvent) {
  118594. var e = this.prepareEvent(inEvent);
  118595. dispatcher.up(e);
  118596. this.cleanup(inEvent.pointerId);
  118597. },
  118598. MSPointerOut: function(inEvent) {
  118599. var e = this.prepareEvent(inEvent);
  118600. dispatcher.leaveOut(e);
  118601. },
  118602. MSPointerOver: function(inEvent) {
  118603. var e = this.prepareEvent(inEvent);
  118604. dispatcher.enterOver(e);
  118605. },
  118606. MSPointerCancel: function(inEvent) {
  118607. var e = this.prepareEvent(inEvent);
  118608. dispatcher.cancel(e);
  118609. this.cleanup(inEvent.pointerId);
  118610. },
  118611. MSLostPointerCapture: function(inEvent) {
  118612. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  118613. dispatcher.dispatchEvent(e);
  118614. },
  118615. MSGotPointerCapture: function(inEvent) {
  118616. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  118617. dispatcher.dispatchEvent(e);
  118618. }
  118619. };
  118620. function applyPolyfill() {
  118621. // only activate if this platform does not have pointer events
  118622. if (!window.PointerEvent) {
  118623. window.PointerEvent = PointerEvent;
  118624. if (window.navigator.msPointerEnabled) {
  118625. var tp = window.navigator.msMaxTouchPoints;
  118626. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  118627. value: tp,
  118628. enumerable: true
  118629. });
  118630. dispatcher.registerSource('ms', msEvents);
  118631. } else {
  118632. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  118633. value: 0,
  118634. enumerable: true
  118635. });
  118636. dispatcher.registerSource('mouse', mouseEvents);
  118637. if (window.ontouchstart !== undefined) {
  118638. dispatcher.registerSource('touch', touchEvents);
  118639. }
  118640. }
  118641. dispatcher.register(document);
  118642. }
  118643. }
  118644. var n = window.navigator;
  118645. var s;
  118646. var r;
  118647. var h;
  118648. function assertActive(id) {
  118649. if (!dispatcher.pointermap.has(id)) {
  118650. var error = new Error('InvalidPointerId');
  118651. error.name = 'InvalidPointerId';
  118652. throw error;
  118653. }
  118654. }
  118655. function assertConnected(elem) {
  118656. var parent = elem.parentNode;
  118657. while (parent && parent !== elem.ownerDocument) {
  118658. parent = parent.parentNode;
  118659. }
  118660. if (!parent) {
  118661. var error = new Error('InvalidStateError');
  118662. error.name = 'InvalidStateError';
  118663. throw error;
  118664. }
  118665. }
  118666. function inActiveButtonState(id) {
  118667. var p = dispatcher.pointermap.get(id);
  118668. return p.buttons !== 0;
  118669. }
  118670. if (n.msPointerEnabled) {
  118671. s = function(pointerId) {
  118672. assertActive(pointerId);
  118673. assertConnected(this);
  118674. if (inActiveButtonState(pointerId)) {
  118675. dispatcher.setCapture(pointerId, this, true);
  118676. this.msSetPointerCapture(pointerId);
  118677. }
  118678. };
  118679. r = function(pointerId) {
  118680. assertActive(pointerId);
  118681. dispatcher.releaseCapture(pointerId, true);
  118682. this.msReleasePointerCapture(pointerId);
  118683. };
  118684. } else {
  118685. s = function setPointerCapture(pointerId) {
  118686. assertActive(pointerId);
  118687. assertConnected(this);
  118688. if (inActiveButtonState(pointerId)) {
  118689. dispatcher.setCapture(pointerId, this);
  118690. }
  118691. };
  118692. r = function releasePointerCapture(pointerId) {
  118693. assertActive(pointerId);
  118694. dispatcher.releaseCapture(pointerId);
  118695. };
  118696. }
  118697. h = function hasPointerCapture(pointerId) {
  118698. return !!dispatcher.captureInfo[pointerId];
  118699. };
  118700. function applyPolyfill$1() {
  118701. if (window.Element && !Element.prototype.setPointerCapture) {
  118702. Object.defineProperties(Element.prototype, {
  118703. 'setPointerCapture': {
  118704. value: s
  118705. },
  118706. 'releasePointerCapture': {
  118707. value: r
  118708. },
  118709. 'hasPointerCapture': {
  118710. value: h
  118711. }
  118712. });
  118713. }
  118714. }
  118715. applyAttributeStyles();
  118716. applyPolyfill();
  118717. applyPolyfill$1();
  118718. var pointerevents = {
  118719. dispatcher: dispatcher,
  118720. Installer: Installer,
  118721. PointerEvent: PointerEvent,
  118722. PointerMap: PointerMap,
  118723. targetFinding: targeting
  118724. };
  118725. return pointerevents;
  118726. }));
  118727. /***/ }),
  118728. /* 65 */
  118729. /***/ (function(module, exports, __webpack_require__) {
  118730. "use strict";
  118731. Object.defineProperty(exports, "__esModule", { value: true });
  118732. var defaultViewer_1 = __webpack_require__(8);
  118733. var mappers_1 = __webpack_require__(3);
  118734. var globals_1 = __webpack_require__(4);
  118735. /**
  118736. * Will attach an init function the the DOMContentLoaded event.
  118737. * The init function will be removed automatically after the event was triggered.
  118738. */
  118739. function initListeners() {
  118740. document.addEventListener("DOMContentLoaded", init);
  118741. function init(event) {
  118742. document.removeEventListener("DOMContentLoaded", init);
  118743. if (globals_1.viewerGlobals.disableInit)
  118744. return;
  118745. InitTags();
  118746. }
  118747. }
  118748. exports.initListeners = initListeners;
  118749. /**
  118750. * Select all HTML tags on the page that match the selector and initialize a viewer
  118751. *
  118752. * @param selector the selector to initialize the viewer on (default is 'babylon')
  118753. */
  118754. function InitTags(selector) {
  118755. if (selector === void 0) { selector = 'babylon'; }
  118756. var elements = document.querySelectorAll(selector);
  118757. for (var i = 0; i < elements.length; ++i) {
  118758. var element = elements.item(i);
  118759. // get the html configuration
  118760. var configMapper = mappers_1.mapperManager.getMapper('dom');
  118761. var config = configMapper.map(element);
  118762. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  118763. }
  118764. }
  118765. exports.InitTags = InitTags;
  118766. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQWtCLEVBQUUsSUFBSSxDQUFDLENBQUM7UUFDdkQsSUFBSSx1QkFBYSxDQUFDLFdBQVc7WUFBRSxPQUFPO1FBQ3RDLFFBQVEsRUFBRSxDQUFDO0lBQ2YsQ0FBQztBQUNMLENBQUM7QUFQRCxzQ0FPQztBQUVEOzs7O0dBSUc7QUFDSCxrQkFBeUIsUUFBNEI7SUFBNUIseUJBQUEsRUFBQSxvQkFBNEI7SUFDakQsSUFBSSxRQUFRLEdBQUcsUUFBUSxDQUFDLGdCQUFnQixDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQ25ELEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFL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